def loaded_sample_changed(sample): if not isinstance(sample, Pin): return if sample is not None: address = sample.getAddress() barcode = sample.getID() else: address = '' barcode = '' logging.getLogger("HWR").info('loaded sample changed now is: ' + address) try: # recreate the dict with the sample info q = queue_to_dict() sampleID = sample.getAddress() sample_data = q.get(sampleID, {}) scutils.set_current_sample(sample_data) msg = {'signal': 'loadReady', 'location': address} socketio.emit('sc', msg, namespace='/hwr') socketio.emit("loaded_sample_changed", {'address': address, 'barcode': barcode}, namespace="/hwr") except Exception, msg: logging.getLogger("HWR").error('error setting loaded sample: %s' + str(msg))
def value_change(self, *args, **kwargs): """ Signal handler to be used for sending values to the client via socketIO. """ data = {"name": self._name, "value": args[0]} socketio.emit("beamline_value_change", data, namespace="/hwr")
def motor_event_callback(*args, **kwargs): # logging.getLogger('HWR').debug('[MOTOR CALLBACK]') # logging.getLogger("HWR").debug(kwargs) # logging.getLogger("HWR").debug(args) signal = kwargs['signal'] sender = str(kwargs['sender'].__class__).split('.')[0] motors_info = Utils.get_centring_motors_info() motors_info.update(Utils.get_light_state_and_intensity()) motors_info['pixelsPerMm'] = mxcube.diffractometer.get_pixels_per_mm() aux = {} for pos in mxcube.diffractometer.savedCentredPos: aux.update({pos['posId']: pos}) # sending all motors position/status, and the current centred positions msg = {'Signal': signal, 'Message': signal, 'Motors': motors_info, 'CentredPositions': aux, 'Data': args[0] if len(args) == 1 else args} # logging.getLogger('HWR').debug('[MOTOR CALLBACK] ' + str(msg)) try: socketio.emit('Motors', msg, namespace='/hwr') except Exception: logging.getLogger("HWR").error('error sending message: %s' + str(msg))
def plot_end(data): try: socketio.emit("plot_end", data, namespace="/hwr") except Exception: logging.getLogger("HWR").error( "error sending plot_end message for plot %s", data["id"] )
def remain_observer(observer_sid, message): observer = loginutils.get_user_by_sid(observer_sid) observer["message"] = message socketio.emit( "setObserver", observer, room=observer["socketio_sid"], namespace="/hwr" )
def beam_changed(*args, **kwargs): ret = {} beam_info = blcontrol.beamline.getObjectByRole("beam_info") if beam_info is None: logging.getLogger("HWR").error("beamInfo is not defined") return Response(status=409) try: beam_info_dict = beam_info.get_beam_info() except Exception: beam_info_dict = dict() ret.update( { "position": beam_info.get_beam_position(), "shape": beam_info_dict.get("shape"), "size_x": beam_info_dict.get("size_x"), "size_y": beam_info_dict.get("size_y"), } ) try: socketio.emit("beam_changed", {"data": ret}, namespace="/hwr") except Exception: logging.getLogger("HWR").exception("error sending message: %s" + str(msg))
def loaded_sample_changed(sample): if hasattr(sample, "getAddress"): address = sample.getAddress() barcode = sample.getID() else: address = "" barcode = "" logging.getLogger("HWR").info("Loaded sample changed now is: " + address) try: sampleID = address if blcontrol.sample_changer.hasLoadedSample(): scutils.set_current_sample(sampleID) else: scutils.set_current_sample(None) address = "" socketio.emit( "loaded_sample_changed", {"address": address, "barcode": barcode}, namespace="/hwr", ) except Exception as msg: logging.getLogger("HWR").error("error setting loaded sample: %s" + str(msg))
def safety_shutter_state_changed(values): ho = BeamlineSetupMediator(mxcube.beamline).getObjectByRole("safety_shutter") data = ho.dict_repr() try: socketio.emit("beamline_value_change", data, namespace="/hwr") except Exception: logging.getLogger("HWR").error('error sending message: %s' + str(data))
def is_collision_safe(*args): # responds to the 'isCollisionSafe' signal from the Sample Changer new_state = args[0] # we are only interested when it becames true if new_state: msg = {"signal": "isCollisionSafe", "message": "Sample moved to safe area"} socketio.emit("sc", msg, namespace="/hwr")
def workflow_dialog(wf): dialog = { "properties": { "name": { "title":"Task name", "type":"string", "minLength": 2 }, "description": { "title":"Description", "type":"string", "widget":"textarea" }, "dueTo": { "title":"Due to", "type":"string", "widget":"compatible-datetime", "format":"date-time" } }, "required":["name"], "dialogName": "Trouble shooting !" } socketio.emit("workflowParametersDialog", dialog, namespace="/hwr") return Response(status=200)
def beam_changed(*args, **kwargs): ret = {} signal = kwargs['signal'] beam_info = mxcube.beamline.getObjectByRole("beam_info") if beam_info is None: logging.getLogger('HWR').error("beamInfo is not defined") return Response(status=409) try: beam_info_dict = beam_info.get_beam_info() except Exception: beam_info_dict = dict() ret.update({'position': beam_info.get_beam_position(), 'shape': beam_info_dict.get("shape"), 'size_x': beam_info_dict.get("size_x"), 'size_y': beam_info_dict.get("size_y") }) msg = {'Signal': signal, 'Message': signal, 'Data': ret} # logging.getLogger('HWR').debug('[MOTOR CALLBACK] ' + str(msg)) try: socketio.emit('beam_changed', msg, namespace='/hwr') except Exception: logging.getLogger("HWR").error('error sending message: %s' + str(msg))
def motor_event_callback(*args, **kwargs): #logging.getLogger('HWR').debug('[MOTOR CALLBACK]') #logging.getLogger("HWR").debug(kwargs) #logging.getLogger("HWR").debug(args) signal = kwargs['signal'] sender = str(kwargs['sender'].__class__).split('.')[0] motors_info = dict() for name in ['Phi', 'Focus', 'PhiZ', 'PhiY', 'Zoom', 'BackLightSwitch','BackLight','FrontLightSwitch', 'FrontLight','Sampx', 'Sampy']: motors_info.update(Utils.get_movable_state_and_position(name)) motors_info['pixelsPerMm'] = mxcube.diffractometer.get_pixels_per_mm() aux = {} for p in mxcube.diffractometer.savedCentredPos: aux.update({p['posId']:p}) ## sending all motors position/status, and the current centred positions msg = {'Signal': signal,'Message': signal, 'Motors':motors_info, 'CentredPositions': aux, 'Data': args[0] if len(args) ==1 else args} #logging.getLogger('HWR').debug('[MOTOR CALLBACK] ' + str(msg)) try: socketio.emit('Motors', msg, namespace='/hwr') except Exception: logging.getLogger("HWR").error('error sending message: %s'+str(msg)) try: msg = { "message": sender +':'+signal, "severity": 'INFO', "timestamp":time.asctime(), "logger":'HWR', "stack_trace":'' } socketio.emit('log_record', msg, namespace='/logging') except Exception: logging.getLogger("HWR").error('error sending message: %s'+str(msg))
def beamline_action_done(name, result): msg = {"name": name, "state": READY, "data": result} try: socketio.emit("beamline_action", msg, namespace="/hwr") except Exception: logging.getLogger("HWR").exception("error sending beamline action message: %s", msg) else: logging.getLogger('user_level_log').info('%s done.', name)
def sc_unload(location): msg = { "signal": "operatingSampleChanger", "location": location, "message": "Please wait, unloading sample", } socketio.emit("sc", msg, namespace="/hwr")
def sc_load_ready(location): msg = { "signal": "loadReady", "location": location, "message": "Sample changer, loaded sample", } socketio.emit("sc", msg, namespace="/hwr")
def beamline_action_failed(name): msg = {"name": name, "state": FAILED} try: socketio.emit("beamline_action", msg, namespace="/hwr") except Exception: logging.getLogger("HWR").exception("error sending beamline action message: %s", msg) else: logging.getLogger('user_level_log').error('Action %s failed !', name)
def beamline_action_start(name): msg = {"name": name, "state": RUNNING} try: socketio.emit("beamline_action", msg, namespace="/hwr") except Exception: logging.getLogger("HWR").exception( "error sending beamline action message: %s", msg )
def collectOscillationFinished(*args): lastQueueNode = mxcube.queue.lastQueueNode msg = {'Signal': 'collectOscillationFinished','Message': task_signals['collectOscillationFinished'], 'QueueId':lastQueueNode['id'], 'Sample' :lastQueueNode['sample'] ,'State':get_signal_result('collectOscillationFinished')} logging.getLogger('HWR').debug('[TASK CALLBACK] ' + str(msg)) try: socketio.emit('Task', msg, namespace='/hwr') except Exception: logging.getLogger("HWR").error('error sending message: '+ str(msg))
def centring_started(method, *args): usr_msg = 'Using 3-click centring, please click the position on ' usr_msg += 'the sample you would like to center (three times)' msg = {'signal': 'SampleCentringRequest', 'message': usr_msg} socketio.emit('sample_centring', msg, namespace='/hwr')
def remove_user(sid): user = mxcube.USERS.pop(sid) if user["operator"]: state_storage.flush() flush() else: socketio.emit("observerLogout", user, namespace="/hwr") socketio.emit("observersChanged", get_observers(), namespace="/hwr")
def centring_started(method, *args): msg = {"method": method} if method in ["Computer automatic"]: msg = {"method": CENTRING_METHOD.LOOP} elif method in ["Manual 3-click"]: msg = {"method": CENTRING_METHOD.MANUAL} socketio.emit("sample_centring", msg, namespace="/hwr")
def _do_take_snapshot(filename): SNAPSHOT_RECEIVED.clear() socketio.emit('take_xtal_snapshot', namespace='/hwr', room=remote_access.MASTER_ROOM, callback=_snapshot_received) SNAPSHOT_RECEIVED.wait(timeout=30) with file(filename, 'wb') as snapshot_file: snapshot_file.write(SNAPSHOT)
def motor_state_callback(motor, state, sender=None, **kw): centred_positions = dict() for pos in mxcube.diffractometer.savedCentredPos: centred_positions.update({pos['posId']: pos}) if state == 2: # READY motor_position_callback(motor, sender.getPosition()) socketio.emit('motor_state', { 'name': motor, 'state': state, 'centredPositions': centred_positions }, namespace='/hwr')
def allow_remote(): """ """ allow = request.get_json().get("allow") if mxcube.ALLOW_REMOTE and allow == False: socketio.emit("forceSignoutObservers", {}, namespace="/hwr") mxcube.ALLOW_REMOTE = allow return Response(status=200)
def queue_unpause(): """ Unpause execution of the queue :returns: Response object, status code set to: 200: On success 409: Queue could not be unpause """ msg = qutils.queue_unpause() socketio.emit("queue", msg, namespace="/hwr") return Response(status=200)
def send_shapes(update_positions=False, movable={}): shape_dict = {} for shape in blcontrol.shapes.get_shapes(): if update_positions: shape.update_position(blcontrol.diffractometer.motor_positions_to_screen) s = to_camel(shape.as_dict()) shape_dict.update({shape.id: s}) socketio.emit("update_shapes", {"shapes": shape_dict}, namespace="/hwr")
def send_shapes(update_positions = False): shape_dict = {} for shape in mxcube.shapes.get_shapes(): if update_positions: shape.update_position(mxcube.diffractometer.motor_positions_to_screen) s = to_camel(shape.as_dict()) shape_dict.update({shape.id: s}) socketio.emit('update_shapes', {'shapes': shape_dict}, namespace='/hwr')
def set_observer(data): name = data.get("name", "") observers = loginutils.get_observers() observer = loginutils.get_user_by_sid(session.sid) if observer and name: observer["name"] = name socketio.emit("observerLogin", observer, include_self=False, namespace="/hwr") socketio.emit("observersChanged", observers, namespace="/hwr") return session.sid
def queueUnpause(): """ Unpause execution of the queue :statuscode: 200: no error :statuscode: 409: queue could not be unpause """ logging.getLogger('HWR').info('[QUEUE] Queue going to unpause') mxcube.queue.queue_hwobj.pause(False) msg = {'Signal': 'QueueStarted','Message': 'Queue execution started', 'State':1} socketio.emit('Queue', msg, namespace='/hwr') logging.getLogger('HWR').info('[QUEUE] Queue unpaused') return Response(status=200)
def connect(): global MASTER_ROOM, DISCONNECT_HANDLED if is_master(session.sid): MASTER_ROOM = request.sid emit_pending_events() if not mxcube.queue.queue_hwobj.is_executing() and not DISCONNECT_HANDLED: DISCONNECT_HANDLED = True socketio.emit("resumeQueueDialog", namespace='/hwr') msg = 'Client reconnected, Queue was previously stopped, asking ' msg += 'client for action' logging.getLogger('HWR').info(msg)
def queue_unpause(): """ Unpause execution of the queue :returns: Response object, status code set to: 200: On success 409: Queue could not be unpause """ mxcube.queue.queue_hwobj.pause(False) msg = {'Signal': qutils.queue_exec_state(), 'Message': 'Queue execution started', 'State': 1} socketio.emit('queue', msg, namespace='/hwr') return Response(status=200)
def loaded_sample_changed(sample): # If sample is a "No sample loaded value" None or '' if sample in [None, '']: msg = {'signal': 'loadReady', 'location': ''} socketio.emit('sc', msg, namespace='/hwr') socketio.emit("loaded_sample_changed", {'address': '', 'barcode': ''}, namespace="/hwr") # If sample is not Pin, Sample pin just return if not (isinstance(sample, Pin) or isinstance(sample, Sample)): return if sample is not None: address = sample.getAddress() barcode = sample.getID() else: address = '' barcode = '' logging.getLogger("HWR").info('loaded sample changed now is: ' + address) try: # recreate the dict with the sample info q = queue_to_dict() sampleID = sample.getAddress() sample_data = q.get(sampleID, {}) scutils.set_current_sample(sample_data) msg = {'signal': 'loadReady', 'location': address} socketio.emit('sc', msg, namespace='/hwr') socketio.emit("loaded_sample_changed", {'address': address, 'barcode': barcode}, namespace="/hwr") except Exception, msg: logging.getLogger("HWR").error('error setting loaded sample: %s' + str(msg))
def request_control_response(): """ """ data = request.get_json() observer = observer_requesting_control() observers = remote_access.OBSERVERS.values() # Request was denied if not data['giveControl']: data["sid"] = session.sid # Reset request of observer, since it was denied observer["requestsControl"] = False socketio.emit("observersChanged", observers, namespace='/hwr') socketio.emit("setMaster", data, namespace='/hwr') else: # Find the user asking for control and remove her from observers # and make her master observer = remote_access.OBSERVERS.pop(observer["host"]) remote_access.set_master(observer["sid"]) data["sid"] = observer["sid"] socketio.emit("observersChanged", observers, namespace='/hwr') socketio.emit("setMaster", data, namespace='/hwr') return make_response("", 200)
def plot_data(data, last_index=[0], **kwargs): data_data = data["data"] if last_index[0] > len(data_data): last_index = [0] data["data"] = data_data[last_index[0]:] try: socketio.emit("plot_data", data, namespace="/hwr") except Exception: logging.getLogger("HWR").exception( "error sending plot_data message for plot %s", data["id"]) else: last_index[0] += len(data_data)
def sc_state_changed(*args): new_state = args[0] old_state = None if len(args) == 2: old_state = args[1] location, sc_location, msg = '', '', None loaded_sample = mxcube.sample_changer.getLoadedSample() # Handle inconsistent API getLoadedSample sometimes returns a sampleID # and other times an object. if isinstance(loaded_sample, str): if not 'None' in loaded_sample: parts = map(int, loaded_sample.split(':')) sc_location = ":".join(["%s" % parts[0], '%0.2d' % parts[1]]) elif loaded_sample: sc_location = loaded_sample.getAddress() known_location = scutils.get_current_sample().get('sampleID', '') location = known_location if known_location else sc_location if new_state == SampleChangerState.Moving: msg = {'signal': 'operatingSampleChanger', 'location': '', 'message': 'Please wait, operating sample changer'} elif new_state in [SampleChangerState.Loading, SampleChangerState.Unloading]: if new_state == SampleChangerState.Loading: location = scutils.get_sample_to_be_mounted() message = 'Please wait, Loading sample %s' % location signal = 'loadingSample' elif new_state == SampleChangerState.Unloading: signal = 'unLoadingSample' message = 'Please wait, Unloading sample' scutils.set_current_sample(None) msg = {'signal': signal, 'location': location, 'message': message} if msg: logging.getLogger("HWR").info('emitting sc state changed: ' + str(msg)) socketio.emit('sc', msg, namespace='/hwr') # emit also brut sample changer state for those interested state_str = SampleChangerState.STATE_DESC.get(new_state, "Unknown").upper() socketio.emit('sc_state', state_str, namespace='/hwr')
def _do_take_snapshot(filename): from . import loginutils SNAPSHOT_RECEIVED.clear() rid = loginutils.get_operator()["socketio_sid"] socketio.emit("take_xtal_snapshot", namespace="/hwr", room=rid, callback=_snapshot_received) SNAPSHOT_RECEIVED.wait(timeout=30) with open(filename, "wb") as snapshot_file: snapshot_file.write(SNAPSHOT)
def motor_state_callback(movable, sender=None, **kw): if movable["state"] == 2: # Re emit the position when the motor have finished to move # so that we are always sure that we have sent the final position motor_position_callback(movable) # Re calculate positions for shapes after motor finished to move send_shapes(update_positions = True, movable=movable) # Update the pixels per mm if it was the zoom motor that moved if movable["name"] == "zoom": ppm = mxcube.diffractometer.get_pixels_per_mm() socketio.emit('update_pixels_per_mm', {"pixelsPerMm": ppm}, namespace='/hwr') socketio.emit('motor_state', movable, namespace='/hwr')
def queue_pause(): """ Pause the execution of the queue :returns: Response object, status code set to: 200: On success 409: Queue could not be paused """ mxcube.queue.queue_hwobj.pause(True) msg = {'Signal': qutils.queue_exec_state(), 'Message': 'Queue execution paused', 'State': 1} socketio.emit('queue', msg, namespace='/hwr') logging.getLogger('HWR').info('[QUEUE] Paused') return Response(status=200)
def append_message(message, sid): user = get_observer_name() if not user: user = "******" + session["loginInfo"]["loginID"] data = { "message": message, "sid": sid, "user": user, "host": remote_addr(), "date": datetime.datetime.now().strftime("%H:%M"), } MESSAGES.append(data) socketio.emit("ra_chat_message", data, namespace="/hwr")
def set_master_id(data): global MASTER_ROOM, OBSERVERS if data['master']: MASTER_ROOM = request.sid emit_pending_events() else: OBSERVERS[remote_addr()] = {"host": remote_addr(), "name": data["name"], "requestsControl": False, "message": '', "sid": session.sid} socketio.emit("observersChanged", OBSERVERS.values(), namespace='/hwr') return session.sid
def motor_state_callback(movable, sender=None, **kw): if movable["state"] == HardwareObjectState.READY.value: # Re emit the position when the motor have finished to move # so that we are always sure that we have sent the final position motor_position_callback(movable) # Re calculate positions for shapes after motor finished to move send_shapes(update_positions=True, movable=movable) # Update the pixels per mm if it was the zoom motor that moved if movable["name"] == "zoom": ppm = blcontrol.beamline.diffractometer.get_pixels_per_mm() socketio.emit("update_pixels_per_mm", {"pixelsPerMm": ppm}, namespace="/hwr") socketio.emit("motor_state", movable, namespace="/hwr")
def connect(): user = loginutils.get_user_by_sid(session.sid) # Make sure user is logged, session may have been closed i.e by timeout if user: user["socketio_sid"] = request.sid # (Note: User is logged in if operator) if loginutils.is_operator(session.sid): if (not blcontrol.beamline.queue_manager.is_executing() and not loginutils.DISCONNECT_HANDLED): loginutils.DISCONNECT_HANDLED = True socketio.emit("resumeQueueDialog", namespace="/hwr") msg = "Client reconnected, Queue was previously stopped, asking " msg += "client for action" logging.getLogger("HWR").info(msg)
def _do_take_snapshot(filename, bw=False): from . import loginutils from mxcube3 import socketio, server SNAPSHOT_RECEIVED.clear() rid = loginutils.get_operator()["socketio_sid"] with server.test_request_context(): socketio.emit( "take_xtal_snapshot", namespace="/hwr", room=rid, callback=_snapshot_received ) SNAPSHOT_RECEIVED.wait(timeout=30) with open(filename, "wb") as snapshot_file: snapshot_file.write(SNAPSHOT)
def xrf_task_progress(taskId, progress): node = last_queue_node() msg = { "Signal": "XRFTaskUpdate", "Message": "XRFTaskUpdate", "taskIndex": node["idx"], "queueID": node["queue_id"], "sample": node["sample"], "state": RUNNING if progress < 1 else COLLECTED, "progress": progress, } try: socketio.emit("task", msg, namespace="/hwr") except Exception: logging.getLogger("HWR").error("error sending message: " + str(msg))
def connect(): user = loginutils.get_user_by_sid(session.sid) # Make sure user is logged, session may have been closed i.e by timeout if user: user["socketio_sid"] = request.sid # (Note: User is logged in if operator) if loginutils.is_operator(session.sid): loginutils.emit_pending_events() if not mxcube.queue.queue_hwobj.is_executing() and \ not loginutils.DISCONNECT_HANDLED: loginutils.DISCONNECT_HANDLED = True socketio.emit("resumeQueueDialog", namespace='/hwr') msg = 'Client reconnected, Queue was previously stopped, asking ' msg += 'client for action' logging.getLogger('HWR').info(msg)
def queue_interleaved_finished(): node = last_queue_node() msg = { "Signal": "queue_interleaved_finished", "Message": "Interleaved collection ended", "taskIndex": node["idx"], "queueID": node["queue_id"], "sample": node["sample"], "state": COLLECTED, "progress": 1, } logging.getLogger("HWR").debug("[TASK CALLBACK] " + str(msg)) try: socketio.emit("task", msg, namespace="/hwr") except Exception: logging.getLogger("HWR").error("error sending message: " + str(msg))
def queue_interleaved_sw_done(data): node = last_queue_node() progress = qutils.get_task_progress(node["node"], data) msg = { "Signal": "collectImageTaken", "Message": task_signals["collectImageTaken"], "taskIndex": node["idx"], "queueID": node["queue_id"], "sample": node["sample"], "state": RUNNING if progress < 1 else COLLECTED, "progress": progress, } logging.getLogger("HWR").debug("[TASK CALLBACK] " + str(msg)) try: socketio.emit("task", msg, namespace="/hwr") except Exception: logging.getLogger("HWR").error("error sending message: " + str(msg))
def collect_oscillation_started(*args): node = last_queue_node() if not qutils.is_interleaved(node["node"]): msg = { "Signal": "collectOscillationStarted", "Message": task_signals["collectOscillationStarted"], "taskIndex": node["idx"], "queueID": node["queue_id"], "sample": node["sample"], "state": RUNNING, "progress": 0, } logging.getLogger("HWR").debug("[TASK CALLBACK] " + str(msg)) try: socketio.emit("task", msg, namespace="/hwr") except Exception: logging.getLogger("HWR").error("error sending message: " + str(msg))
def toggle_operator(new_op_sid, message): current_op = loginutils.get_operator() new_op = loginutils.get_user_by_sid(new_op_sid) loginutils.set_operator(new_op["sid"]) new_op["message"] = message observers = loginutils.get_observers() # Append the new data path so that it can be updated on the client new_op["rootPath"] = blcontrol.beamline.session.get_base_image_directory() # Current op might have logged out, while this is happening if current_op: current_op[ "rootPath"] = blcontrol.beamline.session.get_base_image_directory( ) current_op["message"] = message socketio.emit("setObserver", current_op, room=current_op["socketio_sid"], namespace="/hwr") socketio.emit("observersChanged", observers, namespace="/hwr") socketio.emit("setMaster", new_op, room=new_op["socketio_sid"], namespace="/hwr")
def request_control_response(): """ """ data = request.get_json() new_op = observer_requesting_control() current_op = loginutils.get_operator() # Request was denied if not data['giveControl']: data["sid"] = session.sid # Reset request of observer, since it was denied observers = loginutils.get_observers() else: # Find the user asking for control and remove her from observers # and make her master loginutils.set_operator(new_op["sid"]) observers = loginutils.get_observers() new_op["message"] = data["message"] new_op["requestsControl"] = False socketio.emit("setMaster", new_op, room=new_op["socketio_sid"], namespace='/hwr') socketio.emit("setObserver", current_op, room=current_op["socketio_sid"], namespace='/hwr') socketio.emit("observersChanged", observers, namespace='/hwr') return make_response("", 200)
def add_diffraction_plan(parent, child): """ Listen to the addition of elements to the queue ('child_added') and if it is a diff plan create the appropiate queue entry and emit a socketio signal. This is to overcome the fact that the Characterisation entry only creates the model of the diff plan. """ if isinstance(child, qmo.DataCollection): parent_model, parent_entry = get_entry(parent._node_id) # the parent if 'Diffraction plan' in parent_model.get_name(): # name example string 'Diffraction plan - 3' # Then we do know that we need to add the entry here, Create a # new entry for the new child, in this case a data collection dc_entry = qe.DataCollectionQueueEntry(Mock(), child) dcg_entry = qe.TaskGroupQueueEntry(Mock(), parent) parent.set_enabled(True) dcg_entry.set_enabled(True) child.set_enabled(True) dc_entry.set_enabled(True) sample = parent.get_parent() # mxcube.queue.get_model_root() sample_model, sample_entry = get_entry(sample._node_id) # TODO: check if the parent entry exits in case multiple diff plans sample_entry.enqueue(dcg_entry) # Add the entry to the newly created task group, brother to the # characterisation dcg_entry.enqueue(dc_entry) msg = _handle_dc(sample._node_id, child) msg['parameters']['typePrefix'] = 'P' # TODO: add saved centring pos id, centred_position is removed in # _handle_dc socketio.emit('add_task', msg, namespace='/hwr')
def update_task_result(entry): node_index = qutils.node_index(entry.get_data_model()) node_id = entry.get_data_model()._node_id lims_id = mxcube.NODE_ID_TO_LIMS_ID.get(node_id, 'null') try: limsres = mxcube.rest_lims.get_dc(lims_id) except: limsres = {} try: limsres["limsTaskLink"] = limsutils.get_dc_link(lims_id) except Exception: limsres["limsTaskLink"] = "#" msg = "Could not get lims link for collection with id: %s" % lims_id logging.getLogger("HWR").error(msg) msg = { 'sample': node_index['sample'], 'taskIndex': node_index['idx'], 'limsResultData': limsres } socketio.emit('update_task_lims_data', msg, namespace='/hwr')
def request_control(): """ """ data = request.get_json() # Is someone already asking for control for observer in remote_access.OBSERVERS.values(): if observer["requestsControl"]: msg = "Another user is already asking for control" return make_response(msg, 409) remote_addr = remote_access.remote_addr() remote_access.OBSERVERS[remote_addr]["name"] = data["name"] remote_access.OBSERVERS[remote_addr]["requestsControl"] = True remote_access.OBSERVERS[remote_addr]["message"] = data["message"] data = remote_access.OBSERVERS.values() socketio.emit("observersChanged", data, namespace='/hwr') return make_response("", 200)
def beam_changed(*args, **kwargs): beam_info = blcontrol.beamline.beam if beam_info is None: logging.getLogger("HWR").error("beamInfo is not defined") return Response(status=409) beam_info_dict = {"position": [], "shape": "", "size_x": 0, "size_y": 0} _beam = beam_info.get_value() beam_info_dict.update({ "position": beam_info.get_beam_position(), "size_x": _beam[0], "size_y": _beam[1], "shape": _beam[2].value, }) try: socketio.emit("beam_changed", {"data": beam_info_dict}, namespace="/hwr") except Exception: logging.getLogger("HWR").exception("error sending message: %s" + str(msg))
def collect_ended(owner, success, message): node = last_queue_node() if not qutils.is_interleaved(node["node"]): state = COLLECTED if success else WARNING msg = { "Signal": "collectOscillationFinished", "Message": message, "taskIndex": node["idx"], "queueID": node["queue_id"], "sample": node["sample"], "state": state, "progress": 1, } logging.getLogger("HWR").debug("[TASK CALLBACK] " + str(msg)) try: socketio.emit("task", msg, namespace="/hwr") except Exception: logging.getLogger("HWR").error("error sending message: " + str(msg))
def collect_oscillation_finished(owner, status, state, lims_id, osc_id, params): node = last_queue_node() mxcube.NODE_ID_TO_LIMS_ID[node["queue_id"]] = lims_id if not qutils.is_interleaved(node["node"]): qutils.enable_entry(node["queue_id"], False) msg = { "Signal": "collectOscillationFinished", "Message": task_signals["collectOscillationFinished"], "taskIndex": node["idx"], "queueID": node["queue_id"], "sample": node["sample"], "state": COLLECTED, "progress": 1, } logging.getLogger("HWR").debug("[TASK CALLBACK] " + str(msg)) try: socketio.emit("task", msg, namespace="/hwr") except Exception: logging.getLogger("HWR").error("error sending message: " + str(msg))
def update_task_result(entry): node_index = qutils.node_index(entry.get_data_model()) node_id = entry.get_data_model()._node_id lims_id = mxcube.NODE_ID_TO_LIMS_ID.get(node_id, "null") try: limsres = blcontrol.beamline.lims_rest.get_dc(lims_id) except BaseException: limsres = {} try: limsres["limsTaskLink"] = limsutils.get_dc_link(lims_id) except Exception: limsres["limsTaskLink"] = "#" msg = "Could not get lims link for collection with id: %s" % lims_id logging.getLogger("HWR").error(msg) msg = { "sample": node_index["sample"], "taskIndex": node_index["idx"], "limsResultData": limsres, } socketio.emit("update_task_lims_data", msg, namespace="/hwr")
def request_control(): """ """ @copy_current_request_context def handle_timeout_gives_control(sid, timeout=30): gevent.sleep(timeout) if mxcube.TIMEOUT_GIVES_CONTROL: user = loginutils.get_user_by_sid(sid) # Pass control to user if still waiting if user.get("requestsControl"): toggle_operator(sid, "Timeout expired, you have control") data = request.get_json() remote_addr = loginutils.remote_addr() # Is someone already asking for control for observer in loginutils.get_observers(): if observer["requestsControl"] and observer["host"] != remote_addr: msg = "Another user is already asking for control" return make_response(msg, 409) user = loginutils.get_user_by_sid(session.sid) user["name"] = data["name"] user["requestsControl"] = data["control"] user["message"] = data["message"] observers = loginutils.get_observers() gevent.spawn(handle_timeout_gives_control, session.sid, timeout=10) socketio.emit("observersChanged", observers, namespace="/hwr") return make_response("", 200)