code
stringlengths
52
7.75k
docs
stringlengths
1
5.85k
def _calculate_influence(self, influence_lambda): return np.exp(-np.arange(self.num_neurons) / influence_lambda)[:, None]
Calculate the ranking influence.
def start(self): LOG.info('Listing options...') with indicator.Spinner(**self.indicator_options): objects_list = self._list_contents() if not objects_list: return # Index items self._index_objects(objects_list=objects_list) # Create the underlying structure self._make_directory_structure() # Download everything LOG.debug('Download Items: %s', self.download_items) self._multi_processor( self._get, items=[i for i in self.download_items.values() for i in i] )
Return a list of objects from the API for a container.
def _epoch(self, X, epoch_idx, batch_size, updates_epoch, constants, show_progressbar): # Create batches X_ = self._create_batches(X, batch_size) X_len = np.prod(X.shape[:-1]) # Initialize the previous activation prev = self._init_prev(X_) prev = self.distance_function(X_[0], self.weights)[0] influences = self._update_params(prev) # Iterate over the training data for idx, x in enumerate(tqdm(X_, disable=not show_progressbar)): # Our batches are padded, so we need to # make sure we know when we hit the padding # so we don't inadvertently learn zeroes. diff = X_len - (idx * batch_size) if diff and diff < batch_size: x = x[:diff] # Prev_activation may be None if prev is not None: prev = prev[:diff] # if idx > 0 and idx % update_step == 0: influences = self._update_params(prev) prev = self._propagate(x, influences, prev_activation=prev)
Run a single epoch. This function shuffles the data internally, as this improves performance. Parameters ---------- X : numpy array The training data. epoch_idx : int The current epoch batch_size : int The batch size updates_epoch : int The number of updates to perform per epoch constants : dict A dictionary containing the constants with which to update the parameters in self.parameters. show_progressbar : bool Whether to show a progressbar during training.
def _update_params(self, constants): constants = np.max(np.min(constants, 1)) self.params['r']['value'] = max([self.params['r']['value'], constants]) epsilon = constants / self.params['r']['value'] influence = self._calculate_influence(epsilon) # Account for learning rate return influence * epsilon
Update the params.
def _calculate_influence(self, neighborhood): n = (self.beta - 1) * np.log(1 + neighborhood*(np.e-1)) + 1 grid = np.exp((-self.distance_grid) / n**2) return grid.reshape(self.num_neurons, self.num_neurons)[:, :, None]
Pre-calculate the influence for a given value of sigma. The neighborhood has size num_neurons * num_neurons, so for a 30 * 30 map, the neighborhood will be size (900, 900). Parameters ---------- neighborhood : float The neighborhood value. Returns ------- neighborhood : numpy array The influence from each neuron to each other neuron.
def bucket_type_key(bucket_type): def decorator(f): @functools.wraps(f) def wrapped(item, session): key = f(item) if session is not None: for handler in session.random_order_bucket_type_key_handlers: key = handler(item, key) return key bucket_type_keys[bucket_type] = wrapped return wrapped return decorator
Registers a function that calculates test item key for the specified bucket type.
def verify_tokens(self): xidentity = key_utils.get_compressed_public_key_from_pem(self.pem) url = self.uri + "/tokens" xsignature = key_utils.sign(self.uri + "/tokens", self.pem) headers = {"content-type": "application/json", 'accept': 'application/json', 'X-Identity': xidentity, 'X-Signature': xsignature, 'X-accept-version': '2.0.0'} response = requests.get(self.uri + "/tokens", headers=headers, verify=self.verify) if response.ok: allTokens = response.json()['data'] selfKeys = self.tokens.keys() matchedTokens = [token for token in allTokens for key in selfKeys if token.get(key) == self.tokens.get(key)] if not matchedTokens: return False return True
Deprecated, will be made private in 2.4
def token_from_response(self, responseJson): token = responseJson['data'][0]['token'] facade = responseJson['data'][0]['facade'] return {facade: token} raise BitPayBitPayError('%(code)d: %(message)s' % {'code': response.status_code, 'message': response.json()['error']})
Deprecated, will be made private in 2.4
def verify_invoice_params(self, price, currency): if re.match("^[A-Z]{3,3}$", currency) is None: raise BitPayArgumentError("Currency is invalid.") try: float(price) except: raise BitPayArgumentError("Price must be formatted as a float")
Deprecated, will be made private in 2.4
def unsigned_request(self, path, payload=None): headers = {"content-type": "application/json", "accept": "application/json", "X-accept-version": "2.0.0"} try: if payload: response = requests.post(self.uri + path, verify=self.verify, data=json.dumps(payload), headers=headers) else: response = requests.get(self.uri + path, verify=self.verify, headers=headers) except Exception as pro: raise BitPayConnectionError('Connection refused') return response
generic bitpay usigned wrapper passing a payload will do a POST, otherwise a GET
def main(): try: # Retrieve the first USB device device = AlarmDecoder(SerialDevice(interface=SERIAL_DEVICE)) # Set up an event handler and open the device device.on_rfx_message += handle_rfx with device.open(baudrate=BAUDRATE): while True: time.sleep(1) except Exception as ex: print('Exception:', ex)
Example application that watches for an event from a specific RF device. This feature allows you to watch for events from RF devices if you have an RF receiver. This is useful in the case of internal sensors, which don't emit a FAULT if the sensor is tripped and the panel is armed STAY. It also will monitor sensors that aren't configured. NOTE: You must have an RF receiver installed and enabled in your panel for RFX messages to be seen.
def handle_rfx(sender, message): # Check for our target serial number and loop if message.serial_number == RF_DEVICE_SERIAL_NUMBER and message.loop[0] == True: print(message.serial_number, 'triggered loop #1')
Handles RF message events from the AlarmDecoder.
def _getfunctionlist(self): try: eventhandler = self.obj.__eventhandler__ except AttributeError: eventhandler = self.obj.__eventhandler__ = {} return eventhandler.setdefault(self.event, [])
(internal use)
def fire(self, *args, **kwargs): for func in self._getfunctionlist(): if type(func) == EventHandler: func.fire(*args, **kwargs) else: func(self.obj, *args, **kwargs)
Fire event and call all handler functions You can call EventHandler object itself like e(*args, **kwargs) instead of e.fire(*args, **kwargs).
def _parse_message(self, data): try: _, values = data.split(':') self.serial_number, self.value = values.split(',') self.value = int(self.value, 16) is_bit_set = lambda b: self.value & (1 << (b - 1)) > 0 # Bit 1 = unknown self.battery = is_bit_set(2) self.supervision = is_bit_set(3) # Bit 4 = unknown self.loop[2] = is_bit_set(5) self.loop[1] = is_bit_set(6) self.loop[3] = is_bit_set(7) self.loop[0] = is_bit_set(8) except ValueError: raise InvalidMessageError('Received invalid message: {0}'.format(data))
Parses the raw message from the device. :param data: message data :type data: string :raises: :py:class:`~alarmdecoder.util.InvalidMessageError`
def dict(self, **kwargs): return dict( time = self.timestamp, serial_number = self.serial_number, value = self.value, battery = self.battery, supervision = self.supervision, **kwargs )
Dictionary representation.
def main(): try: # Retrieve the specified serial device. device = AlarmDecoder(SerialDevice(interface=SERIAL_DEVICE)) # Set up an event handler and open the device device.on_message += handle_message # Override the default SerialDevice baudrate since we're using a USB device # over serial in this example. with device.open(baudrate=BAUDRATE): while True: time.sleep(1) except Exception as ex: print('Exception:', ex)
Example application that opens a serial device and prints messages to the terminal.
def open(self, baudrate=None, no_reader_thread=False): try: self._read_thread = Device.ReadThread(self) self._device = socket.socket(socket.AF_INET, socket.SOCK_STREAM) if self._use_ssl: self._init_ssl() self._device.connect((self._host, self._port)) if self._use_ssl: while True: try: self._device.do_handshake() break except SSL.WantReadError: pass self._id = '{0}:{1}'.format(self._host, self._port) except socket.error as err: raise NoDeviceError('Error opening device at {0}:{1}'.format(self._host, self._port), err) else: self._running = True self.on_open() if not no_reader_thread: self._read_thread.start() return self
Opens the device. :param baudrate: baudrate to use :type baudrate: int :param no_reader_thread: whether or not to automatically open the reader thread. :type no_reader_thread: bool :raises: :py:class:`~alarmdecoder.util.NoDeviceError`, :py:class:`~alarmdecoder.util.CommError`
def close(self): try: # TODO: Find a way to speed up this shutdown. if self.ssl: self._device.shutdown() else: # Make sure that it closes immediately. self._device.shutdown(socket.SHUT_RDWR) except Exception: pass Device.close(self)
Closes the device.
def write(self, data): data_sent = None try: if isinstance(data, str): data = data.encode('utf-8') data_sent = self._device.send(data) if data_sent == 0: raise CommError('Error writing to device.') self.on_write(data=data) except (SSL.Error, socket.error) as err: raise CommError('Error writing to device.', err) return data_sent
Writes data to the device. :param data: data to write :type data: string :returns: number of bytes sent :raises: :py:class:`~alarmdecoder.util.CommError`
def read(self): data = '' try: read_ready, _, _ = select.select([self._device], [], [], 0.5) if len(read_ready) != 0: data = self._device.recv(1) except socket.error as err: raise CommError('Error while reading from device: {0}'.format(str(err)), err) return data.decode('utf-8')
Reads a single character from the device. :returns: character read from the device :raises: :py:class:`~alarmdecoder.util.CommError`
def read_line(self, timeout=0.0, purge_buffer=False): def timeout_event(): """Handles read timeout event""" timeout_event.reading = False timeout_event.reading = True if purge_buffer: self._buffer = b'' got_line, ret = False, None timer = threading.Timer(timeout, timeout_event) if timeout > 0: timer.start() try: while timeout_event.reading: read_ready, _, _ = select.select([self._device], [], [], 0.5) if len(read_ready) == 0: continue buf = self._device.recv(1) if buf != b'' and buf != b"\xff": ub = bytes_hack(buf) self._buffer += ub if ub == b"\n": self._buffer = self._buffer.rstrip(b"\r\n") if len(self._buffer) > 0: got_line = True break except socket.error as err: raise CommError('Error reading from device: {0}'.format(str(err)), err) except SSL.SysCallError as err: errno, msg = err raise CommError('SSL error while reading from device: {0} ({1})'.format(msg, errno)) except Exception: raise else: if got_line: ret, self._buffer = self._buffer, b'' self.on_read(data=ret) else: raise TimeoutError('Timeout while waiting for line terminator.') finally: timer.cancel() return ret.decode('utf-8')
Reads a line from the device. :param timeout: read timeout :type timeout: float :param purge_buffer: Indicates whether to purge the buffer prior to reading. :type purge_buffer: bool :returns: line that was read :raises: :py:class:`~alarmdecoder.util.CommError`, :py:class:`~alarmdecoder.util.TimeoutError`
def purge(self): try: self._device.setblocking(0) while(self._device.recv(1)): pass except socket.error as err: pass finally: self._device.setblocking(1)
Purges read/write buffers.
def _init_ssl(self): if not have_openssl: raise ImportError('SSL sockets have been disabled due to missing requirement: pyopenssl.') try: ctx = SSL.Context(SSL.TLSv1_METHOD) if isinstance(self.ssl_key, crypto.PKey): ctx.use_privatekey(self.ssl_key) else: ctx.use_privatekey_file(self.ssl_key) if isinstance(self.ssl_certificate, crypto.X509): ctx.use_certificate(self.ssl_certificate) else: ctx.use_certificate_file(self.ssl_certificate) if isinstance(self.ssl_ca, crypto.X509): store = ctx.get_cert_store() store.add_cert(self.ssl_ca) else: ctx.load_verify_locations(self.ssl_ca, None) verify_method = SSL.VERIFY_PEER if (self._ssl_allow_self_signed): verify_method = SSL.VERIFY_NONE ctx.set_verify(verify_method, self._verify_ssl_callback) self._device = SSL.Connection(ctx, self._device) except SSL.Error as err: raise CommError('Error setting up SSL connection.', err)
Initializes our device as an SSL connection. :raises: :py:class:`~alarmdecoder.util.CommError`
def get_best_frequencies(self): return self.freq[self.best_local_optima], self.per[self.best_local_optima]
Returns the best n_local_max frequencies
def frequency_grid_evaluation(self, fmin=0.0, fmax=1.0, fresolution=1e-4, n_local_max=10): self.fres_grid = fresolution freq = np.arange(np.amax([fmin, fresolution]), fmax, step=fresolution).astype('float32') Nf = len(freq) per = np.zeros(shape=(Nf,)).astype('float32') for k in range(0, Nf): per[k] = self.compute_metric(freq[k]) self.freq = freq self.per = per
Computes the selected criterion over a grid of frequencies with limits and resolution specified by the inputs. After that the best local maxima are evaluated over a finer frequency grid Parameters --------- fmin: float starting frequency fmax: float stopping frequency fresolution: float step size in the frequency grid
def update(self, message): # Firmware version < 2.2a.8.6 if message.version == 1: if message.event_type == 'ALARM_PANIC': self._alarmdecoder._update_panic_status(True) elif message.event_type == 'CANCEL': self._alarmdecoder._update_panic_status(False) # Firmware version >= 2.2a.8.6 elif message.version == 2: source = message.event_source if source == LRR_EVENT_TYPE.CID: self._handle_cid_message(message) elif source == LRR_EVENT_TYPE.DSC: self._handle_dsc_message(message) elif source == LRR_EVENT_TYPE.ADEMCO: self._handle_ademco_message(message) elif source == LRR_EVENT_TYPE.ALARMDECODER: self._handle_alarmdecoder_message(message) elif source == LRR_EVENT_TYPE.UNKNOWN: self._handle_unknown_message(message) else: pass
Updates the states in the primary AlarmDecoder object based on the LRR message provided. :param message: LRR message object :type message: :py:class:`~alarmdecoder.messages.LRRMessage`
def _handle_cid_message(self, message): status = self._get_event_status(message) if status is None: return if message.event_code in LRR_FIRE_EVENTS: if message.event_code == LRR_CID_EVENT.OPENCLOSE_CANCEL_BY_USER: status = False self._alarmdecoder._update_fire_status(status=status) if message.event_code in LRR_ALARM_EVENTS: kwargs = {} field_name = 'zone' if not status: field_name = 'user' kwargs[field_name] = int(message.event_data) self._alarmdecoder._update_alarm_status(status=status, **kwargs) if message.event_code in LRR_POWER_EVENTS: self._alarmdecoder._update_power_status(status=status) if message.event_code in LRR_BYPASS_EVENTS: self._alarmdecoder._update_zone_bypass_status(status=status, zone=int(message.event_data)) if message.event_code in LRR_BATTERY_EVENTS: self._alarmdecoder._update_battery_status(status=status) if message.event_code in LRR_PANIC_EVENTS: if message.event_code == LRR_CID_EVENT.OPENCLOSE_CANCEL_BY_USER: status = False self._alarmdecoder._update_panic_status(status=status) if message.event_code in LRR_ARM_EVENTS: # NOTE: status on OPENCLOSE messages is backwards. status_stay = (message.event_status == LRR_EVENT_STATUS.RESTORE \ and message.event_code in LRR_STAY_EVENTS) if status_stay: status = False else: status = not status self._alarmdecoder._update_armed_status(status=status, status_stay=status_stay)
Handles ContactID LRR events. :param message: LRR message object :type message: :py:class:`~alarmdecoder.messages.LRRMessage`
def _get_event_status(self, message): status = None if message.event_status == LRR_EVENT_STATUS.TRIGGER: status = True elif message.event_status == LRR_EVENT_STATUS.RESTORE: status = False return status
Retrieves the boolean status of an LRR message. :param message: LRR message object :type message: :py:class:`~alarmdecoder.messages.LRRMessage` :returns: Boolean indicating whether the event was triggered or restored.
def find_all(pattern=None): devices = [] try: if pattern: devices = serial.tools.list_ports.grep(pattern) else: devices = serial.tools.list_ports.comports() except serial.SerialException as err: raise CommError('Error enumerating serial devices: {0}'.format(str(err)), err) return devices
Returns all serial ports present. :param pattern: pattern to search for when retrieving serial ports :type pattern: string :returns: list of devices :raises: :py:class:`~alarmdecoder.util.CommError`
def open(self, baudrate=BAUDRATE, no_reader_thread=False): # Set up the defaults if baudrate is None: baudrate = SerialDevice.BAUDRATE if self._port is None: raise NoDeviceError('No device interface specified.') self._read_thread = Device.ReadThread(self) # Open the device and start up the reader thread. try: self._device.port = self._port self._device.open() # NOTE: Setting the baudrate before opening the # port caused issues with Moschip 7840/7820 # USB Serial Driver converter. (mos7840) # # Moving it to this point seems to resolve # all issues with it. self._device.baudrate = baudrate except (serial.SerialException, ValueError, OSError) as err: raise NoDeviceError('Error opening device on {0}.'.format(self._port), err) else: self._running = True self.on_open() if not no_reader_thread: self._read_thread.start() return self
Opens the device. :param baudrate: baudrate to use with the device :type baudrate: int :param no_reader_thread: whether or not to automatically start the reader thread. :type no_reader_thread: bool :raises: :py:class:`~alarmdecoder.util.NoDeviceError`
def write(self, data): try: # Hack to support unicode under Python 2.x if isinstance(data, str) or (sys.version_info < (3,) and isinstance(data, unicode)): data = data.encode('utf-8') self._device.write(data) except serial.SerialTimeoutException: pass except serial.SerialException as err: raise CommError('Error writing to device.', err) else: self.on_write(data=data)
Writes data to the device. :param data: data to write :type data: string :raises: py:class:`~alarmdecoder.util.CommError`
def read(self): data = '' try: read_ready, _, _ = select.select([self._device.fileno()], [], [], 0.5) if len(read_ready) != 0: data = self._device.read(1) except serial.SerialException as err: raise CommError('Error reading from device: {0}'.format(str(err)), err) return data.decode('utf-8')
Reads a single character from the device. :returns: character read from the device :raises: :py:class:`~alarmdecoder.util.CommError`
def parse_numeric_code(self, force_hex=False): code = None got_error = False if not force_hex: try: code = int(self.numeric_code) except ValueError: got_error = True if force_hex or got_error: try: code = int(self.numeric_code, 16) except ValueError: raise return code
Parses and returns the numeric code as an integer. The numeric code can be either base 10 or base 16, depending on where the message came from. :param force_hex: force the numeric code to be processed as base 16. :type force_hex: boolean :raises: ValueError
def dict(self, **kwargs): return dict( time = self.timestamp, bitfield = self.bitfield, numeric_code = self.numeric_code, panel_data = self.panel_data, mask = self.mask, ready = self.ready, armed_away = self.armed_away, armed_home = self.armed_home, backlight_on = self.backlight_on, programming_mode = self.programming_mode, beeps = self.beeps, zone_bypassed = self.zone_bypassed, ac_power = self.ac_power, chime_on = self.chime_on, alarm_event_occurred = self.alarm_event_occurred, alarm_sounding = self.alarm_sounding, battery_low = self.battery_low, entry_delay_off = self.entry_delay_off, fire_alarm = self.fire_alarm, check_zone = self.check_zone, perimeter_only = self.perimeter_only, text = self.text, cursor_location = self.cursor_location, **kwargs )
Dictionary representation.
def LoadCHM(self, archiveName): '''Loads a CHM archive. This function will also call GetArchiveInfo to obtain information such as the index file name and the topics file. It returns 1 on success, and 0 if it fails. ''' if self.filename is not None: self.CloseCHM() self.file = chmlib.chm_open(archiveName) if self.file is None: return 0 self.filename = archiveName self.GetArchiveInfo() return f LoadCHM(self, archiveName): '''Loads a CHM archive. This function will also call GetArchiveInfo to obtain information such as the index file name and the topics file. It returns 1 on success, and 0 if it fails. ''' if self.filename is not None: self.CloseCHM() self.file = chmlib.chm_open(archiveName) if self.file is None: return 0 self.filename = archiveName self.GetArchiveInfo() return 1
Loads a CHM archive. This function will also call GetArchiveInfo to obtain information such as the index file name and the topics file. It returns 1 on success, and 0 if it fails.
def CloseCHM(self): '''Closes the CHM archive. This function will close the CHM file, if it is open. All variables are also reset. ''' if self.filename is not None: chmlib.chm_close(self.file) self.file = None self.filename = '' self.title = "" self.home = "/" self.index = None self.topics = None self.encoding = Nonf CloseCHM(self): '''Closes the CHM archive. This function will close the CHM file, if it is open. All variables are also reset. ''' if self.filename is not None: chmlib.chm_close(self.file) self.file = None self.filename = '' self.title = "" self.home = "/" self.index = None self.topics = None self.encoding = None
Closes the CHM archive. This function will close the CHM file, if it is open. All variables are also reset.
def GetTopicsTree(self): '''Reads and returns the topics tree. This auxiliary function reads and returns the topics tree file contents for the CHM archive. ''' if self.topics is None: return None if self.topics: res, ui = chmlib.chm_resolve_object(self.file, self.topics) if (res != chmlib.CHM_RESOLVE_SUCCESS): return None size, text = chmlib.chm_retrieve_object(self.file, ui, 0l, ui.length) if (size == 0): sys.stderr.write('GetTopicsTree: file size = 0\n') return None return texf GetTopicsTree(self): '''Reads and returns the topics tree. This auxiliary function reads and returns the topics tree file contents for the CHM archive. ''' if self.topics is None: return None if self.topics: res, ui = chmlib.chm_resolve_object(self.file, self.topics) if (res != chmlib.CHM_RESOLVE_SUCCESS): return None size, text = chmlib.chm_retrieve_object(self.file, ui, 0l, ui.length) if (size == 0): sys.stderr.write('GetTopicsTree: file size = 0\n') return None return text
Reads and returns the topics tree. This auxiliary function reads and returns the topics tree file contents for the CHM archive.
def GetIndex(self): '''Reads and returns the index tree. This auxiliary function reads and returns the index tree file contents for the CHM archive. ''' if self.index is None: return None if self.index: res, ui = chmlib.chm_resolve_object(self.file, self.index) if (res != chmlib.CHM_RESOLVE_SUCCESS): return None size, text = chmlib.chm_retrieve_object(self.file, ui, 0l, ui.length) if (size == 0): sys.stderr.write('GetIndex: file size = 0\n') return None return texf GetIndex(self): '''Reads and returns the index tree. This auxiliary function reads and returns the index tree file contents for the CHM archive. ''' if self.index is None: return None if self.index: res, ui = chmlib.chm_resolve_object(self.file, self.index) if (res != chmlib.CHM_RESOLVE_SUCCESS): return None size, text = chmlib.chm_retrieve_object(self.file, ui, 0l, ui.length) if (size == 0): sys.stderr.write('GetIndex: file size = 0\n') return None return text
Reads and returns the index tree. This auxiliary function reads and returns the index tree file contents for the CHM archive.
def ResolveObject(self, document): '''Tries to locate a document in the archive. This function tries to locate the document inside the archive. It returns a tuple where the first element is zero if the function was successful, and the second is the UnitInfo for that document. The UnitInfo is used to retrieve the document contents ''' if self.file: path = os.path.abspath(document) return chmlib.chm_resolve_object(self.file, path) else: return (1, Nonef ResolveObject(self, document): '''Tries to locate a document in the archive. This function tries to locate the document inside the archive. It returns a tuple where the first element is zero if the function was successful, and the second is the UnitInfo for that document. The UnitInfo is used to retrieve the document contents ''' if self.file: path = os.path.abspath(document) return chmlib.chm_resolve_object(self.file, path) else: return (1, None)
Tries to locate a document in the archive. This function tries to locate the document inside the archive. It returns a tuple where the first element is zero if the function was successful, and the second is the UnitInfo for that document. The UnitInfo is used to retrieve the document contents
def RetrieveObject(self, ui, start=-1, length=-1): '''Retrieves the contents of a document. This function takes a UnitInfo and two optional arguments, the first being the start address and the second is the length. These define the amount of data to be read from the archive. ''' if self.file and ui: if length == -1: len = ui.length else: len = length if start == -1: st = 0l else: st = long(start) return chmlib.chm_retrieve_object(self.file, ui, st, len) else: return (0, ''f RetrieveObject(self, ui, start=-1, length=-1): '''Retrieves the contents of a document. This function takes a UnitInfo and two optional arguments, the first being the start address and the second is the length. These define the amount of data to be read from the archive. ''' if self.file and ui: if length == -1: len = ui.length else: len = length if start == -1: st = 0l else: st = long(start) return chmlib.chm_retrieve_object(self.file, ui, st, len) else: return (0, '')
Retrieves the contents of a document. This function takes a UnitInfo and two optional arguments, the first being the start address and the second is the length. These define the amount of data to be read from the archive.
def Search(self, text, wholewords=0, titleonly=0): '''Performs full-text search on the archive. The first parameter is the word to look for, the second indicates if the search should be for whole words only, and the third parameter indicates if the search should be restricted to page titles. This method will return a tuple, the first item indicating if the search results were partial, and the second item being a dictionary containing the results.''' if text and text != '' and self.file: return extra.search(self.file, text, wholewords, titleonly) else: return Nonf Search(self, text, wholewords=0, titleonly=0): '''Performs full-text search on the archive. The first parameter is the word to look for, the second indicates if the search should be for whole words only, and the third parameter indicates if the search should be restricted to page titles. This method will return a tuple, the first item indicating if the search results were partial, and the second item being a dictionary containing the results.''' if text and text != '' and self.file: return extra.search(self.file, text, wholewords, titleonly) else: return None
Performs full-text search on the archive. The first parameter is the word to look for, the second indicates if the search should be for whole words only, and the third parameter indicates if the search should be restricted to page titles. This method will return a tuple, the first item indicating if the search results were partial, and the second item being a dictionary containing the results.
def GetEncoding(self): '''Returns a string that can be used with the codecs python package to encode or decode the files in the chm archive. If an error is found, or if it is not possible to find the encoding, None is returned.''' if self.encoding: vals = string.split(self.encoding, ',') if len(vals) > 2: try: return charset_table[int(vals[2])] except KeyError: pass return Nonf GetEncoding(self): '''Returns a string that can be used with the codecs python package to encode or decode the files in the chm archive. If an error is found, or if it is not possible to find the encoding, None is returned.''' if self.encoding: vals = string.split(self.encoding, ',') if len(vals) > 2: try: return charset_table[int(vals[2])] except KeyError: pass return None
Returns a string that can be used with the codecs python package to encode or decode the files in the chm archive. If an error is found, or if it is not possible to find the encoding, None is returned.
def GetDWORD(self, buff, idx=0): '''Internal method. Reads a double word (4 bytes) from a buffer. ''' result = buff[idx] + (buff[idx+1] << 8) + (buff[idx+2] << 16) + \ (buff[idx+3] << 24) if result == 0xFFFFFFFF: result = 0 return resulf GetDWORD(self, buff, idx=0): '''Internal method. Reads a double word (4 bytes) from a buffer. ''' result = buff[idx] + (buff[idx+1] << 8) + (buff[idx+2] << 16) + \ (buff[idx+3] << 24) if result == 0xFFFFFFFF: result = 0 return result
Internal method. Reads a double word (4 bytes) from a buffer.
def GetString(self, text, idx): '''Internal method. Retrieves a string from the #STRINGS buffer. ''' next = string.find(text, '\x00', idx) chunk = text[idx:next] return chunf GetString(self, text, idx): '''Internal method. Retrieves a string from the #STRINGS buffer. ''' next = string.find(text, '\x00', idx) chunk = text[idx:next] return chunk
Internal method. Retrieves a string from the #STRINGS buffer.
def main(): try: # Retrieve the first USB device device = AlarmDecoder(USBDevice.find()) # Set up an event handler and open the device device.on_message += handle_message with device.open(): while True: time.sleep(1) except Exception as ex: print('Exception:', ex)
Example application that prints messages from the panel to the terminal.
def main(): try: # Retrieve an AD2 device that has been exposed with ser2sock on localhost:10000. device = AlarmDecoder(SocketDevice(interface=(HOSTNAME, PORT))) # Set up an event handler and open the device device.on_message += handle_message with device.open(): while True: time.sleep(1) except Exception as ex: print('Exception:', ex)
Example application that opens a device that has been exposed to the network with ser2sock or similar serial-to-IP software.
def _parse_message(self, data): try: header, values = data.split(':') address, channel, value = values.split(',') self.address = int(address) self.channel = int(channel) self.value = int(value) except ValueError: raise InvalidMessageError('Received invalid message: {0}'.format(data)) if header == '!EXP': self.type = ExpanderMessage.ZONE elif header == '!REL': self.type = ExpanderMessage.RELAY else: raise InvalidMessageError('Unknown expander message header: {0}'.format(data))
Parse the raw message from the device. :param data: message data :type data: string :raises: :py:class:`~alarmdecoder.util.InvalidMessageError`
def dict(self, **kwargs): return dict( time = self.timestamp, address = self.address, channel = self.channel, value = self.value, **kwargs )
Dictionary representation.
def irregular_sampling(T, N, rseed=None): sampling_period = (T/float(N)) N = int(N) np.random.seed(rseed) t = np.linspace(0, T, num=5*N) # First we add jitter t[1:-1] += sampling_period*0.5*np.random.randn(5*N-2) # Then we do a random permutation and keep only N points P = np.random.permutation(5*N) t_irr = np.sort(t[P[:N]]) return t_irr
Generates an irregularly sampled time vector by perturbating a linearly spaced vector and latter deleting a certain number of points Parameters ---------- T: float Time span of the vector, i.e. how long it is in time N: positive integer Number of samples of the resulting time vector rseed: Random seed to feed the random number generator Returns ------- t_irr: ndarray An irregulary sampled time vector
def trigonometric_model(t, f0, A): y = 0.0 M = len(A) var_y = 0.0 for k in range(0, M): y += A[k]*np.sin(2.0*np.pi*t*f0*(k+1)) var_y += 0.5*A[k]**2 return y, var_y
Generates a simple trigonometric model based on a sum of sine waves Parameters ---------- t: ndarray Vector containing the time instants where the model will be sampled f0: float Fundamental frequency of the model A: ndarray Vector containing the amplitudes of the harmonics in the model. The lenght of A defines the number of harmonics Returns ------- y: ndarray Trigonometric model based var_y: float Analytical variance of the trigonometric model Example ------- Assumming a time vector t has already been specified >>> import P4J >>> y_clean = P4J.trigonometric_model(t, f0=2.0, A=[1.0, 0.5, .25])
def first_order_markov_process(t, variance, time_scale, rseed=None): if variance < 0.0: raise ValueError("Variance must be positive") if time_scale < 0.0: raise ValueError("Time scale must be positive") np.random.seed(rseed) N = len(t) mu = np.zeros(shape=(N,)) if variance == 0.0: return mu dt = np.repeat(np.reshape(t, (1, -1)), N, axis=0) dt = np.absolute(dt - dt.T) # This is NxN S = variance*np.exp(-np.absolute(dt)/time_scale) red_noise = np.random.multivariate_normal(mu, S) return red_noise
Generates a correlated noise vector using a multivariate normal random number generator with zero mean and covariance Sigma_ij = s^2 exp(-|t_i - t_j|/l), where s is the variance and l is the time scale. The Power spectral density associated to this covariance is S(f) = 2*l*s^2/(4*pi^2*f^2*l^2 +1), red noise spectrum is defined as proportional to 1/f^2. This covariance is the one expected from a first order markov process (Reference?) Parameters --------- t: ndarray A time vector for which the red noise vector will be sampled variance: positive float variance of the resulting red noise vector time_scale: positive float Parameter of the covariance matrix Returns ------- red_noise: ndarray Vector containing the red noise realizations See also -------- power_law_noise
def generate_uncertainties(N, dist='Gamma', rseed=None): np.random.seed(rseed) #print(dist) if dist == 'EMG': # Exponential modified Gaussian # the mean of a EMG rv is mu + 1/(K*sigma) # the variance of a EMG rv is sigma**2 + 1/(K*sigma)**2 K = 1.824328605481941 sigma = 0.05*0.068768312946785953 mu = 0.05*0.87452567616276777 # IMPORTANT NOTE # These parameters were obtained after fitting uncertainties # coming from 10,000 light curves of the VVV survey expected_s_2 = sigma**2 + mu**2 + 2*K*mu*sigma + 2*K**2*sigma**2 s = exponnorm.rvs(K, loc=mu, scale=sigma, size=N) elif dist == 'Gamma': # The mean of a gamma rv is k*sigma # The variance of a gamma rv is k*sigma**2 k = 3.0 sigma = 0.05/k # mean=0.05, var=0.05**2/k s = gamma.rvs(k, loc=0.0, scale=sigma, size=N) expected_s_2 = k*(1+k)*sigma**2 return s, expected_s_2
This function generates a uncertainties for the white noise component in the synthetic light curve. Parameters --------- N: positive integer Lenght of the returned uncertainty vector dist: {'EMG', 'Gamma'} Probability density function (PDF) used to generate the uncertainties rseed: Seed for the random number generator Returns ------- s: ndarray Vector containing the uncertainties expected_s_2: float Expectation of the square of s computed analytically
def set_model(self, f0, A, model='trigonometric'): self.f0 = f0 self.y_clean, vary = trigonometric_model(self.t, f0, A) # y_clean is normalized to have unit standard deviation self.y_clean = self.y_clean/np.sqrt(vary)
See also -------- trigonometric_model
def get_event_description(event_type, event_code): description = 'Unknown' lookup_map = LRR_TYPE_MAP.get(event_type, None) if lookup_map is not None: description = lookup_map.get(event_code, description) return description
Retrieves the human-readable description of an LRR event. :param event_type: Base LRR event type. Use LRR_EVENT_TYPE.* :type event_type: int :param event_code: LRR event code :type event_code: int :returns: string
def get_event_source(prefix): source = LRR_EVENT_TYPE.UNKNOWN if prefix == 'CID': source = LRR_EVENT_TYPE.CID elif prefix == 'DSC': source = LRR_EVENT_TYPE.DSC elif prefix == 'AD2': source = LRR_EVENT_TYPE.ALARMDECODER elif prefix == 'ADEMCO': source = LRR_EVENT_TYPE.ADEMCO return source
Retrieves the LRR_EVENT_TYPE corresponding to the prefix provided.abs :param prefix: Prefix to convert to event type :type prefix: string :returns: int
def open(self, baudrate=None, no_reader_thread=False): self._wire_events() try: self._device.open(baudrate=baudrate, no_reader_thread=no_reader_thread) except: self._unwire_events raise return self
Opens the device. If the device cannot be opened, an exception is thrown. In that case, open() can be called repeatedly to try and open the connection. :param baudrate: baudrate used for the device. Defaults to the lower-level device default. :type baudrate: int :param no_reader_thread: Specifies whether or not the automatic reader thread should be started. :type no_reader_thread: bool
def send(self, data): if self._device: if isinstance(data, str): data = str.encode(data) # Hack to support unicode under Python 2.x if sys.version_info < (3,): if isinstance(data, unicode): data = bytes(data) self._device.write(data)
Sends data to the `AlarmDecoder`_ device. :param data: data to send :type data: string
def get_config_string(self): config_entries = [] # HACK: This is ugly.. but I can't think of an elegant way of doing it. config_entries.append(('ADDRESS', '{0}'.format(self.address))) config_entries.append(('CONFIGBITS', '{0:x}'.format(self.configbits))) config_entries.append(('MASK', '{0:x}'.format(self.address_mask))) config_entries.append(('EXP', ''.join(['Y' if z else 'N' for z in self.emulate_zone]))) config_entries.append(('REL', ''.join(['Y' if r else 'N' for r in self.emulate_relay]))) config_entries.append(('LRR', 'Y' if self.emulate_lrr else 'N')) config_entries.append(('DEDUPLICATE', 'Y' if self.deduplicate else 'N')) config_entries.append(('MODE', list(PANEL_TYPES)[list(PANEL_TYPES.values()).index(self.mode)])) config_entries.append(('COM', 'Y' if self.emulate_com else 'N')) config_string = '&'.join(['='.join(t) for t in config_entries]) return '&'.join(['='.join(t) for t in config_entries])
Build a configuration string that's compatible with the AlarmDecoder configuration command from the current values in the object. :returns: string
def fault_zone(self, zone, simulate_wire_problem=False): # Allow ourselves to also be passed an address/channel combination # for zone expanders. # # Format (expander index, channel) if isinstance(zone, tuple): expander_idx, channel = zone zone = self._zonetracker.expander_to_zone(expander_idx, channel) status = 2 if simulate_wire_problem else 1 self.send("L{0:02}{1}\r".format(zone, status))
Faults a zone if we are emulating a zone expander. :param zone: zone to fault :type zone: int :param simulate_wire_problem: Whether or not to simulate a wire fault :type simulate_wire_problem: bool
def _wire_events(self): self._device.on_open += self._on_open self._device.on_close += self._on_close self._device.on_read += self._on_read self._device.on_write += self._on_write self._zonetracker.on_fault += self._on_zone_fault self._zonetracker.on_restore += self._on_zone_restore
Wires up the internal device events.
def _handle_message(self, data): try: data = data.decode('utf-8') except: raise InvalidMessageError('Decode failed for message: {0}'.format(data)) if data is not None: data = data.lstrip('\0') if data is None or data == '': raise InvalidMessageError() msg = None header = data[0:4] if header[0] != '!' or header == '!KPM': msg = self._handle_keypad_message(data) elif header == '!EXP' or header == '!REL': msg = self._handle_expander_message(data) elif header == '!RFX': msg = self._handle_rfx(data) elif header == '!LRR': msg = self._handle_lrr(data) elif header == '!AUI': msg = self._handle_aui(data) elif data.startswith('!Ready'): self.on_boot() elif data.startswith('!CONFIG'): self._handle_config(data) elif data.startswith('!VER'): self._handle_version(data) elif data.startswith('!Sending'): self._handle_sending(data) return msg
Parses keypad messages from the panel. :param data: keypad data to parse :type data: string :returns: :py:class:`~alarmdecoder.messages.Message`
def _handle_keypad_message(self, data): msg = Message(data) if self._internal_address_mask & msg.mask > 0: if not self._ignore_message_states: self._update_internal_states(msg) self.on_message(message=msg) return msg
Handle keypad messages. :param data: keypad message to parse :type data: string :returns: :py:class:`~alarmdecoder.messages.Message`
def _handle_expander_message(self, data): msg = ExpanderMessage(data) self._update_internal_states(msg) self.on_expander_message(message=msg) return msg
Handle expander messages. :param data: expander message to parse :type data: string :returns: :py:class:`~alarmdecoder.messages.ExpanderMessage`
def _handle_rfx(self, data): msg = RFMessage(data) self.on_rfx_message(message=msg) return msg
Handle RF messages. :param data: RF message to parse :type data: string :returns: :py:class:`~alarmdecoder.messages.RFMessage`
def _handle_lrr(self, data): msg = LRRMessage(data) if not self._ignore_lrr_states: self._lrr_system.update(msg) self.on_lrr_message(message=msg) return msg
Handle Long Range Radio messages. :param data: LRR message to parse :type data: string :returns: :py:class:`~alarmdecoder.messages.LRRMessage`
def _handle_aui(self, data): msg = AUIMessage(data) self.on_aui_message(message=msg) return msg
Handle AUI messages. :param data: RF message to parse :type data: string :returns: :py:class`~alarmdecoder.messages.AUIMessage`
def _handle_version(self, data): _, version_string = data.split(':') version_parts = version_string.split(',') self.serial_number = version_parts[0] self.version_number = version_parts[1] self.version_flags = version_parts[2]
Handles received version data. :param data: Version string to parse :type data: string
def _handle_config(self, data): _, config_string = data.split('>') for setting in config_string.split('&'): key, val = setting.split('=') if key == 'ADDRESS': self.address = int(val) elif key == 'CONFIGBITS': self.configbits = int(val, 16) elif key == 'MASK': self.address_mask = int(val, 16) elif key == 'EXP': self.emulate_zone = [val[z] == 'Y' for z in list(range(5))] elif key == 'REL': self.emulate_relay = [val[r] == 'Y' for r in list(range(4))] elif key == 'LRR': self.emulate_lrr = (val == 'Y') elif key == 'DEDUPLICATE': self.deduplicate = (val == 'Y') elif key == 'MODE': self.mode = PANEL_TYPES[val] elif key == 'COM': self.emulate_com = (val == 'Y') self.on_config_received()
Handles received configuration data. :param data: Configuration string to parse :type data: string
def _handle_sending(self, data): matches = re.match('^!Sending(\.{1,5})done.*', data) if matches is not None: good_send = False if len(matches.group(1)) < 5: good_send = True self.on_sending_received(status=good_send, message=data)
Handles results of a keypress send. :param data: Sending string to parse :type data: string
def _update_internal_states(self, message): if isinstance(message, Message) and not self._ignore_message_states: self._update_armed_ready_status(message) self._update_power_status(message) self._update_chime_status(message) self._update_alarm_status(message) self._update_zone_bypass_status(message) self._update_battery_status(message) self._update_fire_status(message) elif isinstance(message, ExpanderMessage): self._update_expander_status(message) self._update_zone_tracker(message)
Updates internal device states. :param message: :py:class:`~alarmdecoder.messages.Message` to update internal states with :type message: :py:class:`~alarmdecoder.messages.Message`, :py:class:`~alarmdecoder.messages.ExpanderMessage`, :py:class:`~alarmdecoder.messages.LRRMessage`, or :py:class:`~alarmdecoder.messages.RFMessage`
def _update_power_status(self, message=None, status=None): power_status = status if isinstance(message, Message): power_status = message.ac_power if power_status is None: return if power_status != self._power_status: self._power_status, old_status = power_status, self._power_status if old_status is not None: self.on_power_changed(status=self._power_status) return self._power_status
Uses the provided message to update the AC power state. :param message: message to use to update :type message: :py:class:`~alarmdecoder.messages.Message` :param status: power status, overrides message bits. :type status: bool :returns: bool indicating the new status
def _update_chime_status(self, message=None, status=None): chime_status = status if isinstance(message, Message): chime_status = message.chime_on if chime_status is None: return if chime_status != self._chime_status: self._chime_status, old_status = chime_status, self._chime_status if old_status is not None: self.on_chime_changed(status=self._chime_status) return self._chime_status
Uses the provided message to update the Chime state. :param message: message to use to update :type message: :py:class:`~alarmdecoder.messages.Message` :param status: chime status, overrides message bits. :type status: bool :returns: bool indicating the new status
def _update_alarm_status(self, message=None, status=None, zone=None, user=None): alarm_status = status alarm_zone = zone if isinstance(message, Message): alarm_status = message.alarm_sounding alarm_zone = message.parse_numeric_code() if alarm_status != self._alarm_status: self._alarm_status, old_status = alarm_status, self._alarm_status if old_status is not None or status is not None: if self._alarm_status: self.on_alarm(zone=alarm_zone) else: self.on_alarm_restored(zone=alarm_zone, user=user) return self._alarm_status
Uses the provided message to update the alarm state. :param message: message to use to update :type message: :py:class:`~alarmdecoder.messages.Message` :param status: alarm status, overrides message bits. :type status: bool :param user: user associated with alarm event :type user: string :returns: bool indicating the new status
def _update_zone_bypass_status(self, message=None, status=None, zone=None): bypass_status = status if isinstance(message, Message): bypass_status = message.zone_bypassed if bypass_status is None: return old_bypass_status = self._bypass_status.get(zone, None) if bypass_status != old_bypass_status: if bypass_status == False and zone is None: self._bypass_status = {} else: self._bypass_status[zone] = bypass_status if old_bypass_status is not None or message is None or (old_bypass_status is None and bypass_status is True): self.on_bypass(status=bypass_status, zone=zone) return bypass_status
Uses the provided message to update the zone bypass state. :param message: message to use to update :type message: :py:class:`~alarmdecoder.messages.Message` :param status: bypass status, overrides message bits. :type status: bool :param zone: zone associated with bypass event :type zone: int :returns: dictionary {Zone:True|False,...} Zone can be None if LRR CID Bypass checking is disabled or we do not know what zones but know something is bypassed.
def _update_armed_ready_status(self, message=None): arm_status = None stay_status = None ready_status = None send_ready = False send_arm = False if isinstance(message, Message): arm_status = message.armed_away stay_status = message.armed_home ready_status = message.ready if arm_status is None or stay_status is None or ready_status is None: return self._armed_stay, old_stay = stay_status, self._armed_stay self._armed_status, old_arm = arm_status, self._armed_status self._ready_status, old_ready_status = ready_status, self._ready_status if old_arm is not None: if arm_status != old_arm or stay_status != old_stay: send_arm = True if old_ready_status is not None: if ready_status != old_ready_status: send_ready = True if send_ready: self.on_ready_changed(status=self._ready_status) if send_arm: if self._armed_status or self._armed_stay: self.on_arm(stay=stay_status) else: self.on_disarm()
Uses the provided message to update the armed state and ready state at once as they can change in the same message and we want both events to have the same states. :param message: message to use to update :type message: :py:class:`~alarmdecoder.messages.Message`
def _update_armed_status(self, message=None, status=None, status_stay=None): arm_status = status stay_status = status_stay if isinstance(message, Message): arm_status = message.armed_away stay_status = message.armed_home if arm_status is None or stay_status is None: return self._armed_status, old_status = arm_status, self._armed_status self._armed_stay, old_stay = stay_status, self._armed_stay if arm_status != old_status or stay_status != old_stay: if old_status is not None or message is None: if self._armed_status or self._armed_stay: self.on_arm(stay=stay_status) else: self.on_disarm() return self._armed_status or self._armed_stay
Uses the provided message to update the armed state. :param message: message to use to update :type message: :py:class:`~alarmdecoder.messages.Message` :param status: armed status, overrides message bits :type status: bool :param status_stay: armed stay status, overrides message bits :type status_stay: bool :returns: bool indicating the new status
def _update_battery_status(self, message=None, status=None): battery_status = status if isinstance(message, Message): battery_status = message.battery_low if battery_status is None: return last_status, last_update = self._battery_status if battery_status == last_status: self._battery_status = (last_status, time.time()) else: if battery_status is True or time.time() > last_update + self._battery_timeout: self._battery_status = (battery_status, time.time()) self.on_low_battery(status=battery_status) return self._battery_status[0]
Uses the provided message to update the battery state. :param message: message to use to update :type message: :py:class:`~alarmdecoder.messages.Message` :param status: battery status, overrides message bits :type status: bool :returns: boolean indicating the new status
def _update_fire_status(self, message=None, status=None): fire_status = status last_status = self._fire_status if isinstance(message, Message): # Quirk in Ademco panels. The fire bit drops on "SYSTEM LO BAT" messages. # FIXME: does not support non english panels. if self.mode == ADEMCO and message.text.startswith("SYSTEM"): fire_status = last_status else: fire_status = message.fire_alarm if fire_status is None: return if fire_status != self._fire_status: self._fire_status, old_status = fire_status, self._fire_status if old_status is not None: self.on_fire(status=self._fire_status) return self._fire_status
Uses the provided message to update the fire alarm state. :param message: message to use to update :type message: :py:class:`~alarmdecoder.messages.Message` :param status: fire status, overrides message bits :type status: bool :returns: boolean indicating the new status
def _update_panic_status(self, status=None): if status is None: return if status != self._panic_status: self._panic_status, old_status = status, self._panic_status if old_status is not None: self.on_panic(status=self._panic_status) return self._panic_status
Updates the panic status of the alarm panel. :param status: status to use to update :type status: boolean :returns: boolean indicating the new status
def _update_expander_status(self, message): if message.type == ExpanderMessage.RELAY: self._relay_status[(message.address, message.channel)] = message.value self.on_relay_changed(message=message) return self._relay_status[(message.address, message.channel)]
Uses the provided message to update the expander states. :param message: message to use to update :type message: :py:class:`~alarmdecoder.messages.ExpanderMessage` :returns: boolean indicating the new status
def _update_zone_tracker(self, message): # Retrieve a list of faults. # NOTE: This only happens on first boot or after exiting programming mode. if isinstance(message, Message): if not message.ready and ("Hit * for faults" in message.text or "Press * to show faults" in message.text): if time.time() > self.last_fault_expansion + self.fault_expansion_time_limit: self.last_fault_expansion = time.time() self.send('*') return self._zonetracker.update(message)
Trigger an update of the :py:class:`~alarmdecoder.messages.Zonetracker`. :param message: message to update the zonetracker with :type message: :py:class:`~alarmdecoder.messages.Message`, :py:class:`~alarmdecoder.messages.ExpanderMessage`, :py:class:`~alarmdecoder.messages.LRRMessage`, or :py:class:`~alarmdecoder.messages.RFMessage`
def _on_open(self, sender, *args, **kwargs): self.get_config() self.get_version() self.on_open()
Internal handler for opening the device.
def _on_read(self, sender, *args, **kwargs): data = kwargs.get('data', None) self.on_read(data=data) self._handle_message(data)
Internal handler for reading from the device.
def _on_write(self, sender, *args, **kwargs): self.on_write(data=kwargs.get('data', None))
Internal handler for writing to the device.
def expander_to_zone(self, address, channel, panel_type=ADEMCO): zone = -1 if panel_type == ADEMCO: # TODO: This is going to need to be reworked to support the larger # panels without fixed addressing on the expanders. idx = address - 7 # Expanders start at address 7. zone = address + channel + (idx * 7) + 1 elif panel_type == DSC: zone = (address * 8) + channel return zone
Convert an address and channel into a zone number. :param address: expander address :type address: int :param channel: channel :type channel: int :returns: zone number associated with an address and channel
def _clear_zones(self, zone): cleared_zones = [] found_last_faulted = found_current = at_end = False # First pass: Find our start spot. it = iter(self._zones_faulted) try: while not found_last_faulted: z = next(it) if z == self._last_zone_fault: found_last_faulted = True break except StopIteration: at_end = True # Continue until we find our end point and add zones in # between to our clear list. try: while not at_end and not found_current: z = next(it) if z == zone: found_current = True break else: cleared_zones += [z] except StopIteration: pass # Second pass: roll through the list again if we didn't find # our end point and remove everything until we do. if not found_current: it = iter(self._zones_faulted) try: while not found_current: z = next(it) if z == zone: found_current = True break else: cleared_zones += [z] except StopIteration: pass # Actually remove the zones and trigger the restores. for z in cleared_zones: self._update_zone(z, Zone.CLEAR)
Clear all expired zones from our status list. :param zone: current zone being processed :type zone: int
def _clear_expired_zones(self): zones = [] for z in list(self._zones.keys()): zones += [z] for z in zones: if self._zones[z].status != Zone.CLEAR and self._zone_expired(z): self._update_zone(z, Zone.CLEAR)
Update zone status for all expired zones.
def _add_zone(self, zone, name='', status=Zone.CLEAR, expander=False): if not zone in self._zones: self._zones[zone] = Zone(zone=zone, name=name, status=None, expander=expander) self._update_zone(zone, status=status)
Adds a zone to the internal zone list. :param zone: zone number :type zone: int :param name: human readable zone name :type name: string :param status: zone status :type status: int
def _update_zone(self, zone, status=None): if not zone in self._zones: raise IndexError('Zone does not exist and cannot be updated: %d', zone) old_status = self._zones[zone].status if status is None: status = old_status self._zones[zone].status = status self._zones[zone].timestamp = time.time() if status == Zone.CLEAR: if zone in self._zones_faulted: self._zones_faulted.remove(zone) self.on_restore(zone=zone) else: if old_status != status and status is not None: self.on_fault(zone=zone)
Updates a zones status. :param zone: zone number :type zone: int :param status: zone status :type status: int :raises: IndexError
def _zone_expired(self, zone): return (time.time() > self._zones[zone].timestamp + Zonetracker.EXPIRE) and self._zones[zone].expander is False
Determine if a zone is expired or not. :param zone: zone number :type zone: int :returns: whether or not the zone is expired
def main(): try: # Retrieve the first USB device device = AlarmDecoder(SerialDevice(interface=SERIAL_DEVICE)) # Set up an event handlers and open the device device.on_zone_fault += handle_zone_fault device.on_zone_restore += handle_zone_restore with device.open(baudrate=BAUDRATE): last_update = time.time() while True: if time.time() - last_update > WAIT_TIME: last_update = time.time() device.fault_zone(TARGET_ZONE) time.sleep(1) except Exception as ex: print('Exception:', ex)
Example application that periodically faults a virtual zone and then restores it. This is an advanced feature that allows you to emulate a virtual zone. When the AlarmDecoder is configured to emulate a zone expander we can fault and restore those zones programmatically at will. These events can also be seen by others, such as home automation platforms which allows you to connect other devices or services and monitor them as you would any physical zone. For example, you could connect a ZigBee device and receiver and fault or restore it's zone(s) based on the data received. In order for this to happen you need to perform a couple configuration steps: 1. Enable zone expander emulation on your AlarmDecoder device by hitting '!' in a terminal and going through the prompts. 2. Enable the zone expander in your panel programming.
def bytes_available(device): bytes_avail = 0 if isinstance(device, alarmdecoder.devices.SerialDevice): if hasattr(device._device, "in_waiting"): bytes_avail = device._device.in_waiting else: bytes_avail = device._device.inWaiting() elif isinstance(device, alarmdecoder.devices.SocketDevice): bytes_avail = 4096 return bytes_avail
Determines the number of bytes available for reading from an AlarmDecoder device :param device: the AlarmDecoder device :type device: :py:class:`~alarmdecoder.devices.Device` :returns: int
def bytes_hack(buf): ub = None if sys.version_info > (3,): ub = buf else: ub = bytes(buf) return ub
Hacky workaround for old installs of the library on systems without python-future that were keeping the 2to3 update from working after auto-update.
def read_firmware_file(file_path): data_queue = deque() with open(file_path) as firmware_handle: for line in firmware_handle: line = line.rstrip() if line != '' and line[0] == ':': data_queue.append(line + "\r") return data_queue
Reads a firmware file into a dequeue for processing. :param file_path: Path to the firmware file :type file_path: string :returns: deque
def read(device): response = None bytes_avail = bytes_available(device) if isinstance(device, alarmdecoder.devices.SerialDevice): response = device._device.read(bytes_avail) elif isinstance(device, alarmdecoder.devices.SocketDevice): response = device._device.recv(bytes_avail) return response
Reads data from the specified device. :param device: the AlarmDecoder device :type device: :py:class:`~alarmdecoder.devices.Device` :returns: string
def main(): try: # Start up the detection thread such that handle_attached and handle_detached will # be called when devices are attached and detached, respectively. USBDevice.start_detection(on_attached=handle_attached, on_detached=handle_detached) # Wait for events. while True: time.sleep(1) except Exception as ex: print('Exception:', ex) finally: # Close all devices and stop detection. for sn, device in __devices.items(): device.close() USBDevice.stop_detection()
Example application that shows how to handle attach/detach events generated by the USB devices. In this case we open the device and listen for messages when it is attached. And when it is detached we remove it from our list of monitored devices.
def create_device(device_args): device = AlarmDecoder(USBDevice.find(device_args)) device.on_message += handle_message device.open() return device
Creates an AlarmDecoder from the specified USB device arguments. :param device_args: Tuple containing information on the USB device to open. :type device_args: Tuple (vid, pid, serialnumber, interface_count, description)
def handle_attached(sender, device): # Create the device from the specified device arguments. dev = create_device(device) __devices[dev.id] = dev print('attached', dev.id)
Handles attached events from USBDevice.start_detection().
def handle_detached(sender, device): vendor, product, sernum, ifcount, description = device # Close and remove the device from our list. if sernum in list(__devices.keys()): __devices[sernum].close() del __devices[sernum] print('detached', sernum)
Handles detached events from USBDevice.start_detection().