def _controlCmdWrapper(cmd): """ cmd can either be a single DC.ControlCommand, or a list of them with return resp or resps, according to the multiplicity of cmd may raise hwifError, with type and message attributes """ multiple = isinstance(cmd, list) try: if multiple: with QtCore.QMutexLocker(DAEMON_MUTEX): resps = DC.do_control_cmds(cmd, control_socket=DAEMON_SOCK) if resps: for resp in resps: if resp: if resp.type == DC.ControlResponse.ERR: raise hwifError(1, resp.err.code) else: raise hwifError(2) return resps else: raise hwifError(2) else: with QtCore.QMutexLocker(DAEMON_MUTEX): resp = DC.do_control_cmd(cmd, control_socket=DAEMON_SOCK) if resp: if resp.type == DC.ControlResponse.ERR: raise hwifError(1, resp.err.code) else: raise hwifError(2) return resp except socket.error: raise hwifError(0)
def updateMetaData(self, zmqtopics=None, autozmqtopics=None, datasources=None, disconnect=True, **kargs): """ update source input parameters :param zmqtopics: zmq source topics :type zmqtopics: :obj:`list` <:obj:`str`> > :param autozmqtopics: automatic zmq topics enabled :type autozmqtopics: :obj:`bool` :param datasources: automatic zmq source topics :type datasources: :obj:`list` <:obj:`str`> > :param disconnect: disconnect on update :type disconnect: :obj:`bool` :param kargs: source widget input parameter dictionary :type kargs: :obj:`dict` < :obj:`str`, :obj:`any`> """ if disconnect: with QtCore.QMutexLocker(self.__mutex): self._ui.pickleTopicComboBox.currentIndexChanged.disconnect( self._updateZMQComboBox) text = None updatecombo = False if isinstance(zmqtopics, list): with QtCore.QMutexLocker(self.__mutex): text = str(self._ui.pickleTopicComboBox.currentText()) if not text or text not in zmqtopics: text = None self.__zmqtopics = zmqtopics updatecombo = True if autozmqtopics is not None: self.__autozmqtopics = autozmqtopics if self.__autozmqtopics: updatecombo = True with QtCore.QMutexLocker(self.__mutex): text = str(self._ui.pickleTopicComboBox.currentText()) if isinstance(datasources, list): if not text or text not in datasources: text = None self.__zmqtopics = datasources if updatecombo is True: with QtCore.QMutexLocker(self.__mutex): for i in reversed( range(0, self._ui.pickleTopicComboBox.count())): self._ui.pickleTopicComboBox.removeItem(i) self._ui.pickleTopicComboBox.addItems(self.__zmqtopics) self._ui.pickleTopicComboBox.addItem("**ALL**") if text: tid = self._ui.pickleTopicComboBox.findText(text) if tid > -1: self._ui.pickleTopicComboBox.setCurrentIndex(tid) if disconnect: self.updateButton(disconnect=False) with QtCore.QMutexLocker(self.__mutex): self._ui.pickleTopicComboBox.currentIndexChanged.connect( self._updateZMQComboBox)
def disconnect(self): """ disconnects the source """ try: with QtCore.QMutexLocker(self.__mutex): if self.__socket: if self.__bindaddress: self.__socket.unbind(self.__bindaddress) self.__socket.close(linger=0) self.__socket = None except Exception as e: print(str(e)) pass with QtCore.QMutexLocker(self.__mutex): self.__bindaddress = None
def connect(self): """ connects the source """ try: shost = str(self._configuration).split("/") host, port = str(shost[0]).split(":") self.__topic = shost[1] if len(shost) > 1 else "" hwm = int(shost[2]) if (len(shost) > 2 and shost[2]) else 2 if not self._initiated: if self.__socket: self.disconnect() with QtCore.QMutexLocker(self.__mutex): self.__socket = self.__context.socket(zmq.SUB) if hwm is not None: self.__socket.set_hwm(hwm) self.__bindaddress = ('tcp://' + socket.gethostbyname(host) + ':' + str(port)) self.__socket.setsockopt(zmq.SUBSCRIBE, self.__topic) self.__socket.setsockopt(zmq.SUBSCRIBE, "datasources") # self.__socket.setsockopt(zmq.SUBSCRIBE, "") self.__socket.connect(self.__bindaddress) time.sleep(0.2) return True except Exception as e: self.disconnect() print(str(e)) self._updaterror() return False
def setDataSource(self, datasource): """ sets datasource :param datasource: datasource object :type datasource: :class:`lavuelib.imageSource.BaseSource` """ with QtCore.QMutexLocker(self.__mutex): self.__datasource = datasource
def dataTransfer(self, spectrum): lock = QtCore.QMutexLocker(self.mutex) transfer = {} if "timeHistogram" in spectrum or "all" in spectrum: transfer["timeHistogram"] = (np.copy(self.dataSet.timeRange), np.copy(self.dataSet.timeHistogram)) if "energyHistogram" in spectrum or "all" in spectrum: transfer["energyHistogram"] = (np.copy(self.dataSet.energyRange), np.copy( self.dataSet.energyHistogram)) if "timeImage" in spectrum or "all" in spectrum: transfer["timeImage"] = np.copy(self.dataSet.timeImage) if "energyImage" in spectrum or "all" in spectrum: transfer["energyImage"] = np.copy(self.dataSet.energyImage) if "countrate" in spectrum or "all" in spectrum: transfer["countrate"] = ( np.copy(self.dataSet.countrate.getData()["eventTime"]), np.copy(self.dataSet.countrate.getData()["events"])) if "keithley" in spectrum or "all" in spectrum: if self.dataSet.keithley != None: transfer["keithley"] = ( np.copy(self.dataSet.keithley.getData()["eventTime"]), np.copy(self.dataSet.keithley.getData()["events"])) if "liveView" in spectrum or "all" in spectrum: transfer["liveView"] = (np.copy(self.dataSet.mcp), self.countrate, self.selection) self.sigUpdateGui.emit(transfer)
def _add_data(self, columns, row, obj): """Add data from object o at a row in the cache :param columns: the columns of which to strip data :param row: the row in the cache into which to add data :param obj: the object from which to strip the data """ if not self.admin.is_deleted(obj): row_data = strip_data_from_object(obj, columns) dynamic_field_attributes = list( self.admin.get_dynamic_field_attributes( obj, (c[0] for c in columns))) static_field_attributes = self.admin.get_static_field_attributes( (c[0] for c in columns)) unicode_row_data = stripped_data_to_unicode( row_data, obj, static_field_attributes, dynamic_field_attributes) else: row_data = [None] * len(columns) dynamic_field_attributes = [{'editable': False}] * len(columns) static_field_attributes = self.admin.get_static_field_attributes( (c[0] for c in columns)) unicode_row_data = [u''] * len(columns) locker = QtCore.QMutexLocker(self._mutex) self.edit_cache.add_data(row, obj, row_data) self.display_cache.add_data(row, obj, unicode_row_data) self.attributes_cache.add_data(row, obj, dynamic_field_attributes) locker.unlock() # # it might be that the CollectionProxy is deleted on the QT side of # the application # if not is_deleted(self): self.row_changed_signal.emit(row)
def setData(self, index, value, role=Qt.EditRole): """Value should be a function taking no arguments that returns the data to be set This function will then be called in the model_thread """ assert object_thread(self) # # prevent data of being set in rows not actually in this model # if (not index.isValid()) or (index.model() != self): return False if role == Qt.EditRole: # if the field is not editable, don't waste any time and get out of here # editable should be explicitely True, since the _get_field_attribute_value # might return intermediary values such as ValueLoading ?? if self._get_field_attribute_value(index, 'editable') != True: return locker = QtCore.QMutexLocker(self._mutex) flushed = (index.row() not in self.unflushed_rows) self.unflushed_rows.add(index.row()) self._update_requests.append( (flushed, index.row(), index.column(), value)) locker.unlock() post(self._handle_update_requests) return True
def rotationChanged(self): lock = QtCore.QMutexLocker(self.mutex) if not self.dataSet.rawData == None: electrons = self.dataSet.getElectronsFromRawData() self.dataSet.clearSpectra(ignoreCountrate=True) self.dataSet.setElectrons(electrons=electrons) self.dataTransfer(["All"])
def takeFilename(self): locker = QtCore.QMutexLocker(self.mutex) if self.filenames.isEmpty(): self.condition.wait(self.mutex) if not self.filenames.isEmpty(): return self.filenames.takeFirst() else: return None
def requestNewFortune(self, hostname, port): locker = QtCore.QMutexLocker(self.mutex) self.hostName = hostname self.port = port if not self.isRunning(): self.start() else: self.cond.wakeOne()
def connect(self): """ connects the source """ try: if not self._initiated: with QtCore.QMutexLocker(self.__mutex): self.__query.initiate(self.__target) self._initiated = True with QtCore.QMutexLocker(self.__mutex): self.__query.start() return True except: if self.__query is not None: with QtCore.QMutexLocker(self.__mutex): self.__query.stop() self._updaterror() return False
def readData(self): """ write data into exchange object :returns: tuple of exchange object (name, data, metadata) :rtype: :obj:`list` <:obj:`str`, :class:`numpy.ndarray`, :obj:`str` > """ with QtCore.QMutexLocker(self.__mutex): a, b, c = self.__elist[0], self.__elist[1], self.__elist[2] return a, b, c
def disconnect(self): """ disconnects the source """ try: if self.__query is not None: with QtCore.QMutexLocker(self.__mutex): self.__query.stop() except: self._updaterror()
def consume(self): # when this goes out of scope the lock is opened locker = QtCore.QMutexLocker(QdImageLoader._mutex) if self._index == len(self._paths): return None path = self._paths[self._index] self._index += 1 return path
def clearSpectra(self, rawData=True): lock = QtCore.QMutexLocker(self.mutex) QtCore.QCoreApplication.processEvents() self.dataSet.clearSpectra() self.electrons = np.empty(0, [("x", 'i2'), ("y", 'i2'), ("time", 'i4')]) if rawData: self.closeRawData() self.sigUpdateRequest.emit(["all"])
def _refresh_content(self, rows): self.display_cache = Fifo(10 * self.max_number_of_rows) self.edit_cache = Fifo(10 * self.max_number_of_rows) self.attributes_cache = Fifo(10 * self.max_number_of_rows) locker = QtCore.QMutexLocker(self._mutex) self.rows_under_request = set() self.unflushed_rows = set() locker.unlock() self.setRowCount(rows)
def CanviEstat(self, estat): locker = QtCore.QMutexLocker(self.mutex) self.estat = estat if not self.isRunning(): self.start(QtCore.QThread.LowPriority) else: self.restart = True self.condition.wakeOne()
def on_press(self, event): if event.xdata is not None and event.ydata is not None: with QtCore.QMutexLocker(self.mutex): if self.mark_number == 1: self.mark1_x = event.xdata self.mark1_y = event.ydata elif self.mark_number == 2: self.mark2_x = event.xdata self.mark2_y = event.ydata self.canvas_clicked_signal.emit()
def _doRegRead(module, address): mutexLocker = QtCore.QMutexLocker(DAEMON_MUTEX) resp = DC.do_control_cmd(DC.reg_read(module, address), control_socket=DAEMON_SOCK) if resp: if resp.type == DC.ControlResponse.REG_IO: return resp.reg_io.val elif resp.type == DC.ControlResponse.ERR: raise hwifError(1, resp.err.code) else: raise hwifError(2)
def render(self, centerX, centerY): locker = QtCore.QMutexLocker(self.mutex) self.centerX = centerX self.centerY = centerY if not self.isRunning(): self.start(QtCore.QThread.LowPriority) else: self.restart = True self.condition.wakeOne()
def stopLoading(self, emitSignal=False): self._stopped = True for thread in self._threads: thread.wait() self._stopped = False # when this goes out of scope the lock is opened locker = QtCore.QMutexLocker(QdImageLoader._mutex) self._paths = [] if emitSignal: self.emit(SIGNAL('loadFinished()'))
def load(self, paths): self._stopped = False self.stopLoading() # when this goes out of scope the lock is opened locker = QtCore.QMutexLocker(QdImageLoader._mutex) self._paths = paths self._index = 0 for thread in self._threads: thread.start(QtCore.QThread.IdlePriority)
def _refresh_content(self, rows): assert object_thread(self) locker = QtCore.QMutexLocker(self._mutex) self.display_cache = Fifo(10 * self.max_number_of_rows) self.edit_cache = Fifo(10 * self.max_number_of_rows) self.attributes_cache = Fifo(10 * self.max_number_of_rows) self.rows_under_request = set() self.unflushed_rows = set() # once the cache has been cleared, no updates ought to be accepted self._update_requests = list() locker.unlock() self.setRowCount(rows)
def render(self, centerX, centerY, scaleFactor, resultSize): with QtCore.QMutexLocker(self.mutex) as locker: self.centerX = centerX self.centerY = centerY self.scaleFactor = scaleFactor self.resultSize = resultSize if not self.isRunning(): self.start(self.LowPriority) else: self.restart = True self.condition.wakeOne()
def run(self): with QtCore.QMutexLocker(self.mutex): self.stoped = False while True: if self.stoped or (self.count == self.times): return value = self.pi.next() if not self.printed: value = str(value) + "." self.printed = True self.emit(QtCore.SIGNAL("updateresult"), str(value)) self.count += 1 sleep(0.1)
def addData(self, name, data, metadata=""): """ write data into exchange object :param name: image name :type name: :obj:`str` :param data: image data :type data: :class:`numpy.ndarray` :param metadata: json dictionary with image metadata :type metadata: :obj:`str` """ with QtCore.QMutexLocker(self.__mutex): self.__elist[0] = name self.__elist[1] = data self.__elist[2] = metadata
def _offset_and_limit_rows_to_get(self): """From the current set of rows to get, find the first continuous range of rows that should be fetched. :return: (offset, limit) """ offset, limit, previous_length, i = 0, 0, 0, 0 # # wait for a while until the rows under request don't change any # more # locker = QtCore.QMutexLocker(self._mutex) while previous_length != len(self.rows_under_request): previous_length = len(self.rows_under_request) locker.unlock() QThread.msleep(5) locker.relock() # # now filter out all rows that have been put in the cache # the gui thread didn't know about # rows_to_get = self.rows_under_request rows_already_there = set() for row in rows_to_get: if self.edit_cache.has_data_at_row(row): rows_already_there.add(row) rows_to_get.difference_update(rows_already_there) rows_to_get = list(rows_to_get) locker.unlock() # # see if there is anything left to do # try: if len(rows_to_get): rows_to_get.sort() offset = rows_to_get[0] # # find first discontinuity # for i in range(offset, rows_to_get[-1] + 1): if rows_to_get[i - offset] != i: break limit = i - offset + 1 except IndexError, e: logger.error('index error with rows_to_get %s' % unicode(rows_to_get), exc_info=e) raise e
def setConfiguration(self, configuration): """ set configuration :param configuration: configuration string :type configuration: :obj:`str` """ if self._configuration != configuration: self._configuration = configuration self.__shost, self.__targetname, self.__portnumber \ = str(self._configuration).split() self.__target = [ self.__targetname, self.__portnumber, 19, [".cbf", ".tif", ".tiff"] ] with QtCore.QMutexLocker(self.__mutex): self.__query = hidra.Transfer("QUERY_NEXT", self.__shost) self._initiated = False
def setConfiguration(self, configuration): """ set configuration :param configuration: configuration string :type configuration: :obj:`str` """ if self._configuration != configuration: self._configuration = configuration self._initiated = False with QtCore.QMutexLocker(self.__mutex): if self.__socket: shost = str(self._configuration).split("/") topic = shost[1] if len(shost) > 1 else "" self.__socket.unbind(self.__bindaddress) self.__socket.setsockopt(zmq.UNSUBSCRIBE, self.__topic) self.__socket.setsockopt(zmq.UNSUBSCRIBE, "datasources") self.__socket.setsockopt(zmq.SUBSCRIBE, "datasources") self.__socket.setsockopt(zmq.SUBSCRIBE, topic) self.__topic = topic self.__socket.connect(self.__bindaddress)