def avantesSetMeasAttribute(self): data = np.ctypeslib.as_array(self.data.c_double_array) data = np.resize(data, GLOBAL_VARS['MAXIMUM_PIXELS_RANGE']) try: setattr(self.data, self.data.type, data) except AttributeError: if __debug__: log.error('Uspecified attribute for data storing')
def __init__(self, args): super().__init__() self.device = dev.Device(args.dev, args.cfg) if not self.device.cfg: if __debug__: log.error('Config was not loaded') exit(-1)
def garbageCollect(): #Run this when we have an empty server (or during a map change...) global THREADS alives = 0 for x, i in enumerate(THREADS): if not i.isAlive(): del THREADS[x] else: alives += 1 log.info('Garbage Collected Threads. %s still alive...' % alives) if alives > config_maxthreads: log.error('Wow... way too many threads for our thread limit! Somethings wrong...')
def channelStartingError(self, channelnum, code, desc): """ Action to take when a negative RPY to a channel start message is received. @param channelnum: the channel number that failed to start """ log.error("Failed to start channel: %d %s" % (code, desc)) self.shutdown()
def next(self): message = self._sock.recv() log.info("Recieved message: %s", message) try: has, wants, user, type, amount, ts = self.__match_request(message).groups() return Request(user, type, amount, has, wants, ts) except AttributeError: log.error("Malformed message! %s did not match: %s", self.__match_request, message) return None
def __init__(self, devType, devCfg): self.cfg = None self.handler = None self.devList = None self.data = data.Data() self.devType = devType self.cfgType = devCfg self.initialize() if not self.deviceSelfTest(): if __debug__: log.error('Unsuccessful device self test') exit(-6)
def avantes(self): """ Value '0' means communication via 'USB' """ if ava.init(ct.c_short(0)) <= 0: if __debug__: log.error('Unsuccessful initialization') exit(-2) else: self.devList = (AvsIdentityType * GLOBAL_VARS['DEVICES_AMOUNT'])() ava.getListOfDevices(sizeof(self.devList), ct.c_uint(1), self.devList) """ Activation of the first 'not used' device in the device list. Probably should be changed to device ID (serial number which is a message queue name) """ for device in self.devList: if device._status[0] == 1: self.handler = ava.activate(device) break if not self.handler: if __debug__: log.error('No handler for device') exit(-3) pixelRange = ct.c_ushort(0) ava.getNumPixels(self.handler, pixelRange) pixelRange.value -= 1 GLOBAL_VARS['MAXIMUM_PIXELS_RANGE'] = pixelRange.value self.cfg = MeasConfigType(self.cfgType) """ If the config was set to 'user' the stop pixel value won't be updated """ if self.cfgType != 'user': self.cfg.loadCfg({'_stopPixel': pixelRange.value}) """ Pickle cannot handle such types in a raw format """ self.devList = None return self.deviceSelfTest() return False
def createChannelZero(self): """ Create the Channel 0 for the Session. A special case of createChannel that explicitly binds the channel to the BEEPManagementProfile. Should only get called once when a Session initialises """ if self.channels.has_key(0): log.error("Attempted to create a Channel 0 when one already exists!") raise SessionException("Can't create more than one Channel 0") else: profile = beepmgmtprofile.BEEPManagementProfile() channel = self.createChannel(0, profile) profile.channelStarted(channel, "", "")
def receive(self, timeout=5): try: # loading message from queue self.message = pickle.loads( self.queues[0][1].receive(timeout=timeout)[0]) """ Setting name of a queue in order to send a response """ if 'response' in self.message.keys(): self.queues[1][0] = self.message['response'] self.setSendQueue() return True except posix.BusyError: if __debug__: log.error('Timeout occur while receiving message') return False
def measure_avantes(self): global MEASUREMENT_TIMEOUT global is_measurement_available global measuring_thread exitStatus = ava.prepareMeasure(self.handler, self.cfg) if __debug__: log.warning('Prepare measurenet function return %s', ERROR_CODES_MESSAGES[exitStatus]) if exitStatus == 0: if self.data.type != 'black': ava.setDigitalOut(self.handler, c_ubyte(3), c_ubyte(1)) else: ava.setDigitalOut(self.handler, c_ubyte(3), c_ubyte(0)) if self.cfg.amount == -1: # infinite measurement exitStatus = ava.measure(self.handler, call_back, c_short(self.cfg.amount)) measuring_thread = threading.Thread(target=self.infinite_measure) measuring_thread.start() else: exitStatus = ava.measure(self.handler, call_back, c_short(self.cfg.amount)) if __debug__: log.warning('Measurement function return %s', ERROR_CODES_MESSAGES[exitStatus]) if exitStatus == 0: """ Main thread stop as a workaround for Incorrect behavior """ if not is_measurement_available.wait(timeout=MEASUREMENT_TIMEOUT): if __debug__: log.error('Measurement timeout occur %s', ERROR_CODES_MESSAGES[exitStatus]) return False else: is_measurement_available.clear() # arbitrary defined timeout time return self.avantesGetScopeData() return False
def infinite_measure(self): global stop_measuring while not stop_measuring.is_set(): time.sleep(0.5) exitStatus = ava.getScopeData(self.handler, c_uint(1), self.data.c_double_array) if exitStatus == 0: avantesSetMeasAttribute() if self.data.type == 'analyte': self.data.calcAbsorbance() if __debug__: log.error('While loop return %s', ERROR_CODES_MESSAGES[exitStatus]) # hook to update the graph # socket io for flask # js on web page return True
def closeAllChannels(self): """ Attempts to close all channels on this Session """ try: for channelnum in self.channels.keys(): if channelnum != 0: self.closeChannel(channelnum) log.debug("Finished queueing closure of %d" % channelnum) ## Close channel 0 last # FIXME: We DO NOT close channel 0 to avoid race condition because # the client should close it # self.closeChannel(0) except Exception, e: # If we can't close a channel, we must remain active # FIXME: more detailed error handling required here log.error("Unable to close Session: %s" % e) traceback.print_exc()
def setSendQueue(self, qname=None): """ Name of a queue, where all messages will be sent should be specified in first use After that, the queue will be set to appropriate one which comes in 'response' key in message dict Might be changed with appopriate function call """ if qname is not None: qname = '/' + qname self.queues[1][0] = qname try: if ((qname is None) and (self.queues[1][0]) is not None): qname = self.queues[1][0] """ Setting receiver message queue if exist in order to send messages """ self.queues[1][1] = posix.MessageQueue(qname) return True except ValueError as error: if __debug__: log.error(error) log.error('Queue name should be specified') return False except posix.ExistentialError: if __debug__: log.error('Cannot open queue %s', qname) return False return False
def avantesGetScopeData(self): """ Scoped data should be collected as many times, as measurement amount was set (amount of measurements) """ for i in range (0, self.cfg.amount): """ Data might not be ready yet, so a procedure will be repeated a few more times, for successful data collection """ timeout = time.time() + 6 while time.time() < timeout: time.sleep(0.5) exitStatus = ava.getScopeData(self.handler, c_uint(1), self.data.c_double_array) if exitStatus != 0: if __debug__: log.error('Cannot get scoped data %s', ERROR_CODES_MESSAGES[exitStatus]) else: break """ Device hadn't sent the data errors in communication might be """ if exitStatus != 0: if __debug__: log.warning('Data receiving timeout') return False self.avantesSetMeasAttribute() if self.data.type == 'analyte': exitStatus = self.data.calcAbsorbance() return True
def authenticationFailed(self, errorCode, errorReason): log.error('Authentication failed: [%s] %s' % (errorCode, errorReason) ) raise SessionException('Authentication Failed')