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)
# Crea... | 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... | 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
u... |
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(ep... | 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
-... |
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)
... | 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': xsi... | 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:
... | 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:
t... | 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 m... |
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.ba... | 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,
... | 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 ... | 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._hos... | 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... |
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:
... | 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... | 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}'.for... | 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
... | 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:`~alarmdeco... |
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.... | 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')
... | 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
... |
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._alarmdecode... | 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... | 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... | 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(sel... | 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.NoDevice... |
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.SerialTimeoutExcep... | 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 dev... | 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:
... | 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,
... | 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.CloseC... | 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 = ''
sel... | 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... | 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.fil... | 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... | 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 con... |
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.
'''
... | 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 ... | 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 firs... |
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... | 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... | 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 #STRI... | 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 ... | 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():
... | 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 In... | 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.r... | 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 t... |
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 harm... |
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 =... | 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*... |
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... | 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
uncerta... |
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... | 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
:para... |
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)
... | 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.... | 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 ... | 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 += s... | 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 == '':
rais... | 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 =... | 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(messa... | 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:`~alarmdec... |
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_... | 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_... | 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 != ... | 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
:... |
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, ... | 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
... |
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.arme... | 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_st... | 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... |
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 batte... | 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.... | 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)
... | 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 mes... | 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:`~al... |
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... | 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 == se... | 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... | 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... | 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 b... |
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, alarmd... | 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._d... | 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.
w... | 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(). |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.