├── requirements.txt ├── .DS_Store ├── RedisROS ├── .DS_Store ├── Endpoints │ ├── .DS_Store │ ├── Custom │ │ ├── ROS_Publisher │ │ │ ├── __init__.py │ │ │ └── ROS_publisher_module.py │ │ ├── ROS_Subscriber │ │ │ ├── __init__.py │ │ │ └── ROS_subscriber_module.py │ │ └── __init__.py │ ├── Core │ │ ├── .DS_Store │ │ ├── Timer │ │ │ ├── __init__.py │ │ │ ├── Timer.py │ │ │ └── Timer_module.py │ │ ├── Publisher │ │ │ ├── __init__.py │ │ │ ├── Publisher_module.py │ │ │ └── Publisher.py │ │ ├── Subscriber │ │ │ ├── __init__.py │ │ │ ├── Subscriber_module.py │ │ │ └── Subscriber.py │ │ ├── Shared_variable │ │ │ ├── __init__.py │ │ │ ├── Shared_variable_module.py │ │ │ └── Shared_variable.py │ │ ├── __init__.py │ │ └── Endpoint_abc.py │ └── __init__.py ├── Config.py ├── Nodes │ ├── __init__.py │ └── Clock.py ├── __init__.py ├── Async_timer.py ├── Callback_groups.py └── Node.py ├── setup.py ├── test.py ├── .gitignore ├── README.md └── LICENSE /requirements.txt: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /.DS_Store: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/vguillet/RedisROS/HEAD/.DS_Store -------------------------------------------------------------------------------- /RedisROS/.DS_Store: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/vguillet/RedisROS/HEAD/RedisROS/.DS_Store -------------------------------------------------------------------------------- /RedisROS/Endpoints/.DS_Store: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/vguillet/RedisROS/HEAD/RedisROS/Endpoints/.DS_Store -------------------------------------------------------------------------------- /RedisROS/Endpoints/Custom/ROS_Publisher/__init__.py: -------------------------------------------------------------------------------- 1 | from .ROS_publisher_module import ROS_publisher_module 2 | -------------------------------------------------------------------------------- /RedisROS/Endpoints/Custom/ROS_Subscriber/__init__.py: -------------------------------------------------------------------------------- 1 | from .ROS_subscriber_module import ROS_subscriber_module 2 | -------------------------------------------------------------------------------- /RedisROS/Endpoints/Core/.DS_Store: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/vguillet/RedisROS/HEAD/RedisROS/Endpoints/Core/.DS_Store -------------------------------------------------------------------------------- /RedisROS/Endpoints/Core/Timer/__init__.py: -------------------------------------------------------------------------------- 1 | # from .Timer import Timer 2 | # from .Timer_module import Timer_module 3 | -------------------------------------------------------------------------------- /RedisROS/Endpoints/Core/Publisher/__init__.py: -------------------------------------------------------------------------------- 1 | # from .Publisher import Publisher 2 | # from .Publisher_module import Publisher_module 3 | 4 | -------------------------------------------------------------------------------- /RedisROS/Endpoints/Core/Subscriber/__init__.py: -------------------------------------------------------------------------------- 1 | # from .Subscriber import Subscriber 2 | # from .Subscriber_module import Subscriber_module 3 | -------------------------------------------------------------------------------- /RedisROS/Endpoints/Custom/__init__.py: -------------------------------------------------------------------------------- 1 | 2 | # -> Import custom Endpoints 3 | from .ROS_Publisher import * 4 | from .ROS_Subscriber import * 5 | -------------------------------------------------------------------------------- /RedisROS/Endpoints/Core/Shared_variable/__init__.py: -------------------------------------------------------------------------------- 1 | # from .Shared_variable import Shared_variable 2 | # from .Shared_variable_module import Shared_variable_module 3 | -------------------------------------------------------------------------------- /RedisROS/Config.py: -------------------------------------------------------------------------------- 1 | 2 | # ------- Redis locks config 3 | expire_time = 10 4 | auto_renewal = True 5 | 6 | # ------- Block threadpoolexecutor 7 | worker_pool_size = 100 8 | -------------------------------------------------------------------------------- /RedisROS/Nodes/__init__.py: -------------------------------------------------------------------------------- 1 | 2 | # Import classes and functions 3 | from .Clock import Clock 4 | 5 | # Import submodules 6 | 7 | # -> Define public api 8 | __all__ = [ 9 | "Clock" 10 | ] 11 | -------------------------------------------------------------------------------- /RedisROS/Endpoints/__init__.py: -------------------------------------------------------------------------------- 1 | 2 | # Import classes and functions 3 | from .Core import * 4 | # from .Custom import * 5 | 6 | # Import submodules 7 | 8 | # -> Define public api 9 | # __all__ = [ 10 | # "" 11 | # ] 12 | -------------------------------------------------------------------------------- /RedisROS/__init__.py: -------------------------------------------------------------------------------- 1 | 2 | # Import classes and functions 3 | from RedisROS.Node import Node 4 | # from RedisROS.Config import * 5 | # from RedisROS.Callback_groups import * 6 | 7 | # Import submodules 8 | import RedisROS.Endpoints 9 | import RedisROS.Nodes 10 | 11 | # -> Define public api 12 | __all__ = [ 13 | 'Node', 14 | 'Endpoints', 15 | 'Nodes' 16 | ] 17 | -------------------------------------------------------------------------------- /RedisROS/Endpoints/Core/__init__.py: -------------------------------------------------------------------------------- 1 | 2 | # Import classes and functions 3 | from .Publisher.Publisher import Publisher 4 | from .Subscriber.Subscriber import Subscriber 5 | from .Shared_variable.Shared_variable import Shared_variable 6 | from .Timer.Timer import Timer 7 | 8 | from .Endpoint_abc import Endpoint_abc 9 | 10 | # Import submodules 11 | 12 | # -> Define public api 13 | __all__ = [ 14 | "Publisher", 15 | "Subscriber", 16 | "Shared_variable", 17 | "Timer" 18 | ] 19 | -------------------------------------------------------------------------------- /setup.py: -------------------------------------------------------------------------------- 1 | from setuptools import setup, find_packages 2 | 3 | from time 4 | 5 | # -> Fetch documentation from readme 6 | with open("README.md", "r") as fh: 7 | long_description = fh.read() 8 | 9 | setup( 10 | name="RedisROS", 11 | version="0.0.3", 12 | license="GNU GPLv3", 13 | description="A redis-based event-based ROS2-like library for python", 14 | long_description=long_description, 15 | long_description_content_type="text/markdown", 16 | url="https://github.com/vguillet/RedisROS", 17 | packages=find_packages(), 18 | install_requires=["redis", "python-redis-lock"], 19 | keywords=["ROS", "ROS2", "event-based", "python", "redis", "robotics"], 20 | python_requires=">= 3.8", 21 | author="Victor Guillet", 22 | author_email="victor.guillet@protonmail.com", 23 | classifiers=[ 24 | "Development Status :: 3 - Alpha", 25 | "Intended Audience :: Developers", 26 | "Programming Language :: Python :: 3", 27 | ] 28 | ) -------------------------------------------------------------------------------- /RedisROS/Async_timer.py: -------------------------------------------------------------------------------- 1 | import time 2 | from threading import Timer as ThreadTimer 3 | import random 4 | import string 5 | 6 | 7 | class Async_timer(ThreadTimer): 8 | def __init__(self, 9 | timer_period, 10 | callback, 11 | ref: str = None 12 | ): 13 | super().__init__(interval=timer_period, function=callback) 14 | 15 | # -> Create a unique ID for the timer 16 | if ref is None: 17 | self.ref = ''.join([random.choice(string.ascii_letters + string.digits) for _ in range(8)]) 18 | else: 19 | self.ref = ref 20 | 21 | # -> Initialise the timer properties 22 | self.timer_period = timer_period 23 | self.callback = callback 24 | 25 | def run(self): 26 | while not self.finished.wait(self.interval): 27 | self.function(*self.args, **self.kwargs) 28 | 29 | def destroy_endpoint(self) -> None: 30 | pass 31 | 32 | 33 | if __name__ == "__main__": 34 | def callback(): 35 | print("Hello World!") 36 | 37 | timer = Timer(timer_period=0.1, callback=callback) 38 | timer.run() 39 | 40 | -------------------------------------------------------------------------------- /RedisROS/Endpoints/Core/Timer/Timer.py: -------------------------------------------------------------------------------- 1 | import json 2 | from datetime import datetime 3 | import random 4 | import string 5 | 6 | from redis.commands.graph import Graph, Edge, Node 7 | from redis_lock import Lock 8 | 9 | from ..Endpoint_abc import Endpoint_abc 10 | 11 | 12 | class Timer(Endpoint_abc): 13 | def __init__(self, 14 | callback, 15 | timer_period: float = 1, 16 | ref: str = None, 17 | parent_node_ref: str = None, 18 | namespace: str = "", 19 | manual_spin: bool = False 20 | ): 21 | 22 | # -> Create a unique ID for the timer 23 | if ref is None: 24 | self.ref = ''.join([random.choice(string.ascii_letters + string.digits) for _ in range(8)]) 25 | else: 26 | self.ref = ref 27 | 28 | # -> Initialise the timer properties 29 | self.timer_period = timer_period 30 | self.callback = callback 31 | 32 | # -> Setup endpoint 33 | Endpoint_abc.__init__(self, 34 | parent_node_ref=parent_node_ref, 35 | namespace=namespace, 36 | manual_spin=manual_spin 37 | ) 38 | 39 | # TODO: Couple timer with run clock to ensure the desired timer_period is achieved 40 | if timer_period != 1: 41 | print(f"WARNING - {self.ref} : Timers time_period currently not implemented, timer will run at a rate of 1Hz per spin") 42 | 43 | def spin(self) -> None: 44 | # ----- Spin rate is larger than timer rate 45 | # if spin_rate > self.timer_period: 46 | 47 | # -> Call callback 48 | self.callback() 49 | 50 | # Placeholder methods 51 | def declare_endpoint(self) -> None: 52 | pass 53 | 54 | def destroy_endpoint(self) -> None: 55 | pass 56 | -------------------------------------------------------------------------------- /RedisROS/Nodes/Clock.py: -------------------------------------------------------------------------------- 1 | from tracemalloc import start 2 | from datetime import datetime 3 | from RedisROS import Node 4 | 5 | zero_datetime = datetime(year=1, month=1, day=1) 6 | 7 | 8 | class Clock(Node): 9 | def __init__(self, 10 | ref: str = "Clock", 11 | namespace: str = "", 12 | start_datetime: datetime = zero_datetime, 13 | clock_rate: float = 0.01, 14 | time_factor=1): 15 | Node.__init__( 16 | self, 17 | ref=ref, 18 | namespace=namespace, 19 | ) 20 | 21 | # ----- Setup clock 22 | self.real_start_datetime = datetime.now() 23 | self.sim_start_datetime = start_datetime 24 | 25 | self.clock_rate = clock_rate 26 | self.time_factor = time_factor 27 | 28 | self.datetime_publisher = self.create_publisher( 29 | msg_type=None, 30 | topic=ref 31 | ) 32 | 33 | # self.create_timer( 34 | # timer_period_sec=0.01, 35 | # callback=self.datetime_callback, 36 | # ref="Clock timer" 37 | # ) 38 | 39 | def datetime_callback(self): 40 | # -> Get real elapsed time 41 | delta_t = datetime.now() - self.real_start_datetime 42 | 43 | # -> Determine sim time 44 | sim_datetime = self.sim_start_datetime + delta_t * self.time_factor 45 | 46 | # -> Convert datetime to string 47 | sim_datetime_string = sim_datetime.strftime('%04d-%02d-%02d %02d:%02d:%02d.%06d' % ( 48 | sim_datetime.year, sim_datetime.month, sim_datetime.day, sim_datetime.hour, sim_datetime.minute, 49 | sim_datetime.second, sim_datetime.microsecond)) 50 | 51 | # -> Publish sim time 52 | self.datetime_publisher.publish(msg=sim_datetime_string) 53 | 54 | def run(self): 55 | # self.spin() 56 | 57 | timer = self.create_async_timer( 58 | timer_period_sec=self.clock_rate, 59 | callback=self.datetime_callback, 60 | ref="Clock timer" 61 | ) 62 | 63 | timer.start() 64 | 65 | -------------------------------------------------------------------------------- /RedisROS/Endpoints/Core/Endpoint_abc.py: -------------------------------------------------------------------------------- 1 | from abc import ABC, abstractmethod 2 | import random 3 | import string 4 | 5 | from redis import Redis 6 | 7 | 8 | class Endpoint_abc(ABC): 9 | def __init__(self, 10 | parent_node_ref: str, 11 | namespace: str = "", 12 | manual_spin: bool = False 13 | ): 14 | """ 15 | The base class for all endpoints 16 | 17 | :param parent_node_ref: The reference of the parent node 18 | """ 19 | 20 | # -> Generate a unique ID for the subscriber 21 | self.id = str(id(self)) 22 | 23 | # -> Set the parent node reference 24 | self.parent_node_ref = parent_node_ref 25 | self.parent_address = self.get_topic(topic_elements=[parent_node_ref]) 26 | 27 | # -> Set namespace/comm graph 28 | self.namespace = namespace 29 | 30 | # -> Set manual spin property 31 | self.manual_spin = manual_spin 32 | 33 | # -> Get comm_graph 34 | self.comm_graph = "Comm_graph" 35 | 36 | if self.namespace != "": 37 | self.comm_graph = self.get_topic(topic_elements=[namespace, self.comm_graph]) 38 | 39 | # -> Setup endpoint redis connection 40 | self.client = Redis(client_name=self.id) 41 | 42 | @staticmethod 43 | def get_topic(topic_elements: list): 44 | topic = "/" 45 | 46 | for topic_element in topic_elements: 47 | topic += f"{topic_element}/" 48 | 49 | if topic[0] == topic[1] and topic[0]: # TODO: Fix to also check for if == \ 50 | topic = topic[1:] 51 | 52 | return topic[:-1] 53 | 54 | @staticmethod 55 | def check_topic(topic): 56 | """ 57 | Check if the given topic is in the correct format 58 | """ 59 | 60 | # -> Check if topic starts with / 61 | if topic[0] != "/": 62 | raise ValueError(f"Topic must start with '/', current topic: {topic}") 63 | 64 | else: 65 | return topic 66 | 67 | @abstractmethod 68 | def spin(self) -> None: 69 | pass 70 | 71 | @abstractmethod 72 | def declare_endpoint(self) -> None: 73 | pass 74 | 75 | @abstractmethod 76 | def destroy_endpoint(self) -> None: 77 | pass 78 | -------------------------------------------------------------------------------- /RedisROS/Endpoints/Core/Timer/Timer_module.py: -------------------------------------------------------------------------------- 1 | 2 | from RedisROS.Endpoints import Timer 3 | from RedisROS.Callback_groups import MutuallyExclusiveCallbackGroup, ReentrantCallbackGroup 4 | 5 | 6 | class Timer_module: 7 | def __init__(self): 8 | pass 9 | 10 | @property 11 | def timers(self): 12 | """ 13 | Get timers that have been created on this node in every callback groups. 14 | """ 15 | # -> Get all the timers in every callback group 16 | timers = [] 17 | 18 | for callback_group in self.callbackgroups.values(): 19 | for callback in callback_group.callbacks: 20 | if isinstance(callback, Timer): 21 | timers.append(callback) 22 | 23 | # -> Return the list of timers 24 | return timers 25 | 26 | def create_timer(self, 27 | timer_period_sec: float, 28 | callback, 29 | manual_spin: bool = False, 30 | ref: str = None, 31 | callback_group: MutuallyExclusiveCallbackGroup or ReentrantCallbackGroup = None 32 | ) -> Timer: 33 | """ 34 | Create a timer that calls the callback function at the given rate. 35 | 36 | :param timer_period_sec: The period (s) of the timer. 37 | :param callback: A user-defined callback function that is called when the timer expires. 38 | """ 39 | 40 | # -> Create a timer 41 | new_timer = Timer( 42 | timer_period=timer_period_sec, 43 | callback=callback, 44 | manual_spin=manual_spin, 45 | ref=ref 46 | ) 47 | 48 | # -> Add the timer to the node dictionary timers 49 | if callback_group is None: 50 | self.callbackgroups["default_timer_callback_group"].add_callback(new_timer) 51 | else: 52 | callback_group.add_callback(new_timer) 53 | 54 | # -> Return the timer object 55 | return new_timer 56 | 57 | # ----------------- Destroyer 58 | def destroy_timer(self, timer: Timer) -> None: 59 | """ 60 | Destroy the given timer. 61 | """ 62 | # -> Destroy timer endpoint 63 | timer.destroy_endpoint() 64 | 65 | # -> Remove the timer from its callback group 66 | for callback_group in self.callbackgroups.values(): 67 | if callback_group.has_entity(timer): 68 | callback_group.remove_callback(timer) 69 | break -------------------------------------------------------------------------------- /RedisROS/Callback_groups.py: -------------------------------------------------------------------------------- 1 | from concurrent.futures import ThreadPoolExecutor 2 | from RedisROS.Config import * 3 | 4 | 5 | class CallbackGroup: 6 | def __init__(self, name: str = ""): 7 | """ 8 | Initialise the callback group 9 | 10 | :param name: The name of the callback group 11 | """ 12 | 13 | # -> Initialise the callback group properties 14 | self.name = name 15 | self.callbacks = [] 16 | 17 | def add_callback(self, callback): 18 | """ 19 | Add a callback to the callback group 20 | """ 21 | self.callbacks.append(callback) 22 | 23 | def remove_callback(self, callback): 24 | """ 25 | Remove a callback from the callback group 26 | """ 27 | self.callbacks.remove(callback) 28 | 29 | def has_entity(self, callback): 30 | """ 31 | Check if the given callback belongs to the callback group 32 | """ 33 | if callback in self.callbacks: 34 | return True 35 | else: 36 | return False 37 | 38 | def get_entities(self, entity_type): 39 | """ 40 | Get all the entities in the callback group of the given type 41 | """ 42 | publishers = [] 43 | for callback in self.callbacks: 44 | if isinstance(callback, entity_type): 45 | publishers.append(callback) 46 | return publishers 47 | 48 | 49 | class MutuallyExclusiveCallbackGroup(CallbackGroup): 50 | def __init__(self, name: str = ""): 51 | CallbackGroup.__init__(self, name=name) 52 | 53 | def spin(self) -> None: 54 | """ 55 | Spin the callbacks in the callback group in order 56 | """ 57 | 58 | for callback in self.callbacks: 59 | # -> If callback is not flagged as manual spin, spin 60 | if not callback.manual_spin: 61 | callback.spin() 62 | 63 | 64 | class ReentrantCallbackGroup(CallbackGroup): 65 | def __init__(self, name: str = ""): 66 | CallbackGroup.__init__(self, name=name) 67 | 68 | def spin(self) -> None: 69 | """ 70 | Spin the callbacks in the callback group in threads 71 | """ 72 | 73 | # -> Create a thread pool 74 | with ThreadPoolExecutor(max_workers=worker_pool_size) as executor: 75 | # -> Call the callbacks in the callback group in threads 76 | for callback in self.callbacks: 77 | # -> If callback is not flagged as manual spin, spin 78 | if not callback.manual_spin: 79 | executor.submit(callback.spin) 80 | -------------------------------------------------------------------------------- /RedisROS/Endpoints/Custom/ROS_Publisher/ROS_publisher_module.py: -------------------------------------------------------------------------------- 1 | 2 | from RedisROS.Endpoints import Publisher 3 | 4 | 5 | class ROS_publisher_module: 6 | def __init__(self): 7 | pass 8 | 9 | @property 10 | def ros_publishers(self) -> list[Publisher]: 11 | """ 12 | Get ros publishers that have been created on this node in ros callback groups. 13 | """ 14 | 15 | return self.callbackgroups["ros_callback_group"].get_publishers() 16 | 17 | # ----------------- Factory 18 | def create_ros_publisher(self, 19 | msg_type, 20 | topic: str, 21 | qos_profile=None) -> Publisher: 22 | """ 23 | Create a ros publisher for the given topic 24 | 25 | :param msg_type: The type of the message to be published 26 | :param topic: The topic to publish to 27 | :param qos_profile: The QoS profile to use 28 | """ 29 | 30 | # -> Create a publisher for the given topic 31 | new_publisher = Publisher( 32 | msg_type=msg_type, 33 | topic=self.namespace + topic, 34 | qos_profile=qos_profile, 35 | parent_node_ref=self.ref, 36 | comms_structure=self._comms_structure, 37 | comms_msgs=self._comms_msgs) 38 | 39 | # -> Add the publisher to the ros callback group 40 | self.callbackgroups["ros_callback_group"].add_callback(new_publisher) 41 | 42 | # -> Publish the ros publisher creation msg 43 | self.framework_msgs.publish( 44 | msg={ 45 | "Source": self.ref, 46 | "Type": "ROS_Publisher_Creation", 47 | "Memo": { 48 | "Topic": topic, 49 | } 50 | } 51 | ) 52 | 53 | # -> Return the publisher object 54 | return new_publisher 55 | 56 | # ----------------- Destroyer 57 | def destroy_ros_publisher(self, publisher: Publisher) -> None: 58 | """ 59 | Destroy the given publisher. 60 | """ 61 | # -> Destroy publisher endpoint 62 | publisher.destroy_endpoint() 63 | 64 | # -> Publish the ros publisher destruction msg 65 | self.framework_msgs.publish( 66 | msg={ 67 | "Source": self.ref, 68 | "Type": "ROS_Publisher_Destruction", 69 | "Memo": { 70 | "Topic": publisher.topic, 71 | } 72 | } 73 | ) 74 | 75 | # -> Remove the publisher from its callback group 76 | try: 77 | self.callbackgroups["ros_callback_group"].remove_callback(publisher) 78 | except: 79 | print("Error: Publisher not found in ros callback group") 80 | -------------------------------------------------------------------------------- /RedisROS/Endpoints/Custom/ROS_Subscriber/ROS_subscriber_module.py: -------------------------------------------------------------------------------- 1 | 2 | from RedisROS.Endpoints import Subscriber 3 | 4 | 5 | class ROS_subscriber_module: 6 | def __init__(self): 7 | pass 8 | 9 | @property 10 | def ros_subscribers(self) -> list[Subscriber]: 11 | """ 12 | Get ros subscribers that have been created on this node in ros callback groups. 13 | """ 14 | 15 | return self.callbackgroups["ros_callback_group"].get_subscribers() 16 | 17 | # ----------------- Factory 18 | def create_ros_subscriber(self, 19 | msg_type, 20 | topic: str, 21 | qos_profile=None) -> Subscriber: 22 | """ 23 | Create a ros subscriber for the given topic 24 | 25 | :param msg_type: The type of the message to be published 26 | :param topic: The topic to publish to 27 | :param qos_profile: The QoS profile to use 28 | """ 29 | 30 | # -> Create a subscriber for the given topic 31 | new_subscription = Subscriber( 32 | msg_type=msg_type, 33 | topic=self.namespace + topic, 34 | callback=callback, 35 | qos_profile=qos_profile, 36 | parent_node_ref=self.ref, 37 | comms_structure=self._comms_structure, 38 | comms_msgs=self._comms_msgs 39 | ) 40 | 41 | # -> Add the subscriber to the ros callback group 42 | self.callbackgroups["ros_callback_group"].add_callback(new_subscription) 43 | 44 | # -> Publish the ros subscriber creation msg 45 | self.framework_msgs.publish( 46 | msg={ 47 | "Source": self.ref, 48 | "Type": "ROS_Subscription_Creation", 49 | "Memo": { 50 | "Topic": topic, 51 | } 52 | } 53 | ) 54 | 55 | # -> Return the subscriber object 56 | return new_subscriber 57 | 58 | # ----------------- Destroyer 59 | def destroy_ros_subscriber(self, subscriber: Subscriber) -> None: 60 | """ 61 | Destroy the given subscriber. 62 | """ 63 | # -> Destroy subscriber endpoint 64 | subscriber.destroy_endpoint() 65 | 66 | # -> Publish the ros subscriber destruction msg 67 | self.framework_msgs.publish( 68 | msg={ 69 | "Source": self.ref, 70 | "Type": "ROS_Subscription_Destruction", 71 | "Memo": { 72 | "Topic": subscriber.topic, 73 | } 74 | } 75 | ) 76 | 77 | # -> Remove the subscriber from its callback group 78 | try: 79 | self.callbackgroups["ros_callback_group"].remove_callback(subscriber) 80 | except: 81 | print("Error: Subscriber not found in ros callback group") 82 | -------------------------------------------------------------------------------- /RedisROS/Endpoints/Core/Publisher/Publisher_module.py: -------------------------------------------------------------------------------- 1 | 2 | from RedisROS.Endpoints import Publisher 3 | from RedisROS.Callback_groups import MutuallyExclusiveCallbackGroup, ReentrantCallbackGroup 4 | 5 | 6 | class Publisher_module: 7 | def __init__(self): 8 | pass 9 | 10 | @property 11 | def publishers(self): 12 | """ 13 | Get publishers that have been created on this node in every callback groups. 14 | """ 15 | # -> Get all the publishers in every callback group 16 | publishers = [] 17 | 18 | for callback_group in self.callbackgroups.values(): 19 | for callback in callback_group.callbacks: 20 | if isinstance(callback, Publisher): 21 | publishers.append(callback) 22 | 23 | # -> Return the list of publishers 24 | return publishers 25 | 26 | # ----------------- Factory 27 | def create_publisher(self, 28 | msg_type, 29 | topic: str, 30 | manual_spin: bool = False, 31 | qos_profile=None, 32 | callback_group: MutuallyExclusiveCallbackGroup or ReentrantCallbackGroup = None 33 | ) -> Publisher: 34 | """ 35 | Create a publisher for the given topic 36 | 37 | :param msg_type: The type of the message to be published 38 | :param topic: The topic to publish to 39 | :param qos_profile: The QoS profile to use 40 | :param callback_group: The callback group for the publisher. If None, use the default publisher callback group is used. 41 | """ 42 | 43 | # -> Create a publisher for the given topic 44 | new_publisher = Publisher( 45 | msg_type=msg_type, 46 | topic=topic, 47 | qos_profile=qos_profile, 48 | manual_spin=manual_spin, 49 | parent_node_ref=self.ref, 50 | namespace=self.namespace 51 | ) 52 | 53 | # -> If not callback group is given, use the default publisher callback group 54 | if callback_group is None: 55 | self.callbackgroups["default_publisher_callback_group"].add_callback(new_publisher) 56 | else: 57 | callback_group.add_callback(new_publisher) 58 | 59 | # -> Return the publisher object 60 | return new_publisher 61 | 62 | # ----------------- Destroyer 63 | def destroy_publisher(self, publisher: Publisher) -> None: 64 | """ 65 | Destroy the given publisher. 66 | """ 67 | # -> Destroy publisher endpoint 68 | publisher.destroy_endpoint() 69 | 70 | # -> Remove the publisher from its callback group 71 | for callback_group in self.callbackgroups.values(): 72 | if callback_group.has_entity(publisher): 73 | callback_group.remove_callback(publisher) 74 | break 75 | -------------------------------------------------------------------------------- /RedisROS/Endpoints/Core/Subscriber/Subscriber_module.py: -------------------------------------------------------------------------------- 1 | from RedisROS.Endpoints import Subscriber 2 | from RedisROS.Callback_groups import MutuallyExclusiveCallbackGroup, ReentrantCallbackGroup 3 | 4 | 5 | class Subscriber_module: 6 | def __init__(self): 7 | pass 8 | 9 | @property 10 | def subscriptions(self): 11 | """ 12 | Get subscriptions that have been created on this node in every callback groups. 13 | """ 14 | # -> Get all the subscriptions in every callback group 15 | subscriptions = [] 16 | 17 | for callback_group in self.callbackgroups.values(): 18 | for callback in callback_group.callbacks: 19 | if isinstance(callback, Subscriber): 20 | subscriptions.append(callback) 21 | 22 | # -> Return the list of subscriptions 23 | return subscriptions 24 | 25 | # ----------------- Factory 26 | def create_subscription(self, 27 | msg_type, 28 | topic: str, 29 | callback, 30 | manual_spin: bool = False, 31 | qos_profile=None, 32 | callback_group: MutuallyExclusiveCallbackGroup or ReentrantCallbackGroup = None) -> Subscriber: 33 | """ 34 | Create a subscription for the given topic. 35 | Call the callback function when a message is received. 36 | 37 | :param msg_type: The type of the message to be received. 38 | :param topic: The topic to subscribe to. 39 | :param callback: The callback function to call when a message is received. 40 | :param qos_profile: The QoS profile to use. 41 | :param callback_group: The callback group for the subscription. If None, the default callback group is used. 42 | """ 43 | 44 | # -> Create a subscription for the given topic 45 | new_subscription = Subscriber( 46 | msg_type=msg_type, 47 | topic=topic, 48 | callback=callback, 49 | qos_profile=qos_profile, 50 | parent_node_ref=self.ref, 51 | namespace=self.namespace, 52 | manual_spin=manual_spin 53 | ) 54 | 55 | # -> If not callback group is given, use the default publisher callback group 56 | if callback_group is None: 57 | self.callbackgroups["default_subscriber_callback_group"].add_callback(new_subscription) 58 | else: 59 | callback_group.add_callback(new_subscription) 60 | 61 | # -> Return the subscription object 62 | return new_subscription 63 | 64 | # ----------------- Destroyer 65 | def destroy_subscription(self, subscriber: Subscriber) -> None: 66 | """ 67 | Destroy the given subscriber. 68 | """ 69 | 70 | # -> Destroy subscriber endpoint 71 | subscriber.destroy_endpoint() 72 | 73 | # -> Remove the subscriber from the corresponding callback group 74 | for callback_group in self.callbackgroups.values(): 75 | if callback_group.has_entity(subscriber): 76 | callback_group.remove_callback(subscriber) 77 | break -------------------------------------------------------------------------------- /test.py: -------------------------------------------------------------------------------- 1 | 2 | from concurrent.futures import ThreadPoolExecutor, thread 3 | from datetime import datetime 4 | import time 5 | 6 | from RedisROS.Nodes import Clock 7 | from RedisROS import Node 8 | 9 | NAMESPACE = "namespace" 10 | 11 | 12 | class test_pub(Node): 13 | def __init__(self, ref: str = "test_pub") -> None: 14 | super().__init__( 15 | ref=ref, 16 | namespace=NAMESPACE 17 | ) 18 | 19 | self.test_publisher = self.create_publisher( 20 | msg_type=None, 21 | topic="test_topic", 22 | ) 23 | 24 | self.create_timer( 25 | timer_period_sec=0.01, 26 | callback=self.test_callback 27 | ) 28 | 29 | def run(self): 30 | self.spin() 31 | 32 | # time.sleep(2) 33 | # self.default_spin_condition.set_value(value=False, instant=True) 34 | # test_timer.cancel() 35 | # self.destroy_timer(timer=test_timer) 36 | 37 | def test_callback(self): 38 | msg = f"Hello World! |{datetime.timestamp(datetime.now())}|" 39 | # print(f"\n-> Publishing message: {msg}") 40 | self.test_publisher.publish(msg, instant=False) 41 | 42 | 43 | class test_sub(Node): 44 | def __init__(self, ref: str = "test_sub") -> None: 45 | super().__init__( 46 | ref=ref, 47 | namespace=NAMESPACE 48 | ) 49 | 50 | self.test_subscription = self.create_subscription( 51 | msg_type=None, 52 | topic="test_topic", 53 | callback=self.test_callback, 54 | qos_profile=None, 55 | callback_group=None 56 | ) 57 | 58 | def run(self): 59 | self.spin() 60 | 61 | def test_callback(self, msg): 62 | ts = datetime.timestamp(datetime.now()) 63 | msg_ts = msg.split("|")[1] 64 | 65 | # -> Get timestamp difference 66 | ts_diff = ts - float(msg_ts) 67 | 68 | # -> Convert timestamp difference to seconds 69 | ts_diff_sec = ts_diff 70 | 71 | print(f"-> New message: {msg}, (comm delay: {ts_diff_sec})") 72 | 73 | 74 | from redis import Redis 75 | from threading import Thread 76 | from multiprocessing import Process 77 | 78 | client = Redis() 79 | client.flushall() 80 | 81 | # clock_thread = Process(target=lambda: Clock(ref="Sim_clock", namespace=NAMESPACE, time_factor=10)) 82 | # clock_thread.start() 83 | 84 | # pub_lst = [] 85 | # sub_lst = [] 86 | 87 | # for i in range(3): 88 | # pub_lst.append(test_pub(ref=f"Publisher_{i+1}")) 89 | # sub_lst.append(test_sub(ref=f"Subscriber_{i+1}")) 90 | 91 | # thread_lst = [] 92 | 93 | # for i in range(10): 94 | # thread_lst.append(Thread(target=test_pub)) 95 | # thread_lst.append(Thread(target=test_sub)) 96 | 97 | # for thread in thread_lst: 98 | # thread.start() 99 | 100 | test_pub1 = test_pub() 101 | test_sub1 = test_sub() 102 | 103 | print("Created Nodes") 104 | 105 | pub_thread = Thread(target=test_pub1.run) 106 | sub_thread = Thread(target=test_sub1.run) 107 | 108 | pub_thread.start() 109 | sub_thread.start() 110 | 111 | print("Primed") 112 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | .idea/ 2 | ### Python template 3 | # Byte-compiled / optimized / DLL files 4 | __pycache__/ 5 | *.py[cod] 6 | *$py.class 7 | 8 | # C extensions 9 | *.so 10 | 11 | # Distribution / packaging 12 | .Python 13 | build/ 14 | develop-eggs/ 15 | dist/ 16 | downloads/ 17 | eggs/ 18 | .eggs/ 19 | lib/ 20 | lib64/ 21 | parts/ 22 | sdist/ 23 | var/ 24 | wheels/ 25 | share/python-wheels/ 26 | *.egg-info/ 27 | .installed.cfg 28 | *.egg 29 | MANIFEST 30 | 31 | # PyInstaller 32 | # Usually these files are written by a python script from a template 33 | # before PyInstaller builds the exe, so as to inject date/other infos into it. 34 | *.manifest 35 | *.spec 36 | 37 | # Installer logs 38 | pip-log.txt 39 | pip-delete-this-directory.txt 40 | 41 | # Unit test / coverage reports 42 | htmlcov/ 43 | .tox/ 44 | .nox/ 45 | .coverage 46 | .coverage.* 47 | .cache 48 | nosetests.xml 49 | coverage.xml 50 | *.cover 51 | *.py,cover 52 | .hypothesis/ 53 | .pytest_cache/ 54 | cover/ 55 | 56 | # Translations 57 | *.mo 58 | *.pot 59 | 60 | # Django stuff: 61 | *.log 62 | local_settings.py 63 | db.sqlite3 64 | db.sqlite3-journal 65 | 66 | # Flask stuff: 67 | instance/ 68 | .webassets-cache 69 | 70 | # Scrapy stuff: 71 | .scrapy 72 | 73 | # Sphinx documentation 74 | docs/_build/ 75 | 76 | # PyBuilder 77 | .pybuilder/ 78 | target/ 79 | 80 | # Jupyter Notebook 81 | .ipynb_checkpoints 82 | 83 | # IPython 84 | profile_default/ 85 | ipython_config.py 86 | 87 | # pyenv 88 | # For a library or package, you might want to ignore these files since the code is 89 | # intended to run in multiple environments; otherwise, check them in: 90 | # .python-version 91 | 92 | # pipenv 93 | # According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control. 94 | # However, in case of collaboration, if having platform-specific dependencies or dependencies 95 | # having no cross-platform support, pipenv may install dependencies that don't work, or not 96 | # install all needed dependencies. 97 | #Pipfile.lock 98 | 99 | # poetry 100 | # Similar to Pipfile.lock, it is generally recommended to include poetry.lock in version control. 101 | # This is especially recommended for binary packages to ensure reproducibility, and is more 102 | # commonly ignored for libraries. 103 | # https://python-poetry.org/docs/basic-usage/#commit-your-poetrylock-file-to-version-control 104 | #poetry.lock 105 | 106 | # pdm 107 | # Similar to Pipfile.lock, it is generally recommended to include pdm.lock in version control. 108 | #pdm.lock 109 | # pdm stores project-wide configurations in .pdm.toml, but it is recommended to not include it 110 | # in version control. 111 | # https://pdm.fming.dev/#use-with-ide 112 | .pdm.toml 113 | 114 | # PEP 582; used by e.g. github.com/David-OConnor/pyflow and github.com/pdm-project/pdm 115 | __pypackages__/ 116 | 117 | # Celery stuff 118 | celerybeat-schedule 119 | celerybeat.pid 120 | 121 | # SageMath parsed files 122 | *.sage.py 123 | 124 | # Environments 125 | .env 126 | .venv 127 | env/ 128 | venv/ 129 | ENV/ 130 | env.bak/ 131 | venv.bak/ 132 | 133 | # Spyder project settings 134 | .spyderproject 135 | .spyproject 136 | 137 | # Rope project settings 138 | .ropeproject 139 | 140 | # mkdocs documentation 141 | /site 142 | 143 | # mypy 144 | .mypy_cache/ 145 | .dmypy.json 146 | dmypy.json 147 | 148 | # Pyre type checker 149 | .pyre/ 150 | 151 | # pytype static type analyzer 152 | .pytype/ 153 | 154 | # Cython debug symbols 155 | cython_debug/ 156 | 157 | # PyCharm 158 | # JetBrains specific template is maintained in a separate JetBrains.gitignore that can 159 | # be found at https://github.com/github/gitignore/blob/main/Global/JetBrains.gitignore 160 | # and can be added to the global gitignore or merged into this file. For a more nuclear 161 | # option (not recommended) you can uncomment the following to ignore the entire idea folder. 162 | #.idea/ 163 | 164 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # RedisROS 2 | A Redis-based pure python alternative to ROS2 3 | 4 | [Installation](#installation) | [Usage](#usage) | [Advanced Topics](#advanced-topics) | [About](#about) 5 | 6 | **!!!!! The current published version is unstable, please wait for the next release !!!!!** 7 | 8 | --- 9 | > **Warning** 10 | > This library is still in development, and has not been properly tested, use at your own risks 11 | --- 12 | 13 | RedisROS is an event-based publisher/subscriber communication framework, aimed at enabling fast development and prototying of event-driven applications. Those include robotics, simulation, and any other application operating on this ethos. It follows a very similar structure to the well established Robot Operating System (ROS), with an emphasis put on minimal development overhead and fast prototyping. 14 | 15 | As such, the development of this library has been done according to the following ethos: 16 | 17 | - **A pure-python implementation:** The goal of RedisROS is not performance as much as it is fast and flexible prototyping. Python was as such selected, given its ease of use and accessibility. 18 | 19 | - **An interface similar to that of ROS2:** Scripts developed using RedisROS should be portable to ROS2 with minimal modifications if desired (given no RedisROS-specific features are used, more on that later). 20 | 21 | - **Minimal development overhead:** RedisROS gets rid of all unnecessary steps when possible. There is no more need for compiling, messages definitions, packages etc. 22 | 23 | - **Minimal dependencies:** To further reduce complexity, dependencies are kept to a minimum. The only major dependency being *Redis*, and the *python-redis-lock* library. **ROS is *not* necessary for RedisROS to run**. 24 | 25 | - **Modular and expandable:** RedisROS was coded to be easily expanded. New interfaces can easily be setup, allowing for testing new configurations and ideas. 26 | 27 | *It should be noted that RedisROS is also capable of communicating with ROS/ROS2. Bridges are under development and will be released soon.* 28 | 29 | ## Why Redis? 30 | *"Redis is an in-memory data structure store, used as a distributed, in-memory key–value database, cache and message broker, with optional durability."* 31 | 32 | Redis solves the issue of cross-process comunication, while ensuring performance and reliability in the exchange of information. It can furthermore be deployed on distibuted architecture, making it an interesting choice for scalability purposes. 33 | 34 | # Installation 35 | *Coming soon* 36 | # Usage 37 | With RedisROS, any python class can be made a node capable of communicating with the communication layer. Similarly to ROS2, the class can inherit from RedisROS's node class, which in turn gives it access to all RedisROS methods. 38 | 39 | Alternatively a RedisROS node can be created, which can then be passed around, and interfaced with as needs be. 40 | 41 | *Coming soon* 42 | 43 | ## Core endpoints 44 | To allow for emulating all behaviors desired, three core endpoints are necessary: 45 | - The **publisher**: Used to push data to topics 46 | - The **subscriber**: Used to monitor, retreive, and react to data being published on topics 47 | - The **shared variable**: Used to store a single, cross-process value (somewhat similar to ROS's parameters) 48 | 49 | All other behaviors can be achieved through combining the above (more in [custom endpoints](#custom-endpoints)) 50 | 51 | ### Publisher 52 | *Coming soon* 53 | ### Subscriber 54 | *Coming soon* 55 | ### Shared_variable 56 | *Coming soon* 57 | ## Custom endpoints 58 | The three core endpoints can be combined to emulate most behaviors. RedisROS makes it easy to build on those to achieve the desired behaviors. Currently, the following custom endpoints are being developed 59 | 60 | ### Behavior 61 | - **Service:** Allows for request/response pattern 62 | 63 | ### Bridges 64 | - **ROS publisher:** Bridge endpoint, allowing for sending messages through ROS 65 | - **ROS subscriber:** Bridge endpoint, allowing for sending messages through ROS 66 | 67 | # From RedisROS to ROS2 68 | *Coming soon* 69 | # Advanced Topics 70 | *Coming soon* 71 | ## Custom endpoints 72 | *Coming soon* 73 | # About 74 | RedisROS was developed as part of a **larger upcoming project**. Stay tunned for more! 75 | -------------------------------------------------------------------------------- /RedisROS/Endpoints/Core/Shared_variable/Shared_variable_module.py: -------------------------------------------------------------------------------- 1 | 2 | from RedisROS.Endpoints import Shared_variable 3 | 4 | 5 | class Shared_variable_module: 6 | def __init__(self): 7 | pass 8 | 9 | def shared_variables(self): 10 | """ 11 | Get shared_variables that have been created on this node in every callback groups. 12 | """ 13 | # -> Get all the shared_variables in every callback group 14 | shared_variables = [] 15 | 16 | for callback_group in self.callbackgroups.values(): 17 | for callback in callback_group.callbacks: 18 | if isinstance(callback, Shared_variable): 19 | shared_variables.append(callback) 20 | 21 | # -> Return the list of shared_variables 22 | return shared_variables 23 | 24 | # ---------------------------------------------- Declaration 25 | def declare_shared_variable(self, 26 | name: str, 27 | value: int or float or str or bool = None, 28 | descriptor: str = "", 29 | scope="global", 30 | variable_type: str = "unspecified", 31 | ignore_override: bool = False, 32 | manual_spin: bool = False, 33 | ) -> Shared_variable: 34 | """ 35 | Declare a shared_variable on the node. 36 | 37 | :param name: The name of the shared_variable. 38 | :param value: The value of the shared_variable. 39 | :param descriptor: The descriptor of the shared_variable. 40 | :param scope: The scope of the shared_variable (global or local). 41 | :param variable_type: The type of the shared_variable. 42 | :param ignore_override: If True, ignore any existing shared_variables with the same name. 43 | : 44 | """ 45 | 46 | # -> Check if shared_variable already declared in this node 47 | for shared_variable in self.callbackgroups["default_shared_variable_callback_group"].callbacks: 48 | # -> Return existing shared_variable if name matches and ignore override is False 49 | if shared_variable.name == name and not ignore_override: 50 | return shared_variable 51 | 52 | # -> Set the value of the existing shared_variable if name matches and ignore override is True 53 | elif shared_variable.name == name and ignore_override: 54 | shared_variable.set_value(value=value) 55 | return shared_variable 56 | 57 | # -> Create a shared_variable 58 | new_shared_variable = Shared_variable( 59 | name=name, 60 | value=value, 61 | scope=scope, 62 | variable_type=variable_type, 63 | descriptor=descriptor, 64 | ignore_override=ignore_override, 65 | manual_spin=manual_spin, 66 | parent_node_ref=self.ref, 67 | namespace=self.namespace 68 | ) 69 | 70 | # -> Add the shared_variable to the default shared_variable callback group 71 | self.callbackgroups["default_shared_variable_callback_group"].add_callback(new_shared_variable) 72 | 73 | # -> Return the shared_variable object 74 | return new_shared_variable 75 | 76 | def declare_shared_variables(self, 77 | shared_variables, 78 | namespace: str = ""): 79 | """ 80 | Declare multiple shared_variables on the node. 81 | 82 | Each shared_variable is a dictionary with the following keys: 83 | - name: The name of the shared_variable. 84 | - value: The value of the shared_variable. 85 | - scope: The scope of the shared_variable (global or local). 86 | - variable_type: The type of the shared_variable. 87 | - ignore_override: If True, ignore any existing shared_variables with the same name. 88 | 89 | :param shared_variables: The list of shared_variables to declare. 90 | :param namespace: The namespace of the shared_variables. 91 | """ 92 | 93 | # -> Create a list of shared_variables 94 | new_shared_variables = [] 95 | for shared_variable in shared_variables: 96 | new_shared_variables.append( 97 | self.declare_shared_variable( 98 | name=namespace + shared_variable["name"], 99 | value=shared_variable["value"], 100 | scope=shared_variable["scope"], 101 | variable_type=shared_variable["variable_type"], 102 | ignore_override=shared_variable["ignore_override"]) 103 | ) 104 | 105 | # -> Return the list of shared_variables 106 | return new_shared_variables 107 | 108 | def undeclare_shared_variable(self, shared_variable: str) -> None: 109 | """ 110 | Undeclare a previously declared shared_variable. 111 | """ 112 | # -> Destroy shared_variable endpoint 113 | shared_variable.destroy_endpoint() 114 | 115 | # -> Remove the publisher from its callback group 116 | for callback_group in self.callbackgroups.values(): 117 | if callback_group.has_entity(shared_variable): 118 | callback_group.remove_callback(shared_variable) 119 | break 120 | 121 | # ---------------------------------------------- Getters 122 | def get_shared_variable(self, name: str) -> Shared_variable: 123 | print(f"WARNING: get_shared_variable not implemented yet") 124 | pass 125 | 126 | def get_shared_variables(self, names): 127 | print(f"WARNING: get_shared_variables not implemented yet") 128 | pass 129 | 130 | # ---------------------------------------------- Setters 131 | def set_shared_variable(self, shared_variable: str) -> None: 132 | print(f"WARNING: set_shared_variable not implemented yet") 133 | pass 134 | 135 | def set_shared_variables(self, shared_variable_list) -> None: 136 | print(f"WARNING: set_shared_variables not implemented yet") 137 | pass 138 | -------------------------------------------------------------------------------- /RedisROS/Endpoints/Core/Publisher/Publisher.py: -------------------------------------------------------------------------------- 1 | import json 2 | from datetime import datetime 3 | 4 | from redis.commands.graph import Graph, Edge, Node 5 | from redis_lock import Lock 6 | 7 | from ..Endpoint_abc import Endpoint_abc 8 | 9 | 10 | class Publisher(Endpoint_abc): 11 | def __init__(self, 12 | topic: str, 13 | msg_type: str = "Unspecified", 14 | qos_profile=None, 15 | parent_node_ref: str = None, 16 | namespace: str = "" 17 | ) -> None: 18 | """ 19 | Create a publisher endpoint for the given topic 20 | 21 | :param msg_type: The type of the message to be published 22 | :param topic: The topic to publish to 23 | :param qos_profile: The QoS profile to use 24 | 25 | :param parent_node_ref: The reference of the parent node 26 | """ 27 | 28 | # -> Initialise the publisher properties 29 | self.msg_type = msg_type 30 | self.topic = self.get_topic(topic_elements=[topic]) 31 | self.qos_profile = qos_profile 32 | 33 | # -> Initialise the publisher's cache 34 | self.cache = [] 35 | 36 | # -> Setup endpoint 37 | Endpoint_abc.__init__(self, 38 | parent_node_ref=parent_node_ref, 39 | namespace=namespace) 40 | 41 | # -> Declare the endpoint in the comm graph 42 | self.declare_endpoint() 43 | 44 | def __build_msg(self, msg) -> dict: 45 | # -> Add message metadata 46 | msg = { 47 | "timestamp": datetime.timestamp(datetime.now()), 48 | "msg_type": self.msg_type, 49 | "parent_node_ref": self.parent_node_ref, 50 | "publisher_id": self.id, 51 | "msg": msg 52 | } 53 | 54 | return msg 55 | 56 | def spin(self) -> None: 57 | """ 58 | Publish the messages in the cache to the topic 59 | """ 60 | 61 | for msg in self.cache: 62 | self.client.publish(self.topic, json.dumps(msg)) 63 | 64 | # -> Clear the cache 65 | self.cache = [] 66 | 67 | def publish(self, 68 | msg, 69 | direct: bool = False, 70 | instant: bool = True) -> None: 71 | """ 72 | Publish the given message to the topic. 73 | If instant is True, the message will be published immediately, otherwise it will be published at the next spin 74 | 75 | ROS2 compatibility note: 76 | - Instant publishing is not supported 77 | 78 | :param msg: The message to publish 79 | :param direct: Whether to publish the message directly to the redis server 80 | :param instant: Whether to publish the message instantly or to cache it 81 | """ 82 | 83 | # -> Add message metadata 84 | msg = self.__build_msg(msg=msg) 85 | 86 | # -> Publish the message 87 | if direct: 88 | self.client.publish(self.topic, json.dumps(msg)) 89 | 90 | else: 91 | # -> Add the msg to the cache of messages to publish 92 | self.cache.append(msg) 93 | 94 | if instant: 95 | self.spin() 96 | 97 | def declare_endpoint(self) -> None: 98 | with Lock(redis_client=self.client, name=self.comm_graph): 99 | # -> Get the communication graph from the redis server 100 | comm_graph = self.client.json().get(self.comm_graph) 101 | 102 | # -> Declare the endpoint in the parent node 103 | comm_graph[self.parent_address].append( 104 | {"id": self.id, 105 | "type": "publisher", 106 | "msg_type": self.msg_type, 107 | "topic": self.topic} 108 | ) 109 | 110 | # -> Update comm_graph shared variable 111 | self.client.json().set(self.comm_graph, "$", comm_graph) 112 | 113 | # ======================== Redis graph declaration 114 | # -> Add edge in redis graph 115 | redis_graph = Graph(client=self.client, name="ROS_graph") 116 | 117 | # -> Check if topic node is in graph 118 | query = "MATCH (n:topic {name: '%s'}) RETURN n" % (self.topic) 119 | topic_node = redis_graph.query(query).result_set 120 | 121 | # -> Get topic node 122 | if len(topic_node) == 0: # if it does not exist 123 | # -> Create topic node 124 | topic_node = Node( 125 | label="topic", 126 | properties={ 127 | "name": self.topic, 128 | "pyROS_id": self.id, 129 | "msg_type": str(self.msg_type), 130 | "namespace": self.namespace 131 | } 132 | ) 133 | 134 | # -> Add to graph 135 | redis_graph.add_node(node=topic_node) 136 | redis_graph.commit() 137 | 138 | # -> Create relationship 139 | edge_properties = "{" + f"namespace: '{self.namespace}', msg_type: '{str(self.msg_type)}', qos_profile: '{str(self.qos_profile)}'" + "}" 140 | 141 | query = f"MATCH (p:node), (t:topic) WHERE p.name = '{self.parent_address}' AND t.name = '{self.topic}' CREATE (p)-[r:publish {edge_properties}]->(t) RETURN r" 142 | redis_graph.query(query) 143 | 144 | def destroy_endpoint(self) -> None: 145 | with Lock(redis_client=self.client, name=self.comm_graph): 146 | # -> Get the communication graph from the redis server 147 | comm_graph = self.client.json().get(self.comm_graph) 148 | 149 | # -> Undeclare the endpoint in the parent node 150 | comm_graph[self.parent_address].remove( 151 | {"id": self.id, 152 | "type": "publisher", 153 | "msg_type": self.msg_type, 154 | "topic": self.topic} 155 | ) 156 | 157 | # -> Update comm_graph shared variable 158 | self.client.json().set(self.comm_graph, "$", comm_graph) 159 | 160 | # ======================== Redis graph 161 | # -> Get pubsub graph 162 | redis_graph = Graph(client=self.client, name="ROS_graph") 163 | 164 | # -> Delete relation 165 | query = f"MATCH (p:node)-[r:publish]->(t:topic) WHERE p.name = '{self.parent_address}' AND t.name = '{self.topic}' DELETE r" 166 | redis_graph.query(query) 167 | 168 | # -> Delete topic if no relationships are left to topic 169 | relations_count = 0 170 | 171 | query = f"MATCH (p:node)-[r:publish]->(t:topic) WHERE t.name = '{self.topic}' RETURN COUNT(r)" 172 | relations_count += redis_graph.query(query).result_set[0][0] 173 | 174 | query = f"MATCH (t:topic)-[r:subscribed]->(p:node) WHERE t.name = '{self.topic}' RETURN COUNT(r)" 175 | relations_count += redis_graph.query(query).result_set[0][0] 176 | 177 | if relations_count == 0: 178 | query = f"MATCH (t:topic) WHERE t.name = '{self.topic}' DELETE t" 179 | redis_graph.query(query) -------------------------------------------------------------------------------- /RedisROS/Endpoints/Core/Subscriber/Subscriber.py: -------------------------------------------------------------------------------- 1 | import json 2 | import traceback 3 | 4 | from redis.commands.graph import Graph, Edge, Node 5 | from redis_lock import Lock 6 | 7 | from ..Endpoint_abc import Endpoint_abc 8 | 9 | 10 | class Subscriber(Endpoint_abc): 11 | def __init__(self, 12 | topic: str, 13 | callback, 14 | msg_type: str = "Unspecified", 15 | qos_profile=None, 16 | parent_node_ref: str = None, 17 | namespace: str = "", 18 | manual_spin: bool = False 19 | ) -> None: 20 | """ 21 | Create a subscriber endpoint for the given topic 22 | 23 | :param msg_type: The type of the message to be published 24 | :param topic: The topic to publish to 25 | :param callback: The callback function to call when a message is received 26 | :param qos_profile: The QoS profile to use 27 | 28 | :param parent_node_ref: The reference of the parent node 29 | """ 30 | 31 | # -> Initialise the subscriber properties 32 | self.msg_type = msg_type 33 | self.topic = self.get_topic(topic_elements=[topic]) 34 | self.callback = callback 35 | self.qos_profile = qos_profile 36 | 37 | # -> Setup endpoint 38 | Endpoint_abc.__init__(self, 39 | parent_node_ref=parent_node_ref, 40 | namespace=namespace, 41 | manual_spin=manual_spin 42 | ) 43 | 44 | # -> Setup the subscriber's pubsub connection 45 | self.pubsub = self.client.pubsub(ignore_subscribe_messages=True) 46 | 47 | # -> Subscribe to the topic 48 | self.pubsub.subscribe(**{self.topic: self.__callback}) 49 | 50 | # -> Declare the endpoint in the comm graph 51 | self.declare_endpoint() 52 | 53 | def __str__(self): 54 | return f"{self.parent_node_ref} - Subscriber ({self.id}) to {self.topic}" 55 | 56 | def __repr__(self): 57 | return self.__str__() 58 | 59 | def spin(self) -> None: 60 | """ 61 | Retrieve the message from the topic according to the subscriber's qos profile, 62 | and call the subscriber's callback function 63 | """ 64 | 65 | self.pubsub.get_message() 66 | 67 | def __callback(self, raw_msg): 68 | """ 69 | Call the subscriber's callback function 70 | """ 71 | 72 | with Lock(redis_client=self.client, name=self.id): 73 | # -> Convert raw message to dictionary 74 | raw_msg = json.loads(raw_msg["data"]) 75 | 76 | # -> Call the subscriber's callback function 77 | # Attempt to provide both message and msg meta in callback 78 | try: 79 | try: 80 | self.callback(raw_msg["msg"], raw_msg) 81 | # Only provide msg 82 | except TypeError: 83 | self.callback(raw_msg["msg"]) 84 | except: 85 | print("=============================================================") 86 | print(f"ERROR:: {self.parent_address}: Subscriber to {self.topic} callback crashed") 87 | print("-------------------------------------------------------------") 88 | traceback.print_exc() 89 | print("=============================================================") 90 | 91 | def declare_endpoint(self) -> None: 92 | with Lock(redis_client=self.client, name=self.comm_graph): 93 | # -> Get the communication graph from the redis server 94 | comm_graph = self.client.json().get(self.comm_graph) 95 | 96 | # -> Declare the endpoint in the parent node 97 | comm_graph[self.parent_address].append( 98 | {"id": self.id, 99 | "type": "subscriber", 100 | "msg_type": self.msg_type, 101 | "topic": self.topic} 102 | ) 103 | 104 | # -> Update comm_graph shared variable 105 | self.client.json().set(self.comm_graph, "$", comm_graph) 106 | 107 | # ======================== Redis graph 108 | # -> Add edge in redis graph 109 | redis_graph = Graph(client=self.client, name="ROS_graph") 110 | 111 | # -> Check if topic node is in graph 112 | query = "MATCH (n:topic {name: '%s'}) RETURN n" % (self.topic) 113 | topic_node = redis_graph.query(query).result_set 114 | 115 | # -> Get topic node 116 | if len(topic_node) == 0: # if it does not exist 117 | # -> Create topic node 118 | topic_node = Node( 119 | label="topic", 120 | properties={ 121 | "name": self.topic, 122 | "pyROS_id": self.id, 123 | "msg_type": str(self.msg_type), 124 | "namespace": self.namespace 125 | } 126 | ) 127 | 128 | # -> Add to graph 129 | redis_graph.add_node(node=topic_node) 130 | redis_graph.commit() 131 | 132 | # -> Create relationship 133 | edge_properties = "{" + f"namespace: '{self.namespace}', msg_type: '{str(self.msg_type)}', qos_profile: '{str(self.qos_profile)}'" + "}" 134 | 135 | query = f"MATCH (p:node), (t:topic) WHERE p.name = '{self.parent_address}' AND t.name = '{self.topic}' CREATE (t)-[r:subscribed {edge_properties}]->(p) RETURN r" 136 | redis_graph.query(query) 137 | 138 | def destroy_endpoint(self) -> None: 139 | with Lock(redis_client=self.client, name=self.comm_graph): 140 | # -> Get the communication graph from the redis server 141 | comm_graph = self.client.json().get(self.comm_graph) 142 | 143 | # -> Undeclare the endpoint in the parent node 144 | comm_graph[self.parent_address].remove( 145 | {"id": self.id, 146 | "type": "subscriber", 147 | "msg_type": self.msg_type, 148 | "topic": self.topic} 149 | ) 150 | 151 | # -> Unsubscribe the end point from the topic 152 | self.pubsub.unsubscribe() 153 | 154 | # -> Update comm_graph shared variable 155 | self.client.json().set(self.comm_graph, "$", comm_graph) 156 | 157 | # ======================== Redis graph 158 | # -> Get pubsub graph 159 | redis_graph = Graph(client=self.client, name="ROS_graph") 160 | 161 | # -> Delete relation 162 | query = f"MATCH (t:topic)-[r:subscribed]->(p:node) WHERE p.name = '{self.parent_address}' AND t.name = '{self.topic}' DELETE r" 163 | redis_graph.query(query) 164 | 165 | # -> Delete topic if no relationships are left to topic 166 | relations_count = 0 167 | 168 | query = f"MATCH (p:node)-[r:publish]->(t:topic) WHERE t.name = '{self.topic}' RETURN COUNT(r)" 169 | relations_count += redis_graph.query(query).result_set[0][0] 170 | 171 | query = f"MATCH (t:topic)-[r:subscribed]->(p:node) WHERE t.name = '{self.topic}' RETURN COUNT(r)" 172 | relations_count += redis_graph.query(query).result_set[0][0] 173 | 174 | if relations_count == 0: 175 | query = f"MATCH (t:topic) WHERE t.name = '{self.topic}' DELETE t" 176 | redis_graph.query(query) -------------------------------------------------------------------------------- /RedisROS/Node.py: -------------------------------------------------------------------------------- 1 | from concurrent.futures import ThreadPoolExecutor 2 | from threading import Thread 3 | import random 4 | import string 5 | import json 6 | import time 7 | 8 | from redis import Redis 9 | from redis.commands.graph import Graph, Edge 10 | from redis.commands.graph import Node as Redis_node 11 | 12 | from redis_lock import Lock 13 | 14 | # -> Import endpoint modules 15 | # Core 16 | from RedisROS.Endpoints.Core.Publisher.Publisher_module import Publisher_module 17 | from RedisROS.Endpoints.Core.Subscriber.Subscriber_module import Subscriber_module 18 | from RedisROS.Endpoints.Core.Shared_variable.Shared_variable_module import Shared_variable_module 19 | from RedisROS.Endpoints.Core.Timer.Timer_module import Timer_module 20 | 21 | # Custom 22 | 23 | # -> Import individual endpoint classes 24 | from RedisROS.Endpoints import Publisher 25 | from RedisROS.Endpoints import Subscriber 26 | from RedisROS.Endpoints import Shared_variable 27 | from RedisROS.Async_timer import Async_timer 28 | from RedisROS.Callback_groups import ReentrantCallbackGroup, MutuallyExclusiveCallbackGroup 29 | 30 | """ 31 | Callback groups: https://docs.ros.org/en/foxy/How-To-Guides/Using-callback-groups.html 32 | 33 | "topic_1/subscribers": [subscriber_1, subscriber_2, ..., subscriber_n,] 34 | "topic_1/publishers": [publisher_1, publisher_2, ..., publisher_n,] 35 | 36 | "Node_1": [(publisher_1, Publisher, topic_1), (subscriber_1, Subscriber, topic_1), ..., (subscriber_n, Subscriber, topic_n),] 37 | 38 | # -> Subscriber queues 39 | "subscriber_1" = [...] 40 | "subscriber_2" = [...] 41 | """ 42 | 43 | 44 | class Node( 45 | # Core 46 | Publisher_module, 47 | Subscriber_module, 48 | Shared_variable_module, 49 | Timer_module, 50 | 51 | # Custom 52 | # ROS_publisher_module, 53 | # ROS_subscriber_module, 54 | ): 55 | def __init__(self, 56 | ref: str = None, 57 | namespace: str = "", 58 | labels: list = [] 59 | ) -> None: 60 | # -> Setup endpoint redis connection 61 | self.client = Redis() 62 | 63 | # ---- Initialise the node 64 | # -> Set id 65 | self.id = str(id(self)) 66 | self.namespace = namespace 67 | self.labels = labels 68 | 69 | # -> Get comm_graph 70 | self.comm_graph = "Comm_graph" 71 | 72 | if self.namespace != "": 73 | self.comm_graph = self.get_topic(topic_elements=[namespace, self.comm_graph]) 74 | 75 | # -> Initialise ref if it does not exist 76 | if ref is not None: 77 | # -> Set ref 78 | self.ref = ref 79 | 80 | elif not hasattr(self, "ref"): 81 | # -> Generate a random ref 82 | self.ref = ''.join([random.choice(string.ascii_letters + string.digits) for _ in range(8)]) 83 | 84 | # -. Generate node address 85 | self.address = self.get_topic(topic_elements=[self.ref]) 86 | 87 | # -> Declare node 88 | self.declared_node = False 89 | 90 | with Lock(redis_client=self.client, name=self.comm_graph): 91 | if not self.client.exists(self.comm_graph): 92 | # -> Create comm_graph shared variable 93 | self.client.json().set(self.comm_graph, "$", {f"{self.address}": []}) 94 | 95 | else: 96 | # -> Get comm_graph shared variable 97 | comm_graph = self.client.json().get(self.comm_graph) 98 | 99 | # -> Add node to comm_graph 100 | comm_graph[f"{self.address}"] = [] 101 | 102 | # -> Update comm_graph shared variable 103 | self.client.json().set(self.comm_graph, "$", comm_graph) 104 | 105 | # ======================== Redis graph 106 | # -> Get pubsub graph 107 | redis_graph = Graph(client=self.client, name="ROS_graph") 108 | 109 | # -> Add node 110 | new_node = Redis_node( 111 | label=["node"] + self.labels, 112 | properties={ 113 | "name": self.address, 114 | "pyROS_id": self.id, 115 | "ref": self.ref, 116 | "namespace": self.namespace 117 | } 118 | ) 119 | 120 | redis_graph.add_node(node=new_node) 121 | redis_graph.commit() 122 | 123 | self.declared_node = True 124 | 125 | # -> Initialise the node dictionary 126 | self._node_dict = { 127 | "async_timers": {}, 128 | } 129 | 130 | # -> Initialise pointers 131 | self.threaded_spin = None 132 | self.spin_rate = 0.01 133 | 134 | # -> Initialise the node callbackgroups dictionary 135 | self.callbackgroups = { 136 | # Core 137 | "default_publisher_callback_group": ReentrantCallbackGroup(name="default_publisher_callback_group"), 138 | "default_subscriber_callback_group": MutuallyExclusiveCallbackGroup( 139 | name="default_subscriber_callback_group"), 140 | "default_shared_variable_callback_group": ReentrantCallbackGroup( 141 | name="default_shared_variable_callback_group"), 142 | "default_timer_callback_group": ReentrantCallbackGroup(name="default_timer_callback_group"), 143 | 144 | # Custom 145 | "ros_callback_group": ReentrantCallbackGroup(name="ros_callback_group"), 146 | } 147 | 148 | # -> Setup node messaging basis 149 | # -> Spin control variable 150 | self.spin_state = self.declare_shared_variable( 151 | name=f"spin_state", 152 | value=False, 153 | descriptor=f"Spin_state variable for node {self.ref}. Can be used to spin/stop node spin", 154 | scope="local" 155 | ) 156 | 157 | # -> Create publisher to the framework node msgs 158 | # self.framework_msgs = Publisher( 159 | # msg_type="", 160 | # topic="/Framework_msgs", 161 | # qos_profile=None, 162 | # parent_node_ref=self.ref 163 | # ) 164 | 165 | # -> Initialise node endpoint modules 166 | # Core 167 | Publisher_module.__init__(self) 168 | Subscriber_module.__init__(self) 169 | Shared_variable_module.__init__(self) 170 | Timer_module.__init__(self) 171 | 172 | # Custom 173 | # ROS_publisher_module.__init__(self) 174 | # ROS_subscriber_module.__init__(self) 175 | 176 | # ================================================================== Spin logics 177 | def spin(self, 178 | spin_rate: float = 0.01, 179 | condition: Shared_variable = None, 180 | threaded: bool = False, 181 | ) -> None: 182 | """ 183 | Spin the node until the condition is met or until default spin condition is False. 184 | If no condition is given, spin until default spin condition is False. 185 | If threaded is True, spin in a separate thread. 186 | -> Unlike with ROS, publishers/control variables/parameters do not need to be spun if instant is set to True. 187 | 188 | ROS2 compatibility note: 189 | - condition cannot be used 190 | - threaded cannot be used 191 | 192 | :param spin_rate: The rate rate at which to spin the node 193 | :param condition: A shared variable to be used as a spin condition, 194 | :param threaded: If True, spin in a separate thread. 195 | """ 196 | if not self.spin_state.get_value(spin=True): 197 | with Lock(redis_client=self.client, name=self.ref): 198 | # -> Reset spin control variable 199 | self.spin_state.set_value(value=True, instant=True) 200 | 201 | # -> Set spin rate 202 | self.spin_rate = spin_rate 203 | 204 | # ----- Condition provided 205 | # -> If threaded is True and condition is given 206 | if threaded and condition is not None: 207 | self.threaded_spin = Thread(target=self.__conditional_spin, args=(condition,)) 208 | self.threaded_spin.start() 209 | 210 | # -> If threaded is False and condition is given 211 | elif condition is not None: 212 | self.__conditional_spin(spin_condition=condition) 213 | 214 | # ----- No condition provided 215 | # -> If threaded is True and no condition is given 216 | elif threaded: 217 | self.threaded_spin = Thread(target=self.__unconditional_spin) 218 | self.threaded_spin.start() 219 | 220 | # -> If threaded is False and no condition is given 221 | else: 222 | self.__unconditional_spin() 223 | 224 | else: 225 | print(f"!!! Node {self.ref} is already spinning !!!") 226 | 227 | def __unconditional_spin(self): 228 | """ 229 | Spin while the condition is met. 230 | """ 231 | spin_timer = self.create_async_timer( 232 | timer_period_sec=self.spin_rate, 233 | callback=self.spin_once, 234 | ref=self.ref + "_spin_timer" 235 | ) 236 | 237 | # -> Start all timers 238 | for timer in self.async_timers: 239 | timer.start() 240 | 241 | while self.spin_state.get_value(spin=True): 242 | time.sleep(0.01) 243 | pass 244 | 245 | # -> Stop all timers 246 | for timer in self.timers: 247 | timer.cancel() 248 | 249 | self.destroy_timer(timer=spin_timer) 250 | 251 | def __conditional_spin(self, spin_condition: Shared_variable): 252 | """ 253 | Spin while the condition is met. 254 | """ 255 | # -> Create spin timer 256 | spin_timer = self.create_async_timer( 257 | timer_period_sec=1 / self.spin_rate, 258 | callback=self.spin_once 259 | ) 260 | 261 | # -> Start all timers 262 | for timer in self.async_timers: 263 | timer.start() 264 | 265 | # -> Check for kill condition 266 | while spin_condition.get_value(spin=True) and self.spin_state.get_value(spin=True): 267 | time.sleep(0.01) 268 | pass 269 | 270 | # -> Stop all timers 271 | for timer in self.timers: 272 | timer.cancel() 273 | 274 | # -> Destroy spin timer 275 | self.destroy_timer(timer=spin_timer) 276 | 277 | def spin_once(self) -> None: 278 | """ 279 | For every callback group, call the callbacks in a reentrant way. 280 | """ 281 | # -> Create a thread pool 282 | with ThreadPoolExecutor(max_workers=100) as executor: 283 | # -> Run every callback group in the callback group dictionary in a reentrant way 284 | for callback_group in self.callbackgroups.values(): 285 | executor.submit(callback_group.spin) 286 | 287 | def destroy_node(self): 288 | """ 289 | Destroy the node by removing all the publishers, subscribers, timers, etc... 290 | """ 291 | # -> Destroy every publisher and subscriber in every callback group 292 | for callback_group in self.callbackgroups.values(): 293 | for callback in callback_group.callbacks: 294 | # -> Destroy all the publishers in the callback 295 | if isinstance(callback, Publisher): 296 | self.destroy_publisher(publisher=callback) 297 | 298 | # -> Destroy all the subscribers in the callback 299 | elif isinstance(callback, Subscriber): 300 | self.destroy_subscription(subscriber=callback) 301 | 302 | # -> Destroy all the shared variables in the callback 303 | elif isinstance(callback, Shared_variable): 304 | self.undeclare_shared_variable(shared_variable=callback) 305 | 306 | # -> Destroy every timer in the node 307 | timer_lst = self._node_dict["async_timers"] 308 | for timer in timer_lst: 309 | self.destroy_timer(timer=timer) 310 | 311 | # -> Remove node from comm graph 312 | with Lock(redis_client=self.client, name=self.comm_graph): 313 | # -> Get comm_graph shared variable 314 | comm_graph = self.client.json().get(self.comm_graph) 315 | 316 | # -> Delete node entry from comm_graph 317 | del comm_graph[f"{self.address}"] 318 | 319 | # -> Update comm_graph shared variable 320 | self.client.json().set(self.comm_graph, "$", comm_graph) 321 | 322 | # ======================== Redis graph 323 | # -> Get pubsub graph 324 | redis_graph = Graph(client=self.client, name="ROS_graph") 325 | 326 | # -> Delete node 327 | query = f"MATCH (n:node) WHERE n.name = '{self.address}' DELETE n" 328 | redis_graph.query(query) 329 | 330 | # ================================================================== Misc 331 | # ---------------------------------------------- Timer 332 | @property 333 | def async_timers(self): 334 | """ 335 | Get timers that have been created on this node. 336 | """ 337 | 338 | # -> Return the list of timers 339 | return self._node_dict["async_timers"].values() 340 | 341 | # ----------------- Factory 342 | def create_async_timer(self, 343 | timer_period_sec: float, 344 | callback, 345 | ref: str = None 346 | ) -> Async_timer: 347 | """ 348 | Create a timer that calls the callback function at the given rate. 349 | 350 | :param timer_period_sec: The period (s) of the timer. 351 | :param callback: A user-defined callback function that is called when the timer expires. 352 | """ 353 | 354 | # -> Create a timer 355 | new_timer = Async_timer( 356 | timer_period=timer_period_sec, 357 | callback=callback, 358 | ref=ref 359 | ) 360 | 361 | # -> Start the timer 362 | # new_timer.start() 363 | 364 | # -> Add the timer to the node dictionary timers 365 | self._node_dict["async_timers"][new_timer.ref] = new_timer 366 | 367 | # -> Return the timer object 368 | return new_timer 369 | 370 | # ----------------- Destroyer 371 | def destroy_async_timer(self, timer: Async_timer) -> None: 372 | """ 373 | Destroy the given timer. 374 | """ 375 | 376 | # -> Stop the timer 377 | timer.cancel() 378 | 379 | # -> Remove the timer from the node dictionary timers 380 | del self._node_dict["async_timers"][timer.ref] 381 | 382 | @staticmethod 383 | def get_topic(topic_elements: list): 384 | topic = "/" 385 | 386 | for topic_element in topic_elements: 387 | topic += f"{topic_element}/" 388 | 389 | return topic[:-1] 390 | 391 | def __del__(self): 392 | if self.declared_node: 393 | try: 394 | self.destroy_node() 395 | except: 396 | pass 397 | -------------------------------------------------------------------------------- /RedisROS/Endpoints/Core/Shared_variable/Shared_variable.py: -------------------------------------------------------------------------------- 1 | import warnings 2 | from datetime import datetime 3 | import json 4 | 5 | from redis.commands.graph import Graph, Edge, Node 6 | from redis_lock import Lock 7 | 8 | from ..Endpoint_abc import Endpoint_abc 9 | 10 | 11 | class Shared_variable(Endpoint_abc): 12 | def __init__(self, 13 | name: str, 14 | value=None, 15 | scope: str = "global", 16 | variable_type: str = "unspecified", 17 | descriptor: str = "", 18 | ignore_override: bool = False, 19 | parent_node_ref: str = None, 20 | namespace: str = "" 21 | ) -> None: 22 | """ 23 | Create a iteration2 shared_variable endpoint 24 | 25 | :param name: The name of the shared_variable 26 | :param value: The current value of the shared_variable, can be kept as None if creating a pointer to an existing shared_variable 27 | :param scope: The scope of the shared_variable, can be "global" or "local" 28 | :param variable_type: The type of the shared_variable, must be JSON serializable 29 | :param descriptor: A description of the shared_variable 30 | :param ignore_override: If True, ignore any existing shared_variables with the same name. 31 | 32 | :param parent_node_ref: The reference of the parent node 33 | """ 34 | 35 | # -> Setup endpoint 36 | Endpoint_abc.__init__(self, 37 | parent_node_ref=parent_node_ref, 38 | namespace=namespace) 39 | 40 | # -> Initialise the shared_variable properties 41 | self.scope = scope 42 | if scope == "global": 43 | self.name = self.get_topic(topic_elements=[namespace, name]) 44 | else: 45 | self.name = self.get_topic(topic_elements=[namespace, self.parent_node_ref, name]) 46 | 47 | self.scope = scope 48 | self.variable_type = variable_type 49 | self.descriptor = descriptor 50 | self.__value = value 51 | self.__raw_value = self.__build_value(value=value) # Raw value format 52 | self.__cached_value = None # Raw value format 53 | 54 | # -> Check whether the shared_variable exists 55 | if not self.client.exists(self.name) or ignore_override: 56 | # -> Update the shared_variable shared value 57 | self.client.set(self.name, json.dumps(self.__raw_value)) 58 | 59 | # -> Perform initial spin to get the value if shared_variable already exists 60 | self.spin() 61 | 62 | # -> Declare the endpoint in the comm graph 63 | self.declare_endpoint() 64 | 65 | def __build_value(self, value) -> dict: 66 | value = { 67 | "timestamp": datetime.timestamp(datetime.now()), 68 | "variable_type": self.variable_type, 69 | "descriptor": self.descriptor, 70 | "setter_id": self.parent_node_ref, 71 | "value": value 72 | } 73 | 74 | return value 75 | 76 | @property 77 | def node_name(self): 78 | node_name = self.name.split("/")[-1] 79 | 80 | if self.scope == "local": 81 | node_name = self.get_topic(topic_elements=[self.parent_address, node_name]) 82 | else: 83 | node_name = self.get_topic(topic_elements=[node_name]) 84 | 85 | return node_name 86 | 87 | @property 88 | def shared_value(self): 89 | raw_value = self.client.get(self.name) 90 | raw_value = json.loads(raw_value) 91 | 92 | return raw_value 93 | 94 | def spin(self, non_blocking: bool = False) -> None: 95 | """ 96 | Update the value of the shared_variable to the latest value 97 | """ 98 | 99 | def spin_logic(): 100 | # ----- Update the shared value 101 | if self.__cached_value is not None: 102 | 103 | # -> Update the shared value with the cached value if the cached value is newer than the shared value 104 | if float(self.__cached_value["timestamp"]) > float(self.shared_value["timestamp"]): 105 | # -> Update the shared_variable shared value 106 | self.client.set(self.name, json.dumps(self.__cached_value)) 107 | 108 | # -> Set local value to cached value 109 | self.__raw_value = self.__cached_value 110 | self.__value = self.__cached_value["value"] 111 | 112 | # -> Reset cached value 113 | self.__cached_value = None 114 | 115 | # -> Return as the shared value has been updated 116 | return 117 | 118 | # -> Ignore the cached value as it is older than the current shared value 119 | else: 120 | # -> Reset cached value 121 | self.__cached_value = None 122 | 123 | # ----- Set local value to shared value 124 | self.__raw_value = self.shared_value 125 | self.__value = self.shared_value["value"] 126 | 127 | # -> Get local client lock 128 | if non_blocking: 129 | spin_logic() 130 | 131 | else: 132 | with Lock(redis_client=self.client, name=self.id): 133 | # -> Get shared value lock 134 | with Lock(redis_client=self.client, name=self.name): 135 | spin_logic() 136 | 137 | def get_value(self, spin: bool = True, non_blocking: bool = False): 138 | """ 139 | Get the value of the shared_variable 140 | 141 | :param spin: Whether to spin the shared_variable to get the latest value 142 | :param non_blocking: Whether to spin the shared_variable in a non-blocking manner 143 | """ 144 | if spin: 145 | # -> Spin the shared_variable to get the latest value 146 | self.spin(non_blocking=non_blocking) 147 | 148 | # -> Return the value of the shared_variable 149 | return self.__value 150 | 151 | def get_raw_value(self, spin: bool = True, non_blocking: bool = False): 152 | """ 153 | Get the raw value of the shared_variable 154 | 155 | :param spin: Whether to spin the shared_variable to get the latest value 156 | :param non_blocking: Whether to spin the shared_variable in a non-blocking manner 157 | """ 158 | if spin: 159 | # -> Spin the shared_variable to get the latest value 160 | self.spin(non_blocking=non_blocking) 161 | 162 | # -> Return the value of the shared_variable 163 | return self.__raw_value 164 | 165 | def set_value(self, 166 | value, 167 | direct: bool = False, 168 | instant: bool = True) -> None: 169 | """ 170 | Set the value of the shared_variable 171 | If instant is True, the value will be set immediately, otherwise it will be set at the next spin 172 | 173 | :param value: The value to set the shared_variable to 174 | :param direct: Whether to directly set the shared_variable in the shared_variable database 175 | :param instant: Whether to spin the shared_variable to get the latest value 176 | """ 177 | 178 | # -> Check whether the value is of the right type 179 | if self.variable_type != "unspecified": 180 | # -> Convert variable type string to type 181 | if self.variable_type == "int" and not isinstance(value, int): 182 | warnings.warn( 183 | f"Trying to set a value of incorrect type to {self.name} shared_variable, expected int, got {type(value)}") 184 | return 185 | 186 | elif self.variable_type == "float" and not isinstance(value, float): 187 | warnings.warn( 188 | f"Trying to set a value of incorrect type to {self.name} shared_variable, expected float, got {type(value)}") 189 | return 190 | 191 | elif self.variable_type == "str" and not isinstance(value, str): 192 | warnings.warn( 193 | f"Trying to set a value of incorrect type to {self.name} shared_variable, expected str, got {type(value)}") 194 | return 195 | 196 | elif self.variable_type == "bool" and not isinstance(value, bool): 197 | warnings.warn( 198 | f"Trying to set a value of incorrect type to {self.name} shared_variable, expected bool, got {type(value)}") 199 | return 200 | 201 | # -> Construct the raw value 202 | new_value = self.__build_value(value=value) 203 | 204 | if direct: 205 | # -> Update the shared_variable value 206 | self.client.set(name=self.name, value=json.dumps(new_value)) 207 | 208 | # -> Cache the cache value 209 | self.__cached_value = None 210 | 211 | else: 212 | # -> Set the cached value 213 | self.__cached_value = new_value 214 | 215 | if instant: 216 | # -> Spin the shared_variable to set the latest value 217 | self.spin() 218 | 219 | def __add__(self, other): 220 | # -> Check whether the value is of the right type 221 | if self.variable_type != "unspecified": 222 | # -> Convert variable type string to type 223 | if self.variable_type == "int" and not isinstance(value, int): 224 | warnings.warn( 225 | f"Trying to set a value of incorrect type to {self.name} shared_variable, expected int, got {type(value)}") 226 | return self 227 | 228 | elif self.variable_type == "float" and not isinstance(value, float): 229 | warnings.warn( 230 | f"Trying to set a value of incorrect type to {self.name} shared_variable, expected float, got {type(value)}") 231 | return self 232 | 233 | elif self.variable_type == "str" and not isinstance(value, str): 234 | warnings.warn( 235 | f"Trying to set a value of incorrect type to {self.name} shared_variable, expected str, got {type(value)}") 236 | return self 237 | 238 | elif self.variable_type == "bool" and not isinstance(value, bool): 239 | warnings.warn( 240 | f"Trying to set a value of incorrect type to {self.name} shared_variable, expected bool, got {type(value)}") 241 | return self 242 | 243 | with Lock(redis_client=self.client, name=self.id): 244 | with Lock(redis_client=self.client, name=self.name): 245 | # -> Get current value 246 | current_value = self.get_value( 247 | spin=True, # Spin the shared_variable to get the latest value 248 | non_blocking=True # Make spin non-blocking to avoid deadlocks 249 | ) 250 | 251 | # -> Construct the raw value 252 | new_value = current_value + other 253 | 254 | # -> Update the shared_variable value 255 | self.set_value(value=new_value, direct=True, instant=False) 256 | 257 | # -> Return self 258 | return self 259 | 260 | def declare_endpoint(self) -> None: 261 | with Lock(redis_client=self.client, name=self.comm_graph): 262 | # -> Get the communication graph from the redis server 263 | comm_graph = self.client.json().get(self.comm_graph) 264 | 265 | # -> Declare the endpoint in the parent node 266 | comm_graph[self.parent_address].append( 267 | {"id": self.id, 268 | "type": "shared_variable", 269 | "name": self.name, 270 | "scope": self.scope, 271 | "variable_type": self.variable_type, 272 | "descriptor": self.descriptor} 273 | ) 274 | 275 | # -> Update comm_graph shared variable 276 | self.client.json().set(self.comm_graph, "$", comm_graph) 277 | 278 | # ======================== Redis graph declaration 279 | # -> Add edge in redis graph 280 | redis_graph = Graph(client=self.client, name="ROS_graph") 281 | 282 | # -> Check if topic node is in graph 283 | query = "MATCH (n:shared_variable {name: '%s'}) RETURN n" % (self.node_name) 284 | topic_node = redis_graph.query(query).result_set 285 | 286 | if len(topic_node) == 0: # if it does not exist 287 | # -> Create topic node 288 | topic_node = Node( 289 | label=["shared_variable", self.scope], 290 | properties={ 291 | "name": self.node_name, 292 | "scope": self.scope, 293 | "variable_type": self.variable_type, 294 | "descriptor": self.descriptor, 295 | "pyROS_id": self.id, 296 | "namespace": self.namespace 297 | } 298 | ) 299 | 300 | # -> Add to graph 301 | redis_graph.add_node(node=topic_node) 302 | redis_graph.commit() 303 | 304 | # -> Create relationship 305 | edge_properties = "{" + f"namespace: '{self.namespace}', variable_type: '{str(self.variable_type)}'" + "}" 306 | 307 | query = f"MATCH (p:node), (v:shared_variable) WHERE p.name = '{self.parent_address}' AND v.name = '{self.node_name}' CREATE (p)-[r:uses {edge_properties}] -> (v) RETURN r" 308 | redis_graph.query(query) 309 | 310 | def destroy_endpoint(self) -> None: 311 | with Lock(redis_client=self.client, name=self.comm_graph): 312 | # -> Get the communication graph from the redis server 313 | comm_graph = self.client.json().get(self.comm_graph) 314 | 315 | # -> Undeclare the endpoint in the parent node 316 | comm_graph[self.parent_address].remove( 317 | {"id": self.id, 318 | "type": "shared_variable", 319 | "name": self.name, 320 | "scope": self.scope, 321 | "variable_type": self.variable_type, 322 | "descriptor": self.descriptor} 323 | ) 324 | 325 | # -> Update comm_graph shared variable 326 | self.client.json().set(self.comm_graph, "$", comm_graph) 327 | 328 | # ======================== Redis graph 329 | # -> Get pubsub graph 330 | redis_graph = Graph(client=self.client, name="ROS_graph") 331 | 332 | # -> Delete relation 333 | query = f"MATCH (p:node)-[r:uses]->(v:shared_variable) WHERE p.name = '{self.parent_address}' AND v.name = '{self.node_name}' DELETE r" 334 | redis_graph.query(query) 335 | 336 | # -> Delete shared variable node if no relationships are left to it 337 | query = f"MATCH (p:node)-[r:uses]->(v:shared_variable) WHERE v.name = '{self.node_name}' RETURN COUNT(r)" 338 | relations_count = redis_graph.query(query).result_set[0][0] 339 | 340 | if relations_count == 0: 341 | query = f"MATCH (v:shared_variable) WHERE v.name = '{self.node_name}' DELETE v" 342 | redis_graph.query(query) 343 | 344 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | GNU GENERAL PUBLIC LICENSE 2 | Version 3, 29 June 2007 3 | 4 | Copyright (C) 2007 Free Software Foundation, Inc. 5 | Everyone is permitted to copy and distribute verbatim copies 6 | of this license document, but changing it is not allowed. 7 | 8 | Preamble 9 | 10 | The GNU General Public License is a free, copyleft license for 11 | software and other kinds of works. 12 | 13 | The licenses for most software and other practical works are designed 14 | to take away your freedom to share and change the works. By contrast, 15 | the GNU General Public License is intended to guarantee your freedom to 16 | share and change all versions of a program--to make sure it remains free 17 | software for all its users. We, the Free Software Foundation, use the 18 | GNU General Public License for most of our software; it applies also to 19 | any other work released this way by its authors. You can apply it to 20 | your programs, too. 21 | 22 | When we speak of free software, we are referring to freedom, not 23 | price. Our General Public Licenses are designed to make sure that you 24 | have the freedom to distribute copies of free software (and charge for 25 | them if you wish), that you receive source code or can get it if you 26 | want it, that you can change the software or use pieces of it in new 27 | free programs, and that you know you can do these things. 28 | 29 | To protect your rights, we need to prevent others from denying you 30 | these rights or asking you to surrender the rights. Therefore, you have 31 | certain responsibilities if you distribute copies of the software, or if 32 | you modify it: responsibilities to respect the freedom of others. 33 | 34 | For example, if you distribute copies of such a program, whether 35 | gratis or for a fee, you must pass on to the recipients the same 36 | freedoms that you received. You must make sure that they, too, receive 37 | or can get the source code. And you must show them these terms so they 38 | know their rights. 39 | 40 | Developers that use the GNU GPL protect your rights with two steps: 41 | (1) assert copyright on the software, and (2) offer you this License 42 | giving you legal permission to copy, distribute and/or modify it. 43 | 44 | For the developers' and authors' protection, the GPL clearly explains 45 | that there is no warranty for this free software. For both users' and 46 | authors' sake, the GPL requires that modified versions be marked as 47 | changed, so that their problems will not be attributed erroneously to 48 | authors of previous versions. 49 | 50 | Some devices are designed to deny users access to install or run 51 | modified versions of the software inside them, although the manufacturer 52 | can do so. This is fundamentally incompatible with the aim of 53 | protecting users' freedom to change the software. The systematic 54 | pattern of such abuse occurs in the area of products for individuals to 55 | use, which is precisely where it is most unacceptable. Therefore, we 56 | have designed this version of the GPL to prohibit the practice for those 57 | products. If such problems arise substantially in other domains, we 58 | stand ready to extend this provision to those domains in future versions 59 | of the GPL, as needed to protect the freedom of users. 60 | 61 | Finally, every program is threatened constantly by software patents. 62 | States should not allow patents to restrict development and use of 63 | software on general-purpose computers, but in those that do, we wish to 64 | avoid the special danger that patents applied to a free program could 65 | make it effectively proprietary. To prevent this, the GPL assures that 66 | patents cannot be used to render the program non-free. 67 | 68 | The precise terms and conditions for copying, distribution and 69 | modification follow. 70 | 71 | TERMS AND CONDITIONS 72 | 73 | 0. Definitions. 74 | 75 | "This License" refers to version 3 of the GNU General Public License. 76 | 77 | "Copyright" also means copyright-like laws that apply to other kinds of 78 | works, such as semiconductor masks. 79 | 80 | "The Program" refers to any copyrightable work licensed under this 81 | License. Each licensee is addressed as "you". "Licensees" and 82 | "recipients" may be individuals or organizations. 83 | 84 | To "modify" a work means to copy from or adapt all or part of the work 85 | in a fashion requiring copyright permission, other than the making of an 86 | exact copy. The resulting work is called a "modified version" of the 87 | earlier work or a work "based on" the earlier work. 88 | 89 | A "covered work" means either the unmodified Program or a work based 90 | on the Program. 91 | 92 | To "propagate" a work means to do anything with it that, without 93 | permission, would make you directly or secondarily liable for 94 | infringement under applicable copyright law, except executing it on a 95 | computer or modifying a private copy. Propagation includes copying, 96 | distribution (with or without modification), making available to the 97 | public, and in some countries other activities as well. 98 | 99 | To "convey" a work means any kind of propagation that enables other 100 | parties to make or receive copies. Mere interaction with a user through 101 | a computer network, with no transfer of a copy, is not conveying. 102 | 103 | An interactive user interface displays "Appropriate Legal Notices" 104 | to the extent that it includes a convenient and prominently visible 105 | feature that (1) displays an appropriate copyright notice, and (2) 106 | tells the user that there is no warranty for the work (except to the 107 | extent that warranties are provided), that licensees may convey the 108 | work under this License, and how to view a copy of this License. If 109 | the interface presents a list of user commands or options, such as a 110 | menu, a prominent item in the list meets this criterion. 111 | 112 | 1. Source Code. 113 | 114 | The "source code" for a work means the preferred form of the work 115 | for making modifications to it. "Object code" means any non-source 116 | form of a work. 117 | 118 | A "Standard Interface" means an interface that either is an official 119 | standard defined by a recognized standards body, or, in the case of 120 | interfaces specified for a particular programming language, one that 121 | is widely used among developers working in that language. 122 | 123 | The "System Libraries" of an executable work include anything, other 124 | than the work as a whole, that (a) is included in the normal form of 125 | packaging a Major Component, but which is not part of that Major 126 | Component, and (b) serves only to enable use of the work with that 127 | Major Component, or to implement a Standard Interface for which an 128 | implementation is available to the public in source code form. A 129 | "Major Component", in this context, means a major essential component 130 | (kernel, window system, and so on) of the specific operating system 131 | (if any) on which the executable work runs, or a compiler used to 132 | produce the work, or an object code interpreter used to run it. 133 | 134 | The "Corresponding Source" for a work in object code form means all 135 | the source code needed to generate, install, and (for an executable 136 | work) run the object code and to modify the work, including scripts to 137 | control those activities. However, it does not include the work's 138 | System Libraries, or general-purpose tools or generally available free 139 | programs which are used unmodified in performing those activities but 140 | which are not part of the work. For example, Corresponding Source 141 | includes interface definition files associated with source files for 142 | the work, and the source code for shared libraries and dynamically 143 | linked subprograms that the work is specifically designed to require, 144 | such as by intimate data communication or control flow between those 145 | subprograms and other parts of the work. 146 | 147 | The Corresponding Source need not include anything that users 148 | can regenerate automatically from other parts of the Corresponding 149 | Source. 150 | 151 | The Corresponding Source for a work in source code form is that 152 | same work. 153 | 154 | 2. Basic Permissions. 155 | 156 | All rights granted under this License are granted for the term of 157 | copyright on the Program, and are irrevocable provided the stated 158 | conditions are met. This License explicitly affirms your unlimited 159 | permission to run the unmodified Program. The output from running a 160 | covered work is covered by this License only if the output, given its 161 | content, constitutes a covered work. This License acknowledges your 162 | rights of fair use or other equivalent, as provided by copyright law. 163 | 164 | You may make, run and propagate covered works that you do not 165 | convey, without conditions so long as your license otherwise remains 166 | in force. You may convey covered works to others for the sole purpose 167 | of having them make modifications exclusively for you, or provide you 168 | with facilities for running those works, provided that you comply with 169 | the terms of this License in conveying all material for which you do 170 | not control copyright. Those thus making or running the covered works 171 | for you must do so exclusively on your behalf, under your direction 172 | and control, on terms that prohibit them from making any copies of 173 | your copyrighted material outside their relationship with you. 174 | 175 | Conveying under any other circumstances is permitted solely under 176 | the conditions stated below. Sublicensing is not allowed; section 10 177 | makes it unnecessary. 178 | 179 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law. 180 | 181 | No covered work shall be deemed part of an effective technological 182 | measure under any applicable law fulfilling obligations under article 183 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or 184 | similar laws prohibiting or restricting circumvention of such 185 | measures. 186 | 187 | When you convey a covered work, you waive any legal power to forbid 188 | circumvention of technological measures to the extent such circumvention 189 | is effected by exercising rights under this License with respect to 190 | the covered work, and you disclaim any intention to limit operation or 191 | modification of the work as a means of enforcing, against the work's 192 | users, your or third parties' legal rights to forbid circumvention of 193 | technological measures. 194 | 195 | 4. Conveying Verbatim Copies. 196 | 197 | You may convey verbatim copies of the Program's source code as you 198 | receive it, in any medium, provided that you conspicuously and 199 | appropriately publish on each copy an appropriate copyright notice; 200 | keep intact all notices stating that this License and any 201 | non-permissive terms added in accord with section 7 apply to the code; 202 | keep intact all notices of the absence of any warranty; and give all 203 | recipients a copy of this License along with the Program. 204 | 205 | You may charge any price or no price for each copy that you convey, 206 | and you may offer support or warranty protection for a fee. 207 | 208 | 5. Conveying Modified Source Versions. 209 | 210 | You may convey a work based on the Program, or the modifications to 211 | produce it from the Program, in the form of source code under the 212 | terms of section 4, provided that you also meet all of these conditions: 213 | 214 | a) The work must carry prominent notices stating that you modified 215 | it, and giving a relevant date. 216 | 217 | b) The work must carry prominent notices stating that it is 218 | released under this License and any conditions added under section 219 | 7. This requirement modifies the requirement in section 4 to 220 | "keep intact all notices". 221 | 222 | c) You must license the entire work, as a whole, under this 223 | License to anyone who comes into possession of a copy. This 224 | License will therefore apply, along with any applicable section 7 225 | additional terms, to the whole of the work, and all its parts, 226 | regardless of how they are packaged. This License gives no 227 | permission to license the work in any other way, but it does not 228 | invalidate such permission if you have separately received it. 229 | 230 | d) If the work has interactive user interfaces, each must display 231 | Appropriate Legal Notices; however, if the Program has interactive 232 | interfaces that do not display Appropriate Legal Notices, your 233 | work need not make them do so. 234 | 235 | A compilation of a covered work with other separate and independent 236 | works, which are not by their nature extensions of the covered work, 237 | and which are not combined with it such as to form a larger program, 238 | in or on a volume of a storage or distribution medium, is called an 239 | "aggregate" if the compilation and its resulting copyright are not 240 | used to limit the access or legal rights of the compilation's users 241 | beyond what the individual works permit. Inclusion of a covered work 242 | in an aggregate does not cause this License to apply to the other 243 | parts of the aggregate. 244 | 245 | 6. Conveying Non-Source Forms. 246 | 247 | You may convey a covered work in object code form under the terms 248 | of sections 4 and 5, provided that you also convey the 249 | machine-readable Corresponding Source under the terms of this License, 250 | in one of these ways: 251 | 252 | a) Convey the object code in, or embodied in, a physical product 253 | (including a physical distribution medium), accompanied by the 254 | Corresponding Source fixed on a durable physical medium 255 | customarily used for software interchange. 256 | 257 | b) Convey the object code in, or embodied in, a physical product 258 | (including a physical distribution medium), accompanied by a 259 | written offer, valid for at least three years and valid for as 260 | long as you offer spare parts or customer support for that product 261 | model, to give anyone who possesses the object code either (1) a 262 | copy of the Corresponding Source for all the software in the 263 | product that is covered by this License, on a durable physical 264 | medium customarily used for software interchange, for a price no 265 | more than your reasonable cost of physically performing this 266 | conveying of source, or (2) access to copy the 267 | Corresponding Source from a network server at no charge. 268 | 269 | c) Convey individual copies of the object code with a copy of the 270 | written offer to provide the Corresponding Source. This 271 | alternative is allowed only occasionally and noncommercially, and 272 | only if you received the object code with such an offer, in accord 273 | with subsection 6b. 274 | 275 | d) Convey the object code by offering access from a designated 276 | place (gratis or for a charge), and offer equivalent access to the 277 | Corresponding Source in the same way through the same place at no 278 | further charge. You need not require recipients to copy the 279 | Corresponding Source along with the object code. If the place to 280 | copy the object code is a network server, the Corresponding Source 281 | may be on a different server (operated by you or a third party) 282 | that supports equivalent copying facilities, provided you maintain 283 | clear directions next to the object code saying where to find the 284 | Corresponding Source. Regardless of what server hosts the 285 | Corresponding Source, you remain obligated to ensure that it is 286 | available for as long as needed to satisfy these requirements. 287 | 288 | e) Convey the object code using peer-to-peer transmission, provided 289 | you inform other peers where the object code and Corresponding 290 | Source of the work are being offered to the general public at no 291 | charge under subsection 6d. 292 | 293 | A separable portion of the object code, whose source code is excluded 294 | from the Corresponding Source as a System Library, need not be 295 | included in conveying the object code work. 296 | 297 | A "User Product" is either (1) a "consumer product", which means any 298 | tangible personal property which is normally used for personal, family, 299 | or household purposes, or (2) anything designed or sold for incorporation 300 | into a dwelling. In determining whether a product is a consumer product, 301 | doubtful cases shall be resolved in favor of coverage. For a particular 302 | product received by a particular user, "normally used" refers to a 303 | typical or common use of that class of product, regardless of the status 304 | of the particular user or of the way in which the particular user 305 | actually uses, or expects or is expected to use, the product. A product 306 | is a consumer product regardless of whether the product has substantial 307 | commercial, industrial or non-consumer uses, unless such uses represent 308 | the only significant mode of use of the product. 309 | 310 | "Installation Information" for a User Product means any methods, 311 | procedures, authorization keys, or other information required to install 312 | and execute modified versions of a covered work in that User Product from 313 | a modified version of its Corresponding Source. The information must 314 | suffice to ensure that the continued functioning of the modified object 315 | code is in no case prevented or interfered with solely because 316 | modification has been made. 317 | 318 | If you convey an object code work under this section in, or with, or 319 | specifically for use in, a User Product, and the conveying occurs as 320 | part of a transaction in which the right of possession and use of the 321 | User Product is transferred to the recipient in perpetuity or for a 322 | fixed term (regardless of how the transaction is characterized), the 323 | Corresponding Source conveyed under this section must be accompanied 324 | by the Installation Information. But this requirement does not apply 325 | if neither you nor any third party retains the ability to install 326 | modified object code on the User Product (for example, the work has 327 | been installed in ROM). 328 | 329 | The requirement to provide Installation Information does not include a 330 | requirement to continue to provide support service, warranty, or updates 331 | for a work that has been modified or installed by the recipient, or for 332 | the User Product in which it has been modified or installed. Access to a 333 | network may be denied when the modification itself materially and 334 | adversely affects the operation of the network or violates the rules and 335 | protocols for communication across the network. 336 | 337 | Corresponding Source conveyed, and Installation Information provided, 338 | in accord with this section must be in a format that is publicly 339 | documented (and with an implementation available to the public in 340 | source code form), and must require no special password or key for 341 | unpacking, reading or copying. 342 | 343 | 7. Additional Terms. 344 | 345 | "Additional permissions" are terms that supplement the terms of this 346 | License by making exceptions from one or more of its conditions. 347 | Additional permissions that are applicable to the entire Program shall 348 | be treated as though they were included in this License, to the extent 349 | that they are valid under applicable law. If additional permissions 350 | apply only to part of the Program, that part may be used separately 351 | under those permissions, but the entire Program remains governed by 352 | this License without regard to the additional permissions. 353 | 354 | When you convey a copy of a covered work, you may at your option 355 | remove any additional permissions from that copy, or from any part of 356 | it. (Additional permissions may be written to require their own 357 | removal in certain cases when you modify the work.) You may place 358 | additional permissions on material, added by you to a covered work, 359 | for which you have or can give appropriate copyright permission. 360 | 361 | Notwithstanding any other provision of this License, for material you 362 | add to a covered work, you may (if authorized by the copyright holders of 363 | that material) supplement the terms of this License with terms: 364 | 365 | a) Disclaiming warranty or limiting liability differently from the 366 | terms of sections 15 and 16 of this License; or 367 | 368 | b) Requiring preservation of specified reasonable legal notices or 369 | author attributions in that material or in the Appropriate Legal 370 | Notices displayed by works containing it; or 371 | 372 | c) Prohibiting misrepresentation of the origin of that material, or 373 | requiring that modified versions of such material be marked in 374 | reasonable ways as different from the original version; or 375 | 376 | d) Limiting the use for publicity purposes of names of licensors or 377 | authors of the material; or 378 | 379 | e) Declining to grant rights under trademark law for use of some 380 | trade names, trademarks, or service marks; or 381 | 382 | f) Requiring indemnification of licensors and authors of that 383 | material by anyone who conveys the material (or modified versions of 384 | it) with contractual assumptions of liability to the recipient, for 385 | any liability that these contractual assumptions directly impose on 386 | those licensors and authors. 387 | 388 | All other non-permissive additional terms are considered "further 389 | restrictions" within the meaning of section 10. If the Program as you 390 | received it, or any part of it, contains a notice stating that it is 391 | governed by this License along with a term that is a further 392 | restriction, you may remove that term. If a license document contains 393 | a further restriction but permits relicensing or conveying under this 394 | License, you may add to a covered work material governed by the terms 395 | of that license document, provided that the further restriction does 396 | not survive such relicensing or conveying. 397 | 398 | If you add terms to a covered work in accord with this section, you 399 | must place, in the relevant source files, a statement of the 400 | additional terms that apply to those files, or a notice indicating 401 | where to find the applicable terms. 402 | 403 | Additional terms, permissive or non-permissive, may be stated in the 404 | form of a separately written license, or stated as exceptions; 405 | the above requirements apply either way. 406 | 407 | 8. Termination. 408 | 409 | You may not propagate or modify a covered work except as expressly 410 | provided under this License. Any attempt otherwise to propagate or 411 | modify it is void, and will automatically terminate your rights under 412 | this License (including any patent licenses granted under the third 413 | paragraph of section 11). 414 | 415 | However, if you cease all violation of this License, then your 416 | license from a particular copyright holder is reinstated (a) 417 | provisionally, unless and until the copyright holder explicitly and 418 | finally terminates your license, and (b) permanently, if the copyright 419 | holder fails to notify you of the violation by some reasonable means 420 | prior to 60 days after the cessation. 421 | 422 | Moreover, your license from a particular copyright holder is 423 | reinstated permanently if the copyright holder notifies you of the 424 | violation by some reasonable means, this is the first time you have 425 | received notice of violation of this License (for any work) from that 426 | copyright holder, and you cure the violation prior to 30 days after 427 | your receipt of the notice. 428 | 429 | Termination of your rights under this section does not terminate the 430 | licenses of parties who have received copies or rights from you under 431 | this License. If your rights have been terminated and not permanently 432 | reinstated, you do not qualify to receive new licenses for the same 433 | material under section 10. 434 | 435 | 9. Acceptance Not Required for Having Copies. 436 | 437 | You are not required to accept this License in order to receive or 438 | run a copy of the Program. Ancillary propagation of a covered work 439 | occurring solely as a consequence of using peer-to-peer transmission 440 | to receive a copy likewise does not require acceptance. However, 441 | nothing other than this License grants you permission to propagate or 442 | modify any covered work. These actions infringe copyright if you do 443 | not accept this License. Therefore, by modifying or propagating a 444 | covered work, you indicate your acceptance of this License to do so. 445 | 446 | 10. Automatic Licensing of Downstream Recipients. 447 | 448 | Each time you convey a covered work, the recipient automatically 449 | receives a license from the original licensors, to run, modify and 450 | propagate that work, subject to this License. You are not responsible 451 | for enforcing compliance by third parties with this License. 452 | 453 | An "entity transaction" is a transaction transferring control of an 454 | organization, or substantially all assets of one, or subdividing an 455 | organization, or merging organizations. If propagation of a covered 456 | work results from an entity transaction, each party to that 457 | transaction who receives a copy of the work also receives whatever 458 | licenses to the work the party's predecessor in interest had or could 459 | give under the previous paragraph, plus a right to possession of the 460 | Corresponding Source of the work from the predecessor in interest, if 461 | the predecessor has it or can get it with reasonable efforts. 462 | 463 | You may not impose any further restrictions on the exercise of the 464 | rights granted or affirmed under this License. For example, you may 465 | not impose a license fee, royalty, or other charge for exercise of 466 | rights granted under this License, and you may not initiate litigation 467 | (including a cross-claim or counterclaim in a lawsuit) alleging that 468 | any patent claim is infringed by making, using, selling, offering for 469 | sale, or importing the Program or any portion of it. 470 | 471 | 11. Patents. 472 | 473 | A "contributor" is a copyright holder who authorizes use under this 474 | License of the Program or a work on which the Program is based. The 475 | work thus licensed is called the contributor's "contributor version". 476 | 477 | A contributor's "essential patent claims" are all patent claims 478 | owned or controlled by the contributor, whether already acquired or 479 | hereafter acquired, that would be infringed by some manner, permitted 480 | by this License, of making, using, or selling its contributor version, 481 | but do not include claims that would be infringed only as a 482 | consequence of further modification of the contributor version. For 483 | purposes of this definition, "control" includes the right to grant 484 | patent sublicenses in a manner consistent with the requirements of 485 | this License. 486 | 487 | Each contributor grants you a non-exclusive, worldwide, royalty-free 488 | patent license under the contributor's essential patent claims, to 489 | make, use, sell, offer for sale, import and otherwise run, modify and 490 | propagate the contents of its contributor version. 491 | 492 | In the following three paragraphs, a "patent license" is any express 493 | agreement or commitment, however denominated, not to enforce a patent 494 | (such as an express permission to practice a patent or covenant not to 495 | sue for patent infringement). To "grant" such a patent license to a 496 | party means to make such an agreement or commitment not to enforce a 497 | patent against the party. 498 | 499 | If you convey a covered work, knowingly relying on a patent license, 500 | and the Corresponding Source of the work is not available for anyone 501 | to copy, free of charge and under the terms of this License, through a 502 | publicly available network server or other readily accessible means, 503 | then you must either (1) cause the Corresponding Source to be so 504 | available, or (2) arrange to deprive yourself of the benefit of the 505 | patent license for this particular work, or (3) arrange, in a manner 506 | consistent with the requirements of this License, to extend the patent 507 | license to downstream recipients. "Knowingly relying" means you have 508 | actual knowledge that, but for the patent license, your conveying the 509 | covered work in a country, or your recipient's use of the covered work 510 | in a country, would infringe one or more identifiable patents in that 511 | country that you have reason to believe are valid. 512 | 513 | If, pursuant to or in connection with a single transaction or 514 | arrangement, you convey, or propagate by procuring conveyance of, a 515 | covered work, and grant a patent license to some of the parties 516 | receiving the covered work authorizing them to use, propagate, modify 517 | or convey a specific copy of the covered work, then the patent license 518 | you grant is automatically extended to all recipients of the covered 519 | work and works based on it. 520 | 521 | A patent license is "discriminatory" if it does not include within 522 | the scope of its coverage, prohibits the exercise of, or is 523 | conditioned on the non-exercise of one or more of the rights that are 524 | specifically granted under this License. You may not convey a covered 525 | work if you are a party to an arrangement with a third party that is 526 | in the business of distributing software, under which you make payment 527 | to the third party based on the extent of your activity of conveying 528 | the work, and under which the third party grants, to any of the 529 | parties who would receive the covered work from you, a discriminatory 530 | patent license (a) in connection with copies of the covered work 531 | conveyed by you (or copies made from those copies), or (b) primarily 532 | for and in connection with specific products or compilations that 533 | contain the covered work, unless you entered into that arrangement, 534 | or that patent license was granted, prior to 28 March 2007. 535 | 536 | Nothing in this License shall be construed as excluding or limiting 537 | any implied license or other defenses to infringement that may 538 | otherwise be available to you under applicable patent law. 539 | 540 | 12. No Surrender of Others' Freedom. 541 | 542 | If conditions are imposed on you (whether by court order, agreement or 543 | otherwise) that contradict the conditions of this License, they do not 544 | excuse you from the conditions of this License. If you cannot convey a 545 | covered work so as to satisfy simultaneously your obligations under this 546 | License and any other pertinent obligations, then as a consequence you may 547 | not convey it at all. For example, if you agree to terms that obligate you 548 | to collect a royalty for further conveying from those to whom you convey 549 | the Program, the only way you could satisfy both those terms and this 550 | License would be to refrain entirely from conveying the Program. 551 | 552 | 13. Use with the GNU Affero General Public License. 553 | 554 | Notwithstanding any other provision of this License, you have 555 | permission to link or combine any covered work with a work licensed 556 | under version 3 of the GNU Affero General Public License into a single 557 | combined work, and to convey the resulting work. The terms of this 558 | License will continue to apply to the part which is the covered work, 559 | but the special requirements of the GNU Affero General Public License, 560 | section 13, concerning interaction through a network will apply to the 561 | combination as such. 562 | 563 | 14. Revised Versions of this License. 564 | 565 | The Free Software Foundation may publish revised and/or new versions of 566 | the GNU General Public License from time to time. Such new versions will 567 | be similar in spirit to the present version, but may differ in detail to 568 | address new problems or concerns. 569 | 570 | Each version is given a distinguishing version number. If the 571 | Program specifies that a certain numbered version of the GNU General 572 | Public License "or any later version" applies to it, you have the 573 | option of following the terms and conditions either of that numbered 574 | version or of any later version published by the Free Software 575 | Foundation. If the Program does not specify a version number of the 576 | GNU General Public License, you may choose any version ever published 577 | by the Free Software Foundation. 578 | 579 | If the Program specifies that a proxy can decide which future 580 | versions of the GNU General Public License can be used, that proxy's 581 | public statement of acceptance of a version permanently authorizes you 582 | to choose that version for the Program. 583 | 584 | Later license versions may give you additional or different 585 | permissions. However, no additional obligations are imposed on any 586 | author or copyright holder as a result of your choosing to follow a 587 | later version. 588 | 589 | 15. Disclaimer of Warranty. 590 | 591 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY 592 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT 593 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY 594 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, 595 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR 596 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM 597 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF 598 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 599 | 600 | 16. Limitation of Liability. 601 | 602 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING 603 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS 604 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY 605 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE 606 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF 607 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD 608 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), 609 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF 610 | SUCH DAMAGES. 611 | 612 | 17. Interpretation of Sections 15 and 16. 613 | 614 | If the disclaimer of warranty and limitation of liability provided 615 | above cannot be given local legal effect according to their terms, 616 | reviewing courts shall apply local law that most closely approximates 617 | an absolute waiver of all civil liability in connection with the 618 | Program, unless a warranty or assumption of liability accompanies a 619 | copy of the Program in return for a fee. 620 | 621 | END OF TERMS AND CONDITIONS 622 | 623 | How to Apply These Terms to Your New Programs 624 | 625 | If you develop a new program, and you want it to be of the greatest 626 | possible use to the public, the best way to achieve this is to make it 627 | free software which everyone can redistribute and change under these terms. 628 | 629 | To do so, attach the following notices to the program. It is safest 630 | to attach them to the start of each source file to most effectively 631 | state the exclusion of warranty; and each file should have at least 632 | the "copyright" line and a pointer to where the full notice is found. 633 | 634 | 635 | Copyright (C) 636 | 637 | This program is free software: you can redistribute it and/or modify 638 | it under the terms of the GNU General Public License as published by 639 | the Free Software Foundation, either version 3 of the License, or 640 | (at your option) any later version. 641 | 642 | This program is distributed in the hope that it will be useful, 643 | but WITHOUT ANY WARRANTY; without even the implied warranty of 644 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 645 | GNU General Public License for more details. 646 | 647 | You should have received a copy of the GNU General Public License 648 | along with this program. If not, see . 649 | 650 | Also add information on how to contact you by electronic and paper mail. 651 | 652 | If the program does terminal interaction, make it output a short 653 | notice like this when it starts in an interactive mode: 654 | 655 | Copyright (C) 656 | This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. 657 | This is free software, and you are welcome to redistribute it 658 | under certain conditions; type `show c' for details. 659 | 660 | The hypothetical commands `show w' and `show c' should show the appropriate 661 | parts of the General Public License. Of course, your program's commands 662 | might be different; for a GUI interface, you would use an "about box". 663 | 664 | You should also get your employer (if you work as a programmer) or school, 665 | if any, to sign a "copyright disclaimer" for the program, if necessary. 666 | For more information on this, and how to apply and follow the GNU GPL, see 667 | . 668 | 669 | The GNU General Public License does not permit incorporating your program 670 | into proprietary programs. If your program is a subroutine library, you 671 | may consider it more useful to permit linking proprietary applications with 672 | the library. If this is what you want to do, use the GNU Lesser General 673 | Public License instead of this License. But first, please read 674 | . --------------------------------------------------------------------------------