Defining a server

In this section, we will define the server. Let's look at the code for this. The necessary import statements will be called upon.

You can have a look at the code in our repository here: https://github.com/PacktPublishing/ROS-Robotics-Projects-SecondEdition/blob/master/chapter_4_ws/src/battery_simulator/src/battery_sim_server.py.

Note that we enable multiprocessing and call the necessary actionlib messages from our battery_simulator package:

#! /usr/bin/env python

import time
import rospy
from multiprocessing import Process
from std_msgs.msg import Int32, Bool
import actionlib
from battery_simulator.msg import battery_simAction, battery_simGoal, battery_simResult, battery_simFeedback

In the main function, we initialize the node and server's battery_simulator and start the server. To keep the server up and running, we use rospy.spin():

if __name__ == '__main__': 
rospy.init_node('BatterySimServer')
server = actionlib.SimpleActionServer('battery_simulator', battery_simAction, goalFun, False)
server.start()
rospy.spin()

The server calls upon the goalFun() function, which starts the batterySim() function in parallel. We assume that the goal from the client is Boolean. If the goal that's received is 0, then it means that the battery is in a discharging state and if it is 1, the battery is in a charging state. For ease of use, we will set ROS parameters so that we can enable or disable charging:

def goalFun(goal):
rate = rospy.Rate(2)
process = Process(target = batterySim)
process.start()
time.sleep(1)
if goal.charge_state == 0:
rospy.set_param("/MyRobot/BatteryStatus",goal.charge_state)
elif goal.charge_state == 1:
rospy.set_param("/MyRobot/BatteryStatus",goal.charge_state)

The batterySim() function checks for the parameter value and runs the battery's incremented or decremented code based on the charge_state goal it has received:

def batterySim():
battery_level = 100
result = battery_simResult()
while not rospy.is_shutdown():
if rospy.has_param("/MyRobot/BatteryStatus"):
time.sleep(1)
param = rospy.get_param("/MyRobot/BatteryStatus")
if param == 1:
if battery_level == 100:
result.battery_status = "Full"
server.set_succeeded(result)
print "Setting result!!!"
break
else:
print "Charging...currently, "
battery_level += 1
print battery_level
time.sleep(4)
elif param == 0:
print "Discharging...currently, "
battery_level -= 1
print battery_level
time.sleep(2)

If the charging is full, then the result is set as successful using the server.set_succeeded(result) function. Now, let's define the client.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.220.126.5