Python script getting stuck after closing CoppeliaSim using zmq remote api

Typically: "How do I... ", "How can I... " questions
Post Reply
r_dhak
Posts: 18
Joined: 02 Jan 2019, 15:10

Python script getting stuck after closing CoppeliaSim using zmq remote api

Post by r_dhak »

So I am using zmq remote api client to,
  • Launch CoppeliaSim
  • Load Scene
  • Start Simulation
  • Stop Simulation
  • Close CoppeliaSim
But when I close CoppeliaSim the Python script is getting stuck.

Following is my interface script

Code: Select all

# Imports
import os, sys, time
import  multiprocessing
import subprocess
import signal
#from RL_control.SimConn import sim # using zmq client instead
from SimConn.zmqRemoteApi import RemoteAPIClient
from utils.print_load import print_load_1, print_load_2


class sim_interface(object):
	sim_open = []

	def __init__(self, scene_dir, scene, port_num):
		self.scene_dir = scene_dir
		self.scene = scene
		self.port_num = port_num
		self.sim = []
		self.client = []
		self.sim_open = self.sim_open

#############################################################################################################
	def launch_sim(self):
		print('Launching CoppeliaSim simulator')
		print_load_2()
		args = ['/home/lab-rai05/CoppeliaSim/coppeliaSim.sh', '-gREMOTEAPISERVERSERVICE_' + str(self.port_num) + '_FALSE_TRUE']
		self.sim_open = subprocess.Popen(args, preexec_fn=os.setsid)

#############################################################################################################
	def get_sim_state(self):
		self.simulationState = self.sim.getSimulationState()
		return(self.simulationState)

#############################################################################################################
	def terminate_sim(self):
		os.killpg(os.getpgid(self.sim_open.pid), signal.SIGTERM)  # Send the signal to all the process groups

#############################################################################################################
	def connect_sim(self):
		#simulation connection setup
		self.client = RemoteAPIClient('localhost',self.port_num)
		self.sim = self.client.getObject('sim')
		defaultIdleFps = self.sim.getInt32Param(self.sim.intparam_idle_fps)
		self.sim.setInt32Param(self.sim.intparam_idle_fps, 0)
		sim_err = 0
		while True:
			self.client.setStepping(True)
			print('----------------------------------------------------------------------------------------', '\n',)
			print('Connecting to remote API client and starting simulation')
			self.sim.loadScene(self.scene_dir + '/' + self.scene + '.ttt')
			print_load_2()
			time.sleep(0.5)
			sim_err = self.sim.startSimulation()
			if sim_err > -1:
				break
			else:
				time.sleep(0.2)
				print('Failed connecting to	remote	API	server')
		print('Connection	success!', '\n')
		print('----------------------------------------------------------------------------------------')

#############################################################################################################
	def start_sim(self):
		self.launch_sim()
		time.sleep(5)
		self.connect_sim()
		self.get_sim_state()

#############################################################################################################
	def stop_sim(self):
		while self.get_sim_state() != self.sim.simulation_stopped:
			print("Stopping Simulation")
			print_load_2()
			self.sim.stopSimulation()

			print("Terminating Simulation")
			print_load_2()
			self.terminate_sim()
			time.sleep(10) # Waiting for simulation subprocess to terminate
			print("CoppeliaSim Closed")
		else:
			print("Simulation already stopped")
#############################################################################################################
In the main script when I want to terminate the training and close CoppeliaSim, the main script gets stuck.
Main script:

Code: Select all

# Imports
import numpy as np
np.set_printoptions(precision=4)
from utils.print_table import print_tables
from utils.print_load import print_load_1
from init_modules import init
import shutil

#############################################################################################################
print_tab = print_tables()
RL = init()
RL.init_modules()
print('[Robot Environment] : ', 'Environment Setup Complete')

#############################################################################################################
def close_sim():
	RL.sim_connect.stop_sim()
	shutil.rmtree(RL.dir_cl.model_dir)
	shutil.rmtree(RL.dir_cl.model_results_data_path)
	shutil.rmtree(RL.dir_cl.model_results_plot_path)

#############################################################################################################
# getting and printing object handles
handles = RL.rob_env.rob_handles
print_tab.handle_table(handles)

#############################################################################################################
# resetting simulation environemnt to defined default configuration
reset = RL.sim_env.reset()

#############################################################################################################
# getting initial observation
init_obs = RL.rob_env.rob_obs
print_tab.obs_table(init_obs)

#############################################################################################################
# Start_Training prompt
print('[Robot Environment] : ', "Start Training RL Agent with Defined Parameters?")
RL.params_cl.print_params()
print(' ---------- [y or n] ----------')
start_training = input('[Robot Environment] : ' "Start Training: ")

#############################################################################################################
# Starting training loop
if (start_training == 'n'):
	close_sim()
	print('[Robot Environment] : ', "Training Cancelled")
#	raise Exception('[Robot Environment] : ', "Training Cancelled")
https://drive.google.com/file/d/1ALdHtE ... sp=sharing
Could you let me know why exactly its happening.

Thank You.

r_dhak
Posts: 18
Joined: 02 Jan 2019, 15:10

Re: Python script getting stuck after closing CoppeliaSim using zmq remote api

Post by r_dhak »

I found the mistake.
In the interface script I was checking for the simulation state using a while loop, which was causing the problem.
Even after closing CoppeliaSim the interface script was checking for simulation state because of the while loop.

Sorry for the inconvenience.

Post Reply