Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Implement locking service #15

Open
wants to merge 6 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion src/nautilus_scripts/setup.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,4 +8,4 @@
packages=['subway_car', 'nautilus_utils', 'coral_bleaching'],
package_dir={'': 'src'})

setup(**setup_args)
setup(**setup_args)
22 changes: 13 additions & 9 deletions src/robot_module/CMakeLists.txt
Original file line number Diff line number Diff line change
Expand Up @@ -8,8 +8,10 @@ project(robot_module)
## if COMPONENTS list like find_package(catkin REQUIRED COMPONENTS xyz)
## is used, also find other catkin packages
find_package(catkin REQUIRED COMPONENTS
roscpp
rospy
std_msgs
message_generation
)

## System dependencies are found with CMake's conventions
Expand Down Expand Up @@ -53,11 +55,11 @@ catkin_python_setup()
# )

## Generate services in the 'srv' folder
# add_service_files(
# FILES
# Service1.srv
# Service2.srv
# )
add_service_files(
FILES
acquire_lock.srv
release_lock.srv
)

## Generate actions in the 'action' folder
# add_action_files(
Expand All @@ -67,10 +69,10 @@ catkin_python_setup()
# )

## Generate added messages and services with any dependencies listed here
# generate_messages(
# DEPENDENCIES
# std_msgs
# )
generate_messages(
DEPENDENCIES
std_msgs
)

################################################
## Declare ROS dynamic reconfigure parameters ##
Expand Down Expand Up @@ -193,6 +195,8 @@ include_directories(

catkin_install_python(PROGRAMS
scripts/test.py
scripts/example_lock_client.py
scripts/lock_server.py
DESTINATION ${CATKIN_PACKAGE_BIN_DESTINATION}
)

Expand Down
27 changes: 27 additions & 0 deletions src/robot_module/doc/lock_service.puml
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
@startuml Locking Service Sequence Diagram
Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

PUML is a diagram generator we use at Microsoft, it's free and is a nice way to create pictures from text.

You can generate the diagram by copying this into the bottom of the plant uml website or downloading a local viewer (there's a vs code extension called PlantUml by Jebbs that has some instructions on that)

Also here's a link to the image

title Locking Service Sequence Diagram
participant Auto_Script as auto
participant UI as ui
participant Lock_Service as ls

ls -> ui : Sends enable message over topic

...

auto -> ls : Sends a lock request
ls -> ui : Send disable message over topic
ls --> auto : Send lock confirmation

...

Second_Auto_Script -> ls : Sends lock request
return Send failure message
Second_Auto_Script -> Second_Auto_Script : Periodically ping\nto try and get lock

...

auto -> ls : Send lock release message
return Acknowledge lock release (no need to wait)
ls -> ui : Send enable message over topic

@enduml
5 changes: 5 additions & 0 deletions src/robot_module/package.xml
Original file line number Diff line number Diff line change
Expand Up @@ -50,10 +50,15 @@
<!-- <doc_depend>doxygen</doc_depend> -->
<buildtool_depend>catkin</buildtool_depend>
<build_depend>rospy</build_depend>
<build_depend>roscpp</build_depend>
<build_depend>std_msgs</build_depend>
<build_depend>message_generation</build_depend>
<build_export_depend>rospy</build_export_depend>
<build_export_depend>roscpp</build_export_depend>
<build_export_depend>std_msgs</build_export_depend>
<exec_depend>message_runtime</exec_depend>
<exec_depend>rospy</exec_depend>
<exec_depend>roscpp</exec_depend>
<exec_depend>std_msgs</exec_depend>


Expand Down
23 changes: 23 additions & 0 deletions src/robot_module/scripts/example_lock_client.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
#!/usr/bin/env python3

from locks.lock_service_client import LockClient
import time
import rospy

if __name__ == '__main__':
rospy.init_node('test_lock_client')
rospy.on_shutdown(lambda: rospy.loginfo("shutting down test client"))

# Test case 1 : manage lock using the with statement
with LockClient('test_client') as lc:
time.sleep(0.25)
rospy.loginfo("lock acquired automatically")
rospy.loginfo("lock released automatically")


# Test case 2 : manage lock manually
lc = LockClient('test_client')
lc.lock()
rospy.loginfo("lock acquired manually")
lc.unlock()
rospy.loginfo("lock released manually")
7 changes: 7 additions & 0 deletions src/robot_module/scripts/lock_server.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
#!/usr/bin/env python3

from locks.lock_service_server import LockServer

if __name__ == '__main__':
ls = LockServer()
ls.init_server()
4 changes: 3 additions & 1 deletion src/robot_module/scripts/test.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,6 @@
from robot_module import RobotModule
#!/usr/bin/env python3

from robot_module.main import RobotModule
import time

robot = RobotModule("test")
Expand Down
2 changes: 1 addition & 1 deletion src/robot_module/setup.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@
from catkin_pkg.python_setup import generate_distutils_setup

setup_args = generate_distutils_setup(
packages=['robot_module'],
packages=['robot_module', 'locks', 'services'],
package_dir={'': 'src'}
)

Expand Down
47 changes: 47 additions & 0 deletions src/robot_module/src/locks/lock_service_client.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,47 @@
#!/usr/bin/env python3

from robot_module.srv import acquire_lock, release_lock
from std_msgs.msg import String
import rospy
import time

class LockClient:
def __init__(self, name):
self.name = name


def __enter__(self):
acquire_attempts = 0
lock_acquired = self.lock()

# use exponential backoff to try again without flooding network
while not lock_acquired:
rospy.loginfo("Couldn't acquire the lock, trying again")
Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Consider changing to a debug message instead, this will pop up whenever a node is waiting on the lock every once in a while.

time.sleep(1 * (2**acquire_attempts))
acquire_attempts += 1

lock_acquired = self.lock()


def __exit__(self, exc_type, exc_value, traceback):
self.unlock()


def lock(self) -> bool:
rospy.wait_for_service('acquire_service')
try:
acquire_lock_fn = rospy.ServiceProxy('acquire_service', acquire_lock)
lock_server_response = acquire_lock_fn(self.name)
return lock_server_response.result
except rospy.ServiceException as e:
rospy.logerr("couldn't access acquire_service service")
return False


def unlock(self):
rospy.wait_for_service('release_service')
try:
release_lock_fn = rospy.ServiceProxy('release_service', release_lock)
release_lock_fn(self.name)
except rospy.ServiceException as e:
rospy.logerr("couldn't access release_service service... something's broken, destroy everything and try again")
58 changes: 58 additions & 0 deletions src/robot_module/src/locks/lock_service_server.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,58 @@
#!/usr/bin/env python3

from threading import Lock
from robot_module.srv import acquire_lock, release_lock
from std_msgs.msg import String, Bool
import rospy

# Consider tossing this into a command line parameter for on-the-fly retargeting
ui_enablement_topic = '/ui/enablement'

class LockServer:
def __init__(self):
self.lock_holder = None
self.ui_publisher = None
self.mutex = Lock()


def handle_acquire_request(self, req):
with self.mutex:
req_name = req.requester

# If no autonomous script is holding on, preempt our UI
if self.lock_holder is None:
self.lock_holder = req_name
self.ui_publisher.publish(False)
return True

# Be forgiving and allow a single caller to acquire a lock more than once
return self.lock_holder == req_name


def handle_release_request(self, req):
with self.mutex:
req_name = req.requester

# If the client holding the lock is releasing, give control back to UI
if self.lock_holder is not None and req_name == self.lock_holder:
self.lock_holder = None
self.ui_publisher.publish(True)
return True

return False


def init_server(self):
rospy.init_node('lock_server')
rospy.on_shutdown(lambda : rospy.loginfo("Shutting down Lock Server"))

rospy.loginfo("Starting Lock Server")
self.ui_publisher = rospy.Publisher(ui_enablement_topic, Bool, queue_size=1)

# services can't take in extra parameters like a subscriber can,
# so we have to use this funny workaround
# https://answers.ros.org/question/247540/pass-parameters-to-a-service-handler-in-rospy/
acquire_service = rospy.Service('acquire_service', acquire_lock, lambda msg: self.handle_acquire_request(msg))
release_service = rospy.Service('release_service', release_lock, lambda msg: self.handle_release_request(msg))

rospy.spin()
3 changes: 0 additions & 3 deletions src/robot_module/src/robot_module/__init__.py

This file was deleted.

2 changes: 2 additions & 0 deletions src/robot_module/src/robot_module/image_sub.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
#!/usr/bin/env python3

import rospy
from .subscriber import ServerSub

Expand Down
4 changes: 3 additions & 1 deletion src/robot_module/src/robot_module/main.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
#!/usr/bin/env python3

import rospy
from .services.movement import Movement
from services.movement import Movement

# Service topics
# subscriber_topics = {
Expand Down
3 changes: 3 additions & 0 deletions src/robot_module/srv/acquire_lock.srv
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
string requester
---
bool result
3 changes: 3 additions & 0 deletions src/robot_module/srv/release_lock.srv
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
string requester
---
bool result