Browse Source

Code cleaning

master
Carlos Reding 1 year ago
parent
commit
19fcf10c06
1 changed files with 135 additions and 0 deletions
  1. 135
    0
      srv_controller.py

+ 135
- 0
srv_controller.py View File

@@ -0,0 +1,135 @@
import threading, sys, time, queue
from puppeteer import Controller, HardwareTest, TemperatureTest,\
ProtocolTest, ExportData, QueueStatus, CancelProtocol,\
CameraRepetitions
from pupuicon import InitNetwork, NetworkOperator

# Hack
# FIXME: Does it mean `translator have should it's own package?.
sys.modules['translator'] = sys.modules['pupuicon.translator']
del sys.modules['pupuicon.translator']

# Create `cancel' and `gui' switches. Default to FALSE.
cancel_switch = threading.Event()
gui_status = threading.Event()
protocol_status = threading.Event()
# Check for presence of queueFile after restarting LiMO, set `protocol_status'
# accordingly:

Replicates, LagReplicates = CameraRepetitions()

while True:
try:
print("GUI status is: " + str(gui_status.is_set()))
# Set server-side
Box_Socket = InitNetwork(PORT=10011, MAX_CONNECTIONS=1)
# Wait here until connection happens.
gui_status.set() # GUI status -> TRUE, user connected.
print("GUI status is now: " + str(gui_status.is_set()))
while True:
if protocol_status.is_set():
print("Protocol finished, but data not retrieved.")
if cancel_switch.is_set():
cancel_switch.clear()
GUI = NetworkOperator(Box_Socket.Connection, BUFFER_SIZE=64) # Buffer in bytes.
# Create a new thread (box hardware independent of everything else).
# Box_Socket can still be populated in parallel (i.e. to cancel protocol).
try:
if GUI.command.__module__ == 'pupuicon.translator._core':
USR_Instructions = GUI.command
BoxQueue = queue.Queue()
Box = threading.Thread(target=Controller, args=(USR_Instructions,
Box_Socket.Connection,
cancel_switch,
gui_status,
BoxQueue,
protocol_status))
Box.start()
[LiMO, Protocol, QueueFile] = BoxQueue.get()
# Box.join() # Will wait until `target' finishes.
# _AVOID_ at any cost for proper multi-threading.
# Adjust __WAITING_TIME__ as a function of `replicates'.
# WARNING! ASSUMES 10 FPS MODE! (0.1s exposure will be the slowest mode available).
__SHUTTER_SPEED__ = Protocol._device._camera.shutter_speed * 10**-6 # From µS to SECONDS
if Replicates > 1:
__REPLICATE_SCALING_FACTOR__ = 2.0 + __SHUTTER_SPEED__
elif Replicates == 1:
__REPLICATE_SCALING_FACTOR__ = 4.35 + __SHUTTER_SPEED__
__FILTER_SCALING_FACTOR__ = 2.35 + Replicates # 2.35 = all t.sleep() added, 0.75s ~ read/write/processing time
__WAITING_TIME__ = len(Protocol._filters) * __FILTER_SCALING_FACTOR__ + Replicates * __REPLICATE_SCALING_FACTOR__
time.sleep(__WAITING_TIME__) # Setting for dataGrab
if protocol_status.is_set():
# Means dataGrab
ExportData(Protocol, False, QueueFile,
Box_Socket.Connection, gui_status, Test=True)
protocol_status.clear()
else:
# Means protocol running
continue
except AttributeError:
# __module__ attribute does not exist, therefore
# GUI.command does not contain a protocol.
print("User says: " + GUI.command + ".")
if GUI.command == "Close Connection":
Box_Socket.Socket.close()
break
elif GUI.command == "Test Hardware":
print("Testing hardware...")
HardwareTest(Box_Socket.Connection, gui_status)
elif GUI.command == "Test Temperature":
print("Testing heater...")
TemperatureTest(Box_Socket.Connection, gui_status)
elif GUI.command == "Test Protocol":
print("Running test protocol...")
Protocol = ProtocolTest(Box_Socket.Connection,
cancel_switch, gui_status)
ExportData(Protocol, False, False,
Box_Socket.Connection, gui_status, Test=True)
elif GUI.command == "Abort Protocol":
# Turn hardware OFF before cancelling!! otherwise things
# like HEATER can be left ON.
print("Cancel Protocol.")
if 'LiMO' in locals():
CancelProtocol(with_device=LiMO)
else:
# This steps allows to restart LiMO without anything running.
CancelProtocol()
elif GUI.command == "Check Queue":
try:
if Protocol:
print("Checking Queue...")
QueueStatus(QueueFile, Box_Socket.Connection) # Assumes `Protocol' exists. Greyed-out in GUI.
except NameError:
print("No protocol running.")
pass
elif GUI.command == "Retrieve data": # Assumes `Protocol' exists. Greyed-out in GUI.
ExportData(Protocol, False, QueueFile,
Box_Socket.Connection, gui_status)
protocol_status.clear()
else:
# GUI _always_ expects something coming back.
# By returning a message, the interface won't stall.
Box_Socket.Connection.sendall(str("::IDLE::").encode())
except (ConnectionResetError, BrokenPipeError, OSError) as err: # This will forever (unsuccessfully) try to start server
Box_Socket.Socket.close()
print("GUI status was: " + str(gui_status.is_set()))
gui_status.clear() # GUI status -> FALSE, disconnect user.
print("GUI status is now: " + str(gui_status.is_set()))
print(err)
print("\nRestarting server.")

"""
TODO:
- Implement logs to deal with potential problems reported by users. [DONE]
- Export data when process_data=False (send over network) [TODO: issues with threading...] [DONE]
- Retrieve Queue and initiate protocol automatically if LiMO's power breaks. [DONE]
MISSING FIELDS in LIF file:
- panel_type (guess from 'nmwavelengthsOfFiltersInstalled'?)
- device calibration
- number of wells
- well calibration
- protocol name (guess from 'readsDirectory'?) [NOT NEEDED]
- notes [NOT NEEDED]
- export metadata [DONE/ NOT NEEDED]
"""

Loading…
Cancel
Save