Skip to content

Commit

Permalink
Merge pull request #1 from AleNovelli/thread_branch
Browse files Browse the repository at this point in the history
Thread branch
  • Loading branch information
AleNovelli authored Aug 30, 2022
2 parents fe45cc1 + dd80dc2 commit 9fd7441
Show file tree
Hide file tree
Showing 15 changed files with 219 additions and 99 deletions.
96 changes: 58 additions & 38 deletions drivers/main.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,9 +14,9 @@
args=parser.parse_args()


log = logging.getLogger("strip_motors_log")
log = logging.getLogger("main")
log.setLevel(logging.INFO)
formatter = logging.Formatter('%(asctime)s :: %(levelname)s :: %(message)s')
formatter = logging.Formatter('%(asctime)s :: %(levelname)s :: %(filename)s :: %(message)s')
stream_handler = logging.StreamHandler()
stream_handler.setFormatter(formatter)
log.addHandler(stream_handler)
Expand Down Expand Up @@ -49,8 +49,7 @@

# function to determine if a file is a modbus proxy
def file_is_proxy(file_name):
#if "proxy" in file_name:
if "monitor" in file_name:
if "proxy" in file_name:
return 1
else:
return 0
Expand Down Expand Up @@ -78,7 +77,7 @@ def file_is_proxy(file_name):
if args.simulator:
log.info("Launching master clock simulator")
cmd="python master_clock_sim.py"
#mc_proc = subprocess.Popen(cmd.split(), stdout=subprocess.PIPE, cwd="./utils")
mc_proc = subprocess.Popen(cmd.split(), stdout=subprocess.PIPE, cwd="./utils")
#time.sleep(3)
#cmd = "python fault_acknowledge.py"
#ackn_proc = subprocess.Popen(cmd.split(), stdout=subprocess.PIPE)
Expand All @@ -98,71 +97,92 @@ def file_is_proxy(file_name):
log.info("Connection to TCS made, ready to accept comands.")

while True:

#controllo che tutti i processi permanenti siano ancora in funzione
for proc_name, proc in zip(perm_files_list, perm_processes):

if proc.poll()!=None:
raise Exception("PERMANENT SUBPROCESS {} HAS CRASHED!!!".format(proc_name))

raise Exception("Permanent process crashed: {}".format(proc_name))
#ricevo eventuali messaggi
message = pub_sub.get_message()
if message and message["data"] != 1:#<--- rivedere da dove arriva

message_channel=(message["channel"]).decode("utf-8")

if message_channel==channel_motion_commands:
command = msgpack.unpackb(message["data"])
curr_motion=(redis_client.get(current_motion_var)).decode("utf-8")
#print("MOTION: ", curr_motion)
if curr_motion=="none":
redis_client.set(current_motion_var, command["motion"])
redis_client.publish(channel_motion_answerbacks, "motion '" + command["motion"] + "' RUNNING")

print("motion '" + command["motion"] + "' LAUNCHED")
redis_client.set(current_motion_var, command["motion"])

cmd= "python "+motion_comands[command["motion"]]+" "+json.dumps(command["parameters"]).replace(" ", "")
print(cmd)

#Per Windows
#motion_proc = subprocess.Popen(cmd.split(), cwd="./motion", shell=True)

#Per LINUX
motion_proc = subprocess.Popen(cmd.split(), cwd="./motion")#, shell=True , preexec_fn=os.setsid)
motion_proc = subprocess.Popen(cmd.split(), cwd="./motion")

redis_client.publish(channel_motion_answerbacks, "motion '" + command["motion"] + "' RUNNING")
log.info("Comand '" + command["motion"] + "' launched -- parameters: "+str(command["parameters"]))
log.debug("Program executed: "+cmd)

else:
redis_client.publish(channel_motion_answerbacks, "new motion '" + command["motion"] + "' FAILED")
redis_client.publish(channel_motion_answerbacks, "Running: "+ curr_motion)
print("motion '" + command["motion"] + "' FAILED\n"+"Running: "+ curr_motion)
log.warning("Comand '" + command["motion"] + "' FAILED\n"+"Already running: "+ curr_motion)

elif message_channel==channel_fault_alert:
log.warning("Fault detected")
if motion_proc:
if motion_proc.poll()==None:
#Per LINUX
#Per LINUX
#os.killpg(os.getpgid(pro.pid), signal.SIGTERM)
motion_proc.terminate()

#per Windows
#kill=subprocess.Popen("TASKKILL /F /PID {pid} /T".format(pid=motion_proc.pid))
#kill.wait()
print("PROCESS KILLEd")
log.warning("Current motion was terminated")

except redis.exceptions.ConnectionError:
#traceback.print_exc()
log.critical("Failing to connect to the Redis server at: {}:{:d}".format(redis_ip, redis_port))
#traceback.print_exc()
except Exception as exception:
print("\nGENERAL ERROR:")
#if the list with all the permanent processes has already been defined
if perm_processes and perm_files_list:
for process, proc_name in zip(perm_processes, perm_files_list):
print("-------\nProcess: {}".format(proc_name))
if process.poll()!=None:
print("Process was still running")
else:
print("Process seemed to have crashed")
process.terminate()
output, error = process.communicate()
if output:
print("Output:")
print(output.decode("utf-8"))
if error:
print("Errors:")
print(error.decode("utf-8"))
traceback.print_exc()
if "Permanent process crashed:" in str(exception):
log.exception(str(exception))
log.info("Shutting down all processes")

#if the list with all the permanent processes has already been defined
if perm_processes and perm_files_list:
for process in perm_processes:
process.terminate()
"""
for process, proc_name in zip(perm_processes, perm_files_list):
print("-------\nProcess: {}".format(proc_name))
if process.poll()!=None:
print("Process was still running")
else:
print("Process seemed to have crashed")
process.terminate()
output, error = process.communicate()
if output:
print("Output:")
print(output.decode("utf-8"))
if error:
print("Errors:")
print(error.decode("utf-8"))
"""
if motion_proc:
motion_proc.terminate()
#traceback.print_exc()
else:
log.exception(str(exception))
log.info("Shutting down all processes")
if perm_processes and perm_files_list:
for process in perm_processes:
process.terminate()

if motion_proc:
motion_proc.terminate()
#traceback.print_exc()

33 changes: 22 additions & 11 deletions drivers/motion/calibration_sequence.py
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,14 @@
import redis
import sys

import logging
log = logging.getLogger("calibration_motion")
log.setLevel(logging.INFO)
formatter = logging.Formatter('%(asctime)s :: %(levelname)s :: %(filename)s :: %(message)s')
stream_handler = logging.StreamHandler()
stream_handler.setFormatter(formatter)
log.addHandler(stream_handler)

driver_params=json.load(open("../configuration/TCS_driver_parameters.json"))

az_ip=driver_params["ip&ports"]["az_proxy_ip"]
Expand Down Expand Up @@ -65,6 +73,7 @@
modbus_alt=None
modbus_az=None
try:
log.info("Calibration sequence starting")
if np.any(np.array(params).T[0]>alt_max) or np.any(np.array(params).T[0]<alt_min):
redis_answerback="invalid parameters"
raise Exception("Moving telescope outside of elevation safety range")
Expand Down Expand Up @@ -95,7 +104,7 @@
lb.Enable_Motion(modbus_alt, "alt", alt_status, software_timeout)

for j, position in enumerate(params):
print("Point", j, position)
log.debug("Reaching position {:d}: alt {:f}, az {:f}, duration {:f}".format(j, position[0], position[1],position[2]))
#a=input("---")
final_alt, final_az, duration = position

Expand Down Expand Up @@ -125,7 +134,7 @@
#az = lb.Read_32_bit_floats(modbus_az, azdef.ax_mpos)[0]


print(alt,az)
log.debug("Starting position: alt {:d}, az{:d}".format(alt, az))
#input("---")
start = np.array([[az, alt]])
start = SkyCoord(start, unit="degree", frame='altaz')
Expand All @@ -146,7 +155,7 @@
raise Exception("CRITICAL ERROR!\n" +
"Error in calculating the trjectory to avoid the sun")
elif traj_lenght==1:
print("The telescope is already in position!!!")
log.debug("The telescope is already in position!!!")
lb.Disconnect_Controller(modbus_az, "Azimuth")
lb.Disconnect_Controller(modbus_alt, "Elevation")
exit()
Expand All @@ -173,8 +182,8 @@
#mediating the communications between the controllers during the jog
for i in range(1, traj_lenght):
# printing on terminal the motion needed by the two axis (only one axis move at a time)
print("AZ: " + str(az_traj[i - 1]) + "-->" + str(az_traj[i]))
print("ALT: " + str(alt_traj[i - 1]) + "-->" + str(alt_traj[i]))
log.debug("moving AZ: " + str(az_traj[i - 1]) + "-->" + str(az_traj[i]))
log.debug("moving ALT: " + str(alt_traj[i - 1]) + "-->" + str(alt_traj[i]))

# if it is the turn of the azimuth azis to move
if az_traj[i]!=az_traj[i-1] and alt_traj[i]==alt_traj[i-1]:
Expand All @@ -185,12 +194,12 @@
modbus_az.write_single_coil(azdef.io_user_azimuth_idle, False)
# giving the signal to the alt controller has reached idle state
modbus_alt.write_single_coil(altdef.in_user_azimuth_idle, True)
print("AZ Moving!!!!")
log.debug("AZ Moving!!!!")
elif alt_traj[i] != alt_traj[i - 1] and az_traj[i] == az_traj[i - 1]:
lb.Wait_until_coils(modbus_alt, altdef.io_user_elevation_idle, motion_timeout)
modbus_alt.write_single_coil(altdef.io_user_elevation_idle, False)
modbus_az.write_single_coil(azdef.in_user_elevation_idle, True)
print("ALT Moving!!!!")
log.debug("ALT Moving!!!!")
else:
raise Exception("CRITICAL ERROR:\n The trajectory calculated to avoid the sun is not valid!!")

Expand All @@ -199,7 +208,7 @@
lb.Wait_until_register(modbus_az, azdef.current_point, j, motion_timeout)
lb.Wait_until_register(modbus_alt, altdef.current_point, j, motion_timeout)

print("Waiting: ", duration)
log.debug("Waiting: {:d} seconds".format(duration))
#waiting the specified time
time.sleep(duration)

Expand All @@ -211,9 +220,11 @@
answerback = {'type': "answerback", 'from': "calibration",
"answer": "success"}
redis_client.publish(channel_motion_answerback, msgpack.packb(answerback))
log.info("Calibration sequence terminated")

except:
print("Error in running calibration motion:", redis_answerback)
except Exception as e:
log.critical("Error in running calibration motion:", redis_answerback)
log.exception(e)
redis_client = redis.Redis(host=redis_ip, port=redis_port)
answerback = {'type': "answerback", 'from': "calibration",
"answer": redis_answerback}
Expand All @@ -223,4 +234,4 @@
if modbus_az:
lb.Disconnect_Controller(modbus_az, "Azimuth")
if modbus_alt:
lb.Disconnect_Controller(modbus_alt, "Elevation")
lb.Disconnect_Controller(modbus_alt, "Elevation")
17 changes: 14 additions & 3 deletions drivers/motion/define_position.py
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,14 @@
import redis
import sys

import logging
log = logging.getLogger("defpos_motion")
log.setLevel(logging.INFO)
formatter = logging.Formatter('%(asctime)s :: %(levelname)s :: %(filename)s :: %(message)s')
stream_handler = logging.StreamHandler()
stream_handler.setFormatter(formatter)
log.addHandler(stream_handler)

param_file=open("../configuration/TCS_driver_parameters.json")
driver_params=json.load(param_file)

Expand Down Expand Up @@ -52,6 +60,7 @@
modbus_alt=None
modbus_az=None
try:
log.info("Executing pointing position redefinition")
modbus_az = ModbusClient(host=az_ip, port=az_port, debug=False) #preparing modbus connection to Azimuth Controller
modbus_alt = ModbusClient(host=alt_ip, port=alt_port, debug=False) #preparing modbus connection to Elevation Controller

Expand Down Expand Up @@ -99,9 +108,11 @@
answerback = {'type': "answerback", 'from': "redefine_pos",
"answer": "success"}
redis_client.publish(channel_motion_answerback, msgpack.packb(answerback))
log.info("Pointing position correctly redefined")

except:
print("Error in redefining telescope position:", redis_answerback)
except Exception as e:
log.critical("Error in redefining telescope position:", redis_answerback)
log.exception(e)
redis_client = redis.Redis(host=redis_ip, port=redis_port)
answerback = {'type': "answerback", 'from': "redefine_pos",
"answer": redis_answerback}
Expand All @@ -111,4 +122,4 @@
if modbus_az:
lb.Disconnect_Controller(modbus_az, "Azimuth")
if modbus_alt:
lb.Disconnect_Controller(modbus_alt, "Elevation")
lb.Disconnect_Controller(modbus_alt, "Elevation")
17 changes: 14 additions & 3 deletions drivers/motion/move_to_start.py
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,14 @@

#from utils.redis_definitions import *

import logging
log = logging.getLogger("moveto_motion")
log.setLevel(logging.INFO)
formatter = logging.Formatter('%(asctime)s :: %(levelname)s :: %(filename)s :: %(message)s')
stream_handler = logging.StreamHandler()
stream_handler.setFormatter(formatter)
log.addHandler(stream_handler)

driver_params=json.load(open("../configuration/TCS_driver_parameters.json"))

az_ip=driver_params["ip&ports"]["az_proxy_ip"]
Expand Down Expand Up @@ -63,6 +71,7 @@
modbus_alt=None
modbus_az=None
try:
log.info("Telescope motion to new fixed position started")
if alt>alt_max or alt<alt_min:
redis_answerback="invalid parameters"
raise Exception("Moving telescope outside of elevation safety range")
Expand Down Expand Up @@ -120,7 +129,7 @@
#start = SkyCoord(start, unit="degree", frame='altaz')
#start.az.wrap_at("180d", inplace=True)
if start.separation(finish).deg<1/36000:
print("The telescope is already positioned correctly with a precision higher than 1/10 arcsec")
log.debug("The telescope is already positioned correctly with a precision higher than 1/10 arcsec")
else:
az_traj, alt_traj = lb.Traj_to_Pos(sun, start, finish, elongation, alt_max, alt_min)

Expand Down Expand Up @@ -177,9 +186,11 @@
answerback = {'type': "answerback", 'from': "move to",
"answer":"success"}
redis_client.publish(channel_motion_answerback, msgpack.packb(answerback))
log.info("Telescope motion to new fixed position terminated")

except Exception:
print("Error in running move_to_start motion:", redis_answerback)
except Exception as e:
log.critical("Error in running move_to_start motion:", redis_answerback)
log.exception(e)
redis_client = redis.Redis(host=redis_ip, port=redis_port)
answerback = {'type': "answerback", 'from': "move to",
"answer": redis_answerback}
Expand Down
17 changes: 14 additions & 3 deletions drivers/motion/nominal_survey.py
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,14 @@
import redis
import sys

import logging
log = logging.getLogger("nominal_motion")
log.setLevel(logging.INFO)
formatter = logging.Formatter('%(asctime)s :: %(levelname)s :: %(filename)s :: %(message)s')
stream_handler = logging.StreamHandler()
stream_handler.setFormatter(formatter)
log.addHandler(stream_handler)

driver_params=json.load(open("../configuration/TCS_driver_parameters.json"))

az_ip=driver_params["ip&ports"]["az_proxy_ip"]
Expand Down Expand Up @@ -57,6 +65,7 @@
modbus_alt=None
modbus_az=None
try:
log.info("Nominal survey started")
if alt>alt_max or alt<alt_min:
redis_answerback="invalid parameters"
raise Exception("Moving telescope outside of elevation safety range")
Expand Down Expand Up @@ -134,9 +143,11 @@
answerback = {'type': "answerback", 'from': "nominal",
"answer": "success"}
redis_client.publish(channel_motion_answerback, msgpack.packb(answerback))
log.info("Nominal survey terminated")

except:
print("Error in running nominal_survey motion:", redis_answerback)
except Exception as e:
log.critical("Error in running nominal_survey motion:", redis_answerback)
log.exception(e)
redis_client = redis.Redis(host=redis_ip, port=redis_port)
answerback = {'type': "answerback", 'from': "nominal",
"answer": redis_answerback}
Expand All @@ -146,4 +157,4 @@
if modbus_az:
lb.Disconnect_Controller(modbus_az, "Azimuth")
if modbus_alt:
lb.Disconnect_Controller(modbus_alt, "Elevation")
lb.Disconnect_Controller(modbus_alt, "Elevation")
Loading

0 comments on commit 9fd7441

Please sign in to comment.