code string | signature string | docstring string | loss_without_docstring float64 | loss_with_docstring float64 | factor float64 |
|---|---|---|---|---|---|
params = args.split()
addr = None
clear = True
try:
addr = params[0]
except IndexError:
_LOGGING.error('Device address required.')
self.do_help('load_aldb')
try:
clear_prior = params[1]
_LOGGING.info('param clear_prior %s', clear_prior)
if clear_prior.lower() == 'y':
clear = True
elif clear_prior.lower() == 'n':
clear = False
else:
_LOGGING.error('Invalid value for parameter `clear_prior`')
_LOGGING.error('Valid values are `y` or `n`')
except IndexError:
pass
if addr:
if addr.lower() == 'all':
await self.tools.load_all_aldb(clear)
else:
await self.tools.load_device_aldb(addr, clear)
else:
self.do_help('load_aldb') | async def do_load_aldb(self, args) | Load the All-Link database for a device.
Usage:
load_aldb address|all [clear_prior]
Arguments:
address: NSTEON address of the device
all: Load the All-Link database for all devices
clear_prior: y|n
y - Clear the prior data and start fresh.
n - Keep the prior data and only apply changes
Default is y
This does NOT write to the database so no changes are made to the
device with this command. | 2.727578 | 2.415179 | 1.129348 |
params = args.split()
addr = None
mem_bytes = None
memory = None
mode = None
group = None
target = None
data1 = 0x00
data2 = 0x00
data3 = 0x00
try:
addr = Address(params[0])
mem_bytes = binascii.unhexlify(params[1])
memory = int.from_bytes(mem_bytes, byteorder='big')
mode = params[2]
group = int(params[3])
target = Address(params[4])
_LOGGING.info('address: %s', addr)
_LOGGING.info('memory: %04x', memory)
_LOGGING.info('mode: %s', mode)
_LOGGING.info('group: %d', group)
_LOGGING.info('target: %s', target)
except IndexError:
_LOGGING.error('Device address memory mode group and target '
'are all required.')
self.do_help('write_aldb')
except ValueError:
_LOGGING.error('Value error - Check parameters')
self.do_help('write_aldb')
try:
data1 = int(params[5])
data2 = int(params[6])
data3 = int(params[7])
except IndexError:
pass
except ValueError:
addr = None
_LOGGING.error('Value error - Check parameters')
self.do_help('write_aldb')
return
if addr and memory and mode and isinstance(group, int) and target:
await self.tools.write_aldb(addr, memory, mode, group, target,
data1, data2, data3) | async def do_write_aldb(self, args) | Write device All-Link record.
WARNING THIS METHOD CAN DAMAGE YOUR DEVICE IF USED INCORRECTLY.
Please ensure the memory id is appropriate for the device.
You must load the ALDB of the device before using this method.
The memory id must be an existing memory id in the ALDB or this
method will return an error.
If you are looking to create a new link between two devices,
use the `link_devices` command or the `start_all_linking` command.
Usage:
write_aldb addr memory mode group target [data1 data2 data3]
Required Parameters:
addr: Inseon address of the device to write
memory: record ID of the record to write (i.e. 0fff)
mode: r | c
r = Device is a responder of target
c = Device is a controller of target
group: All-Link group integer
target: Insteon address of the link target device
Optional Parameters:
data1: int = Device sepcific
data2: int = Device specific
data3: int = Device specific | 2.368712 | 2.0679 | 1.145468 |
params = args.split()
addr = None
mem_bytes = None
memory = None
try:
addr = Address(params[0])
mem_bytes = binascii.unhexlify(params[1])
memory = int.from_bytes(mem_bytes, byteorder='big')
_LOGGING.info('address: %s', addr)
_LOGGING.info('memory: %04x', memory)
except IndexError:
_LOGGING.error('Device address and memory are required.')
self.do_help('del_aldb')
except ValueError:
_LOGGING.error('Value error - Check parameters')
self.do_help('write_aldb')
if addr and memory:
await self.tools.del_aldb(addr, memory) | async def do_del_aldb(self, args) | Delete device All-Link record.
WARNING THIS METHOD CAN DAMAGE YOUR DEVICE IF USED INCORRECTLY.
Please ensure the memory id is appropriate for the device.
You must load the ALDB of the device before using this method.
The memory id must be an existing memory id in the ALDB or this
method will return an error.
If you are looking to create a new link between two devices,
use the `link_devices` command or the `start_all_linking` command.
Usage:
del_aldb addr memory
Required Parameters:
addr: Inseon address of the device to write
memory: record ID of the record to write (i.e. 0fff) | 3.670028 | 3.417171 | 1.073996 |
if arg in ['i', 'v']:
_LOGGING.info('Setting log level to %s', arg)
if arg == 'i':
_LOGGING.setLevel(logging.INFO)
_INSTEONPLM_LOGGING.setLevel(logging.INFO)
else:
_LOGGING.setLevel(logging.DEBUG)
_INSTEONPLM_LOGGING.setLevel(logging.DEBUG)
else:
_LOGGING.error('Log level value error.')
self.do_help('set_log_level') | def do_set_log_level(self, arg) | Set the log level.
Usage:
set_log_level i|v
Parameters:
log_level: i - info | v - verbose | 2.994904 | 2.936472 | 1.019899 |
params = args.split()
device = None
try:
device = params[0]
except IndexError:
_LOGGING.error('Device name required.')
self.do_help('set_device')
if device:
self.tools.device = device | def do_set_device(self, args) | Set the PLM OS device.
Device defaults to /dev/ttyUSB0
Usage:
set_device device
Arguments:
device: Required - INSTEON PLM device | 5.207966 | 6.10173 | 0.853523 |
params = args.split()
workdir = None
try:
workdir = params[0]
except IndexError:
_LOGGING.error('Device name required.')
self.do_help('set_workdir')
if workdir:
self.tools.workdir = workdir | def do_set_workdir(self, args) | Set the working directory.
The working directory is used to load and save known devices
to improve startup times. During startup the application
loads and saves a file `insteon_plm_device_info.dat`. This file
is saved in the working directory.
The working directory has no default value. If the working directory is
not set, the `insteon_plm_device_info.dat` file is not loaded or saved.
Usage:
set_workdir workdir
Arguments:
workdir: Required - Working directory to load and save devie list | 5.731407 | 6.942953 | 0.8255 |
cmds = arg.split()
if cmds:
func = getattr(self, 'do_{}'.format(cmds[0]))
if func:
_LOGGING.info(func.__doc__)
else:
_LOGGING.error('Command %s not found', cmds[0])
else:
_LOGGING.info("Available command list: ")
for curr_cmd in dir(self.__class__):
if curr_cmd.startswith("do_") and not curr_cmd == 'do_test':
print(" - ", curr_cmd[3:])
_LOGGING.info("For help with a command type `help command`") | def do_help(self, arg) | Help command.
Usage:
help [command]
Parameters:
command: Optional - command name to display detailed help | 3.461666 | 3.935497 | 0.879601 |
params = args.split()
addr = None
cat = None
subcat = None
firmware = None
error = None
try:
addr = Address(params[0])
cat = binascii.unhexlify(params[1][2:])
subcat = binascii.unhexlify(params[2][2:])
firmware = binascii.unhexlify(params[3][2:])
except IndexError:
error = 'missing'
except ValueError:
error = 'value'
if addr and cat and subcat:
self.tools.add_device_override(addr, cat, subcat, firmware)
else:
if error == 'missing':
_LOGGING.error('Device address, category and subcategory are '
'required.')
else:
_LOGGING.error('Check the vales for address, category and '
'subcategory.')
self.do_help('add_device_override') | def do_add_device_override(self, args) | Add a device override to the IM.
Usage:
add_device_override address cat subcat [firmware]
Arguments:
address: Insteon address of the device to override
cat: Device category
subcat: Device subcategory
firmware: Optional - Device firmware
The device address can be written with our without the dots and in
upper or lower case, for example: 1a2b3c or 1A.2B.3C.
The category, subcategory and firmware numbers are written in hex
format, for example: 0x01 0x1b
Example:
add_device_override 1a2b3c 0x02 0x1a | 3.048821 | 2.848276 | 1.070409 |
params = args.split()
housecode = None
unitcode = None
dev_type = None
try:
housecode = params[0]
unitcode = int(params[1])
if unitcode not in range(1, 17):
raise ValueError
dev_type = params[2]
except IndexError:
pass
except ValueError:
_LOGGING.error('X10 unit code must be an integer 1 - 16')
unitcode = None
if housecode and unitcode and dev_type:
device = self.tools.add_x10_device(housecode, unitcode, dev_type)
if not device:
_LOGGING.error('Device not added. Please check the '
'information you provided.')
self.do_help('add_x10_device')
else:
_LOGGING.error('Device housecode, unitcode and type are '
'required.')
self.do_help('add_x10_device') | def do_add_x10_device(self, args) | Add an X10 device to the IM.
Usage:
add_x10_device housecode unitcode type
Arguments:
housecode: Device housecode (A - P)
unitcode: Device unitcode (1 - 16)
type: Device type
Current device types are:
- OnOff
- Dimmable
- Sensor
Example:
add_x10_device M 12 OnOff | 2.712578 | 2.396041 | 1.132108 |
params = args.split()
address = None
group = None
try:
address = params[0]
group = int(params[1])
except IndexError:
_LOGGING.error("Address and group are regquired")
self.do_help('kpl_status')
except TypeError:
_LOGGING.error("Group must be an integer")
self.do_help('kpl_status')
if address and group:
self.tools.kpl_status(address, group) | def do_kpl_status(self, args) | Get the status of a KeypadLinc button.
Usage:
kpl_status address group | 3.61944 | 3.263989 | 1.108901 |
params = args.split()
address = None
group = None
try:
address = params[0]
group = int(params[1])
except IndexError:
_LOGGING.error("Address and group are regquired")
self.do_help('kpl_status')
except TypeError:
_LOGGING.error("Group must be an integer")
self.do_help('kpl_status')
if address and group:
self.tools.kpl_on(address, group) | def do_kpl_on(self, args) | Turn on a KeypadLinc button.
Usage:
kpl_on address group | 3.840835 | 3.516511 | 1.092229 |
params = args.split()
address = None
group = None
try:
address = params[0]
group = int(params[1])
except IndexError:
_LOGGING.error("Address and group are regquired")
self.do_help('kpl_status')
except TypeError:
_LOGGING.error("Group must be an integer")
self.do_help('kpl_status')
if address and group:
self.tools.kpl_off(address, group) | def do_kpl_off(self, args) | Turn off a KeypadLinc button.
Usage:
kpl_on address group | 3.784513 | 3.520816 | 1.074896 |
params = args.split()
address = None
group = None
mask_string = None
mask = None
try:
address = params[0]
group = int(params[1])
mask_string = params[2]
if mask_string[0:2].lower() == '0x':
mask = binascii.unhexlify(mask_string[2:])
else:
mask = int(mask_string)
except IndexError:
_LOGGING.error("Address, group and mask are regquired")
self.do_help('kpl_status')
except TypeError:
_LOGGING.error("Group must be an integer")
self.do_help('kpl_status')
if address and group and mask:
self.tools.kpl_set_on_mask(address, group, mask) | def do_kpl_set_on_mask(self, args) | Set the on mask for a KeypadLinc button.
Usage:
kpl_set_on_mask address group mask | 2.861719 | 2.72251 | 1.051132 |
strout = ''
first = True
for i in range(0, 28, 2):
if first:
first = False
else:
strout = strout + '.'
strout = strout + self.hex[i:i + 2]
return strout | def human(self) | Emit the address in human-readible format (AA.BB.CC). | 3.605044 | 2.962009 | 1.217094 |
byteout = bytearray()
for i in range(1, 15):
key = 'd' + str(i)
if self._userdata[key] is not None:
byteout.append(self._userdata[key])
else:
byteout.append(0x00)
return byteout | def bytes(self) | Emit the address in bytes format. | 3.659528 | 3.325442 | 1.100464 |
empty = cls.create_empty(0x00)
userdata_dict = cls.normalize(empty, rawmessage)
return Userdata(userdata_dict) | def from_raw_message(cls, rawmessage) | Create a user data instance from a raw byte stream. | 10.366826 | 7.686456 | 1.348713 |
empty = cls.create_empty(None)
userdata_dict = cls.normalize(empty, userdata)
return Userdata(userdata_dict) | def create_pattern(cls, userdata) | Create a user data instance with all values the same. | 9.421779 | 7.521704 | 1.252612 |
ud = Userdata(cls.normalize(cls.create_empty(None), userdata))
return ud | def template(cls, userdata) | Create a template instance used for message callbacks. | 18.149685 | 17.546204 | 1.034394 |
ismatch = False
if isinstance(other, Userdata):
for key in self._userdata:
if self._userdata[key] is None or other[key] is None:
ismatch = True
elif self._userdata[key] == other[key]:
ismatch = True
else:
ismatch = False
break
return ismatch | def matches_pattern(self, other) | Test if the current instance matches a template instance. | 2.784913 | 2.722426 | 1.022953 |
userdata_dict = {}
for i in range(1, 15):
key = 'd{}'.format(i)
userdata_dict.update({key: val})
return userdata_dict | def create_empty(cls, val=0x00) | Create an empty Userdata object.
val: value to fill the empty user data fields with (default is 0x00) | 4.672737 | 4.435581 | 1.053467 |
if isinstance(userdata, Userdata):
return userdata.to_dict()
if isinstance(userdata, dict):
return cls._dict_to_dict(empty, userdata)
if isinstance(userdata, (bytes, bytearray)):
return cls._bytes_to_dict(empty, userdata)
if userdata is None:
return empty
raise ValueError | def normalize(cls, empty, userdata) | Return normalized user data as a dictionary.
empty: an empty dictionary
userdata: data in the form of Userdata, dict or None | 2.50967 | 2.145445 | 1.169767 |
props = self._message_properties()
msg = bytearray([MESSAGE_START_CODE_0X02, self._code])
for prop in props:
# pylint: disable=unused-variable
for key, val in prop.items():
if val is None:
pass
elif isinstance(val, int):
msg.append(val)
elif isinstance(val, Address):
if val.addr is None:
pass
else:
msg.extend(val.bytes)
elif isinstance(val, MessageFlags):
msg.extend(val.bytes)
elif isinstance(val, bytearray):
msg.extend(val)
elif isinstance(val, bytes):
msg.extend(val)
elif isinstance(val, Userdata):
msg.extend(val.bytes)
return binascii.hexlify(msg).decode() | def hex(self) | Hexideciaml representation of the message in bytes. | 3.157079 | 2.941517 | 1.073282 |
properties = self._message_properties()
ismatch = False
if isinstance(other, Message) and self.code == other.code:
for prop in properties:
for key, prop_val in prop.items():
if hasattr(other, key):
key_val = getattr(other, key)
ismatch = self._test_match(prop_val, key_val)
else:
ismatch = False
if not ismatch:
break
if not ismatch:
break
return ismatch | def matches_pattern(self, other) | Return if the current message matches a message template.
Compare the current message to a template message to test matches
to a pattern. | 3.366878 | 3.158763 | 1.065885 |
on_command = StandardSend(self._address,
COMMAND_LIGHT_ON_0X11_NONE, 0xff)
self._send_method(on_command,
self._on_message_received) | def on(self) | Send ON command to device. | 14.642731 | 10.376507 | 1.411143 |
self._send_method(StandardSend(self._address,
COMMAND_LIGHT_OFF_0X13_0X00),
self._off_message_received) | def off(self) | Send OFF command to device. | 19.619799 | 15.776073 | 1.243643 |
status_command = StandardSend(self._address,
COMMAND_LIGHT_STATUS_REQUEST_0X19_0X01)
self._send_method(status_command, self._status_message_0x01_received) | def _send_status_0x01_request(self) | Sent status request to device. | 8.609678 | 7.285705 | 1.181722 |
if msg.cmd2 == 0x00 or msg.cmd2 == 0x02:
self._update_subscribers(0x00)
elif msg.cmd2 == 0x01 or msg.cmd2 == 0x03:
self._update_subscribers(0xff)
else:
raise ValueError | def _status_message_0x01_received(self, msg) | Handle status received messages.
The following status values can be received:
0x00 = Both Outlets Off
0x01 = Only Top Outlet On
0x02 = Only Bottom Outlet On
0x03 = Both Outlets On | 2.785213 | 2.846588 | 0.978439 |
on_command = ExtendedSend(self._address,
COMMAND_LIGHT_ON_0X11_NONE,
self._udata,
cmd2=0xff)
on_command.set_checksum()
self._send_method(on_command, self._on_message_received) | def on(self) | Send an ON message to device group. | 12.996798 | 10.520546 | 1.235373 |
off_command = ExtendedSend(self._address,
COMMAND_LIGHT_OFF_0X13_0X00,
self._udata)
off_command.set_checksum()
self._send_method(off_command, self._off_message_received) | def off(self) | Send an OFF message to device group. | 11.774835 | 9.820516 | 1.199004 |
status_command = StandardSend(self._address,
COMMAND_LIGHT_STATUS_REQUEST_0X19_0X01)
self._send_method(status_command, self._status_message_received) | def _send_status_0x01_request(self) | Send a status request. | 9.814746 | 8.813772 | 1.113569 |
if msg.cmd2 == 0x00 or msg.cmd2 == 0x01:
self._update_subscribers(0x00)
elif msg.cmd2 == 0x02 or msg.cmd2 == 0x03:
self._update_subscribers(0xff)
else:
raise ValueError | def _status_message_received(self, msg) | Receive a status message.
The following status values can be received:
0x00 = Both Outlets Off
0x01 = Only Top Outlet On
0x02 = Only Bottom Outlet On
0x03 = Both Outlets On | 2.941508 | 2.815943 | 1.044591 |
close_command = StandardSend(self._address,
COMMAND_LIGHT_OFF_0X13_0X00)
self._send_method(close_command, self._close_message_received) | def close(self) | Send CLOSE command to device. | 13.824748 | 10.181828 | 1.357787 |
_LOGGER.debug("Button %d LED changed from %d to %d",
self._group, self._value, val)
led_on = bool(val)
if led_on != bool(self._value):
self._update_subscribers(int(led_on)) | def led_changed(self, addr, group, val) | Capture a change to the LED for this button. | 4.945549 | 4.618207 | 1.070881 |
set_cmd = self._create_set_property_msg('_on_mask', 0x02, mask)
self._send_method(set_cmd, self._property_set) | def set_on_mask(self, mask) | Set the on mask for the current group/button. | 9.289269 | 8.873971 | 1.0468 |
set_cmd = self._create_set_property_msg('_off_mask', 0x03, mask)
self._send_method(set_cmd, self._property_set) | def set_off_mask(self, mask) | Set the off mask for the current group/button. | 9.355492 | 9.209999 | 1.015797 |
set_cmd = self._create_set_property_msg('_x10_house_code', 0x04,
x10address)
self._send_method(set_cmd, self._property_set) | def set_x10_address(self, x10address) | Set the X10 address for the current group/button. | 9.334582 | 9.5771 | 0.974677 |
set_cmd = self._create_set_property_msg('_ramp_rate', 0x05,
ramp_rate)
self._send_method(set_cmd, self._property_set) | def set_ramp_rate(self, ramp_rate) | Set the X10 address for the current group/button. | 8.498556 | 8.309091 | 1.022802 |
on_cmd = self._create_set_property_msg("_on_level", 0x06,
val)
self._send_method(on_cmd, self._property_set)
self._send_method(on_cmd, self._on_message_received) | def set_on_level(self, val) | Set on level for the button/group. | 7.690411 | 8.024002 | 0.958426 |
set_cmd = self._create_set_property_msg("_led_brightness", 0x07,
brightness)
self._send_method(set_cmd, self._property_set) | def set_led_brightness(self, brightness) | Set the LED brightness for the current group/button. | 9.815191 | 10.075178 | 0.974195 |
set_cmd = self._create_set_property_msg("_non_toggle_mask", 0x08,
non_toggle_mask)
self._send_method(set_cmd, self._property_set) | def set_non_toggle_mask(self, non_toggle_mask) | Set the non_toggle_mask for the current group/button. | 7.905169 | 7.959841 | 0.993131 |
set_cmd = self._create_set_property_msg("_x10_all_bit_mask", 0x0a,
x10_all_bit_mask)
self._send_method(set_cmd, self._property_set) | def set_x10_all_bit_mask(self, x10_all_bit_mask) | Set the x10_all_bit_mask for the current group/button. | 6.00782 | 6.257798 | 0.960053 |
set_cmd = self._create_set_property_msg("_trigger_group_bit_mask",
0x0c, trigger_group_bit_mask)
self._send_method(set_cmd, self._property_set) | def set_trigger_group_bit_mask(self, trigger_group_bit_mask) | Set the trigger_group_bit_mask for the current group/button. | 6.80127 | 7.121058 | 0.955093 |
user_data = Userdata({'d1': self._group,
'd2': 0x00,
'd3': 0x00,
'd4': 0x11,
'd5': 0xff,
'd6': 0x00})
self._set_sent_property(DIMMABLE_KEYPAD_SCENE_ON_LEVEL, 0xff)
cmd = ExtendedSend(self._address,
COMMAND_EXTENDED_TRIGGER_ALL_LINK_0X30_0X00,
user_data)
cmd.set_checksum()
_LOGGER.debug('Calling scene_on and sending response to '
'_received_scene_triggered')
self._send_method(cmd, self._received_scene_triggered) | def scene_on(self) | Trigger group/scene to ON level. | 6.957991 | 6.339871 | 1.097497 |
user_data = Userdata({'d1': self._group,
'd2': 0x00,
'd3': 0x00,
'd4': 0x13,
'd5': 0x00,
'd6': 0x00})
self._set_sent_property(DIMMABLE_KEYPAD_SCENE_ON_LEVEL, 0x00)
cmd = ExtendedSend(self._address,
COMMAND_EXTENDED_TRIGGER_ALL_LINK_0X30_0X00,
user_data)
cmd.set_checksum()
self._send_method(cmd, self._received_scene_triggered) | def scene_off(self) | Trigger group/scene to OFF level. | 6.256183 | 5.708177 | 1.096004 |
self._status_received = False
user_data = Userdata({'d1': self.group,
'd2': 0x00})
cmd = ExtendedSend(self._address,
COMMAND_EXTENDED_GET_SET_0X2E_0X00,
userdata=user_data)
cmd.set_checksum()
self._send_method(cmd, self._status_message_received, True) | def extended_status_request(self) | Send status request for group/button. | 9.372133 | 7.932698 | 1.181456 |
if not self._status_received:
asyncio.ensure_future(self._confirm_status_received(),
loop=self._loop) | def _status_message_received(self, msg) | Receive confirmation that the status message is coming.
The real status message is the extended direct message. | 5.64389 | 5.707706 | 0.988819 |
self._status_received = True
self._status_retries = 0
_LOGGER.debug("Extended status message received")
if self._status_response_lock.locked():
self._status_response_lock.release()
user_data = msg.userdata
# self._update_subscribers(user_data['d8'])
self._set_status_data(user_data) | def _status_extended_message_received(self, msg) | Receeive an extended status message.
Status message received:
cmd1: 0x2e
cmd2: 0x00
flags: Direct Extended
d1: group
d2: 0x01
d3: On Mask
d4: Off Mask
d5: X10 House Code
d6: X10 Unit
d7: Ramp Rate
d8: On-Level
d9: LED Brightness
d10: Non-Toggle Mask
d11: LED Bit Mask
d12: X10 ALL Bit Mask
d13: On/Off Bit Mask
d14: Check sum | 4.99615 | 4.657268 | 1.072764 |
prop = self._sent_property.get('prop')
if prop and hasattr(self, prop):
setattr(self, prop, self._sent_property.get('val'))
self._sent_property = {} | def _property_set(self, msg) | Set command received and acknowledged. | 3.993414 | 3.842038 | 1.0394 |
self._on_mask = userdata['d3']
self._off_mask = userdata['d4']
self._x10_house_code = userdata['d5']
self._x10_unit = userdata['d6']
self._ramp_rate = userdata['d7']
self._on_level = userdata['d8']
self._led_brightness = userdata['d9']
self._non_toggle_mask = userdata['d10']
self._led_bit_mask = userdata['d11']
self._x10_all_bit_mask = userdata['d12']
self._on_off_bit_mask = userdata['d13']
self._trigger_group_bit_mask = userdata['d14'] | def _set_status_data(self, userdata) | Set status properties from userdata response.
Response values:
d3: On Mask
d4: Off Mask
d5: X10 House Code
d6: X10 Unit
d7: Ramp Rate
d8: On-Level
d9: LED Brightness
d10: Non-Toggle Mask
d11: LED Bit Mask
d12: X10 ALL Bit Mask
d13: On/Off Bit Mask | 2.916492 | 1.373415 | 2.123533 |
user_data = Userdata({'d1': self.group,
'd2': cmd,
'd3': val})
msg = ExtendedSend(self._address,
COMMAND_EXTENDED_GET_SET_0X2E_0X00,
user_data)
msg.set_checksum()
self._set_sent_property(prop, val)
return msg | def _create_set_property_msg(self, prop, cmd, val) | Create an extended message to set a property.
Create an extended message with:
cmd1: 0x2e
cmd2: 0x00
flags: Direct Extended
d1: group
d2: cmd
d3: val
d4 - d14: 0x00
Parameters:
prop: Property name to update
cmd: Command value
0x02: on mask
0x03: off mask
0x04: x10 house code
0x05: ramp rate
0x06: on level
0x07: LED brightness
0x08: Non-Toggle mask
0x09: LED bit mask (Do not use in this class. Use LED class)
0x0a: X10 All bit mask
0x0c: Trigger group bit mask
val: New property value | 7.750469 | 6.501277 | 1.192146 |
asyncio.ensure_future(self._send_led_on_off_request(group, 1),
loop=self._loop) | def on(self, group) | Turn the LED on for a group. | 7.805738 | 6.143033 | 1.270665 |
asyncio.ensure_future(self._send_led_on_off_request(group, 0),
loop=self._loop) | def off(self, group) | Turn the LED off for a group. | 7.338148 | 5.815482 | 1.26183 |
button_callbacks = self._button_observer_callbacks.get(button)
if not button_callbacks:
self._button_observer_callbacks[button] = []
_LOGGER.debug('New callback for button %d', button)
self._button_observer_callbacks[button].append(callback) | def register_led_updates(self, callback, button) | Register a callback when a specific button LED changes. | 3.295974 | 3.099775 | 1.063295 |
new_bitmask = set_bit(self._value, group, bool(val))
self._set_led_bitmask(new_bitmask) | def _set_led_value(self, group, val) | Set the LED value and confirm with a status check. | 5.640511 | 5.820225 | 0.969122 |
bitshift = group - 1
if val:
new_value = self._value | (1 << bitshift)
else:
new_value = self._value & (0xff & ~(1 << bitshift))
return new_value | def _bit_value(self, group, val) | Set the LED on/off value from the LED bitmap. | 3.536128 | 3.40596 | 1.038218 |
new_mode = None
if mode == ThermostatMode.OFF:
new_mode = COMMAND_THERMOSTAT_CONTROL_OFF_ALL_0X6B_0X09
elif mode == ThermostatMode.HEAT:
new_mode = COMMAND_THERMOSTAT_CONTROL_ON_HEAT_0X6B_0X04
elif mode == ThermostatMode.COOL:
new_mode = COMMAND_THERMOSTAT_CONTROL_ON_COOL_0X6B_0X05
elif mode == ThermostatMode.AUTO:
new_mode = COMMAND_THERMOSTAT_CONTROL_ON_AUTO_0X6B_0X06
if new_mode:
msg = ExtendedSend(address=self._address,
commandtuple=new_mode,
userdata=Userdata())
msg.set_checksum()
self._send_method(msg, self._mode_change_ack) | def set(self, mode) | Set the thermostat mode.
Mode optons:
OFF = 0x00,
HEAT = 0x01,
COOL = 0x02,
AUTO = 0x03,
FAN_AUTO = 0x04,
FAN_ALWAYS_ON = 0x8 | 2.866431 | 2.853676 | 1.004469 |
if mode == ThermostatMode.FAN_AUTO:
new_mode = COMMAND_THERMOSTAT_CONTROL_OFF_FAN_0X6B_0X08
elif mode == ThermostatMode.FAN_ALWAYS_ON:
new_mode = COMMAND_THERMOSTAT_CONTROL_ON_FAN_0X6B_0X07
if new_mode:
msg = ExtendedSend(address=self._address,
commandtuple=new_mode,
userdata=Userdata())
msg.set_checksum()
self._send_method(msg, self._mode_change_ack) | def set(self, mode) | Set the thermostat mode.
Mode optons:
OFF = 0x00,
HEAT = 0x01,
COOL = 0x02,
AUTO = 0x03,
FAN_AUTO = 0x04,
FAN_ALWAYS_ON = 0x8 | 5.46719 | 5.079021 | 1.076426 |
msg = ExtendedSend(
address=self._address,
commandtuple=COMMAND_THERMOSTAT_SET_COOL_SETPOINT_0X6C_NONE,
cmd2=int(val * 2),
userdata=Userdata())
msg.set_checksum()
self._send_method(msg, self._set_cool_point_ack) | def set(self, val) | Set the cool set point. | 12.842677 | 10.966419 | 1.171091 |
msg = ExtendedSend(
address=self._address,
commandtuple=COMMAND_THERMOSTAT_SET_HEAT_SETPOINT_0X6D_NONE,
cmd2=int(val * 2),
userdata=Userdata())
msg.set_checksum()
self._send_method(msg, self._set_heat_point_ack) | def set(self, val) | Set the heat set point. | 12.977891 | 10.880174 | 1.192802 |
_LOGGER.debug('Added new callback %s ', callback)
self._cb_new_device.append(callback) | def add_device_callback(self, callback) | Register a callback to be invoked when a new device appears. | 8.964988 | 7.923487 | 1.131445 |
address = Address(str(addr)).id
_LOGGER.debug('New override for %s %s is %s', address, key, value)
device_override = self._overrides.get(address, {})
device_override[key] = value
self._overrides[address] = device_override | def add_override(self, addr, key, value) | Register an attribute override for a device. | 4.059375 | 3.752992 | 1.081637 |
saved_device = self._saved_devices.get(Address(addr).id, {})
cat = saved_device.get('cat', cat)
subcat = saved_device.get('subcat', subcat)
product_key = saved_device.get('product_key', product_key)
device_override = self._overrides.get(Address(addr).id, {})
cat = device_override.get('cat', cat)
subcat = device_override.get('subcat', subcat)
product_key = device_override.get('firmware', product_key)
product_key = device_override.get('product_key', product_key)
return insteonplm.devices.create(plm, addr, cat, subcat, product_key) | def create_device_from_category(self, plm, addr, cat, subcat,
product_key=0x00) | Create a new device from the cat, subcat and product_key data. | 2.275922 | 2.198065 | 1.035421 |
saved = False
if self._saved_devices.get(addr, None) is not None:
saved = True
return saved | def has_saved(self, addr) | Test if device has data from the saved data file. | 4.50506 | 3.52715 | 1.277252 |
override = False
if self._overrides.get(addr, None) is not None:
override = True
return override | def has_override(self, addr) | Test if device has data from a device override setting. | 4.288199 | 3.696892 | 1.159947 |
from insteonplm.devices import ALDBStatus
for addr in self._saved_devices:
if not self._devices.get(addr):
saved_device = self._saved_devices.get(Address(addr).id, {})
cat = saved_device.get('cat')
subcat = saved_device.get('subcat')
product_key = saved_device.get('firmware')
product_key = saved_device.get('product_key', product_key)
device = self.create_device_from_category(
plm, addr, cat, subcat, product_key)
if device:
_LOGGER.debug('Device with id %s added to device list '
'from saved device data.', addr)
aldb_status = saved_device.get('aldb_status', 0)
device.aldb.status = ALDBStatus(aldb_status)
aldb = saved_device.get('aldb', {})
device.aldb.load_saved_records(aldb_status, aldb)
self[addr] = device
for addr in self._overrides:
if not self._devices.get(addr):
device_override = self._overrides.get(Address(addr).id, {})
cat = device_override.get('cat')
subcat = device_override.get('subcat')
product_key = device_override.get('firmware')
product_key = device_override.get('product_key', product_key)
device = self.create_device_from_category(
plm, addr, cat, subcat, product_key)
if device:
_LOGGER.debug('Device with id %s added to device list '
'from device override data.', addr)
self[addr] = device | def add_known_devices(self, plm) | Add devices from the saved devices or from the device overrides. | 2.26141 | 2.148735 | 1.052437 |
if self._workdir is not None:
devices = []
for addr in self._devices:
device = self._devices.get(addr)
if not device.address.is_x10:
aldb = {}
for mem in device.aldb:
rec = device.aldb[mem]
if rec:
aldbRec = {'memory': mem,
'control_flags': rec.control_flags.byte,
'group': rec.group,
'address': rec.address.id,
'data1': rec.data1,
'data2': rec.data2,
'data3': rec.data3}
aldb[mem] = aldbRec
deviceInfo = {'address': device.address.id,
'cat': device.cat,
'subcat': device.subcat,
'product_key': device.product_key,
'aldb_status': device.aldb.status.value,
'aldb': aldb}
devices.append(deviceInfo)
asyncio.ensure_future(self._write_saved_device_info(devices),
loop=self._loop) | def save_device_info(self) | Save all device information to the device info file. | 3.177065 | 3.075604 | 1.032989 |
addr = kwarg.get('address')
_LOGGER.debug('Found saved device with address %s', addr)
self._saved_devices[addr] = kwarg | def _add_saved_device_info(self, **kwarg) | Register device info from the saved data file. | 4.720306 | 5.01743 | 0.940782 |
_LOGGER.debug("Loading saved device info.")
deviceinfo = []
if self._workdir:
_LOGGER.debug("Really Loading saved device info.")
try:
device_file = '{}/{}'.format(self._workdir, DEVICE_INFO_FILE)
with open(device_file, 'r') as infile:
try:
deviceinfo = json.load(infile)
_LOGGER.debug("Saved device file loaded")
except json.decoder.JSONDecodeError:
_LOGGER.debug("Loading saved device file failed")
except FileNotFoundError:
_LOGGER.debug("Saved device file not found")
for device in deviceinfo:
self._add_saved_device_info(**device) | async def load_saved_device_info(self) | Load device information from the device info file. | 2.86113 | 2.749884 | 1.040455 |
house_byte = 0
unit_byte = 0
if isinstance(housecode, str):
house_byte = insteonplm.utils.housecode_to_byte(housecode) << 4
unit_byte = insteonplm.utils.unitcode_to_byte(unitcode)
elif isinstance(housecode, int) and housecode < 16:
house_byte = housecode << 4
unit_byte = unitcode
else:
house_byte = housecode
unit_byte = unitcode
return X10Received(house_byte + unit_byte, 0x00) | def unit_code_msg(housecode, unitcode) | Create an X10 message to send the house code and unit code. | 2.634388 | 2.337944 | 1.126797 |
house_byte = 0
if isinstance(housecode, str):
house_byte = insteonplm.utils.housecode_to_byte(housecode) << 4
elif isinstance(housecode, int) and housecode < 16:
house_byte = housecode << 4
else:
house_byte = housecode
return X10Received(house_byte + command, 0x80) | def command_msg(housecode, command) | Create an X10 message to send the house code and a command code. | 3.740087 | 3.408495 | 1.097284 |
protocol = protocol_factory()
transport = HttpTransport(loop, protocol, host, port, auth)
_LOGGER.debug("create_http_connection Finished creating connection")
return (transport, protocol) | async def create_http_connection(loop, protocol_factory, host, port=25105,
auth=None) | Create an HTTP session used to connect to the Insteon Hub. | 5.100179 | 4.888074 | 1.043392 |
_LOGGER.debug("Starting Modified Connection.create")
conn = cls(device=device, host=host, username=username,
password=password, port=port, hub_version=hub_version,
loop=loop, retry_interval=1, auto_reconnect=auto_reconnect)
def connection_lost():
if conn.auto_reconnect and not conn.closing:
_LOGGER.debug("Reconnecting to transport")
asyncio.ensure_future(conn.reconnect(), loop=conn.loop)
protocol_class = PLM
if conn.host and conn.hub_version == 2:
protocol_class = Hub
conn.protocol = protocol_class(
connection_lost_callback=connection_lost,
loop=conn.loop,
workdir=workdir,
poll_devices=poll_devices,
load_aldb=load_aldb)
await conn.reconnect()
_LOGGER.debug("Ending Connection.create")
return conn | async def create(cls, device='/dev/ttyUSB0', host=None,
username=None, password=None, port=25010, hub_version=2,
auto_reconnect=True, loop=None, workdir=None,
poll_devices=True, load_aldb=True) | Create a connection to a specific device.
Here is where we supply the device and callback callables we
expect for this PLM class object.
:param device:
Unix device where the PLM is attached
:param address:
IP Address of the Hub
:param username:
User name for connecting to the Hub
:param password:
Password for connecting to the Hub
:param auto_reconnect:
Should the Connection try to automatically reconnect if needed?
:param loop:
asyncio.loop for async operation
:param load_aldb:
Should the ALDB be loaded on connect
:type device:
str
:type auto_reconnect:
boolean
:type loop:
asyncio.loop
:type update_callback:
callable | 3.030376 | 3.292783 | 0.920308 |
_LOGGER.debug('starting Connection.reconnect')
await self._connect()
while self._closed:
await self._retry_connection()
_LOGGER.debug('ending Connection.reconnect') | async def reconnect(self) | Reconnect to the modem. | 7.088617 | 6.480552 | 1.093829 |
_LOGGER.info('Closing connection to Insteon Modem')
self._closing = True
self._auto_reconnect = False
await self.protocol.close()
if self.protocol.transport:
self.protocol.transport.close()
await asyncio.sleep(0, loop=self._loop)
_LOGGER.info('Insteon Modem connection closed') | async def close(self, event) | Close the PLM device connection and don't try to reconnect. | 3.957745 | 3.603779 | 1.098221 |
attrs = vars(self)
return ', '.join("%s: %s" % item for item in attrs.items()) | def dump_conndata(self) | Developer tool for debugging forensics. | 4.320889 | 3.625148 | 1.191921 |
msg = X10Send.unit_code_msg(self.address.x10_housecode,
self.address.x10_unitcode)
self._send_method(msg)
msg = X10Send.command_msg(self.address.x10_housecode,
X10_COMMAND_ON)
self._send_method(msg, False)
self._update_subscribers(0xff) | def on(self) | Send the On command to an X10 device. | 5.587892 | 4.907734 | 1.138589 |
msg = X10Send.unit_code_msg(self.address.x10_housecode,
self.address.x10_unitcode)
self._send_method(msg)
msg = X10Send.command_msg(self.address.x10_housecode,
X10_COMMAND_OFF)
self._send_method(msg, False)
self._update_subscribers(0x00) | def off(self) | Send the Off command to an X10 device. | 5.299046 | 4.80547 | 1.102711 |
if val == 0:
self.off()
elif val == 255:
self.on()
else:
setlevel = 255
if val < 1:
setlevel = val * 255
elif val <= 0xff:
setlevel = val
change = setlevel - self._value
increment = 255 / self._steps
steps = round(abs(change) / increment)
print('Steps: ', steps)
if change > 0:
method = self.brighten
self._value += round(steps * increment)
self._value = min(255, self._value)
else:
method = self.dim
self._value -= round(steps * increment)
self._value = max(0, self._value)
# pylint: disable=unused-variable
for step in range(0, steps):
method(True)
self._update_subscribers(self._value) | def set_level(self, val) | Set the device ON LEVEL. | 3.01576 | 2.945666 | 1.023795 |
msg = X10Send.unit_code_msg(self.address.x10_housecode,
self.address.x10_unitcode)
self._send_method(msg)
msg = X10Send.command_msg(self.address.x10_housecode,
X10_COMMAND_BRIGHT)
self._send_method(msg, False)
if not defer_update:
self._update_subscribers(self._value + 255 / self._steps) | def brighten(self, defer_update=False) | Brighten the device one step. | 5.660254 | 5.384629 | 1.051187 |
msg = X10Send.unit_code_msg(self.address.x10_housecode,
self.address.x10_unitcode)
self._send_method(msg)
msg = X10Send.command_msg(self.address.x10_housecode,
X10_COMMAND_DIM)
self._send_method(msg, False)
if not defer_update:
self._update_subscribers(self._value - 255 / self._steps) | def dim(self, defer_update=False) | Dim the device one step. | 5.731973 | 5.330355 | 1.075345 |
matches = False
if hasattr(other, 'addr'):
if self.addr is None or other.addr is None:
matches = True
else:
matches = self.addr == other.addr
return matches | def matches_pattern(self, other) | Test Address object matches the pattern of another object. | 3.014072 | 2.520396 | 1.195872 |
normalize = None
if isinstance(addr, Address):
normalize = addr.addr
self._is_x10 = addr.is_x10
elif isinstance(addr, bytearray):
normalize = binascii.unhexlify(binascii.hexlify(addr).decode())
elif isinstance(addr, bytes):
normalize = addr
elif isinstance(addr, str):
addr = addr.replace('.', '')
addr = addr[0:6]
if addr[0:3].lower() == 'x10':
x10_addr = Address.x10(addr[3:4], int(addr[4:6]))
normalize = x10_addr.addr
self._is_x10 = True
else:
normalize = binascii.unhexlify(addr.lower())
elif addr is None:
normalize = None
else:
_LOGGER.warning('Address class init with unknown type %s: %r',
type(addr), addr)
return normalize | def _normalize(self, addr) | Take any format of address and turn it into a hex string. | 2.88432 | 2.811751 | 1.025809 |
addrstr = '00.00.00'
if self.addr:
if self._is_x10:
housecode_byte = self.addr[1]
housecode = insteonplm.utils.byte_to_housecode(housecode_byte)
unitcode_byte = self.addr[2]
unitcode = insteonplm.utils.byte_to_unitcode(unitcode_byte)
addrstr = 'X10.{}.{:02d}'.format(housecode.upper(), unitcode)
else:
addrstr = '{}.{}.{}'.format(self.hex[0:2],
self.hex[2:4],
self.hex[4:6]).upper()
return addrstr | def human(self) | Emit the address in human-readible format (AA.BB.CC). | 2.977587 | 2.698635 | 1.103368 |
addrstr = '000000'
if self.addr is not None:
addrstr = binascii.hexlify(self.addr).decode()
return addrstr | def hex(self) | Emit the address in bare hex format (aabbcc). | 4.405706 | 3.456048 | 1.274781 |
addrbyte = b'\x00\x00\x00'
if self.addr is not None:
addrbyte = self.addr
return addrbyte | def bytes(self) | Emit the address in bytes format. | 4.665098 | 3.513608 | 1.327723 |
dev_id = ''
if self._is_x10:
dev_id = 'x10{}{:02d}'.format(self.x10_housecode,
self.x10_unitcode)
else:
dev_id = self.hex
return dev_id | def id(self) | Return the ID of the device address. | 4.693313 | 3.823416 | 1.227518 |
housecode = None
if self.is_x10:
housecode = insteonplm.utils.byte_to_housecode(self.addr[1])
return housecode | def x10_housecode(self) | Emit the X10 house code. | 4.892227 | 4.585035 | 1.066999 |
unitcode = None
if self.is_x10:
unitcode = insteonplm.utils.byte_to_unitcode(self.addr[2])
return unitcode | def x10_unitcode(self) | Emit the X10 unit code. | 5.589187 | 5.059136 | 1.104771 |
if housecode.lower() in ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h',
'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p']:
byte_housecode = insteonplm.utils.housecode_to_byte(housecode)
else:
if isinstance(housecode, str):
_LOGGER.error('X10 house code error: %s', housecode)
else:
_LOGGER.error('X10 house code is not a string')
raise ValueError
# 20, 21 and 22 for All Units Off, All Lights On and All Lights Off
# 'fake' units
if unitcode in range(1, 17) or unitcode in range(20, 23):
byte_unitcode = insteonplm.utils.unitcode_to_byte(unitcode)
else:
if isinstance(unitcode, int):
_LOGGER.error('X10 unit code error: %d', unitcode)
else:
_LOGGER.error('X10 unit code is not an integer 1 - 16')
raise ValueError
addr = Address(bytearray([0x00, byte_housecode, byte_unitcode]))
addr.is_x10 = True
return addr | def x10(cls, housecode, unitcode) | Create an X10 device address. | 2.629957 | 2.492489 | 1.055153 |
return ManageAllLinkRecord(rawmessage[2:3],
rawmessage[3:4],
rawmessage[4:7],
rawmessage[7:8],
rawmessage[8:9],
rawmessage[9:10],
rawmessage[10:11]) | def from_raw_message(cls, rawmessage) | Create message from raw byte stream. | 3.394128 | 3.216684 | 1.055164 |
assert field_type in FIELD_TYPES
def strf(dt):
return '%04d%02d%02d%02d%02d%02d' % (
dt.year, dt.month, dt.day, dt.hour, dt.minute, dt.second)
if field_type == 'boolean':
assert isinstance(term, bool)
if term:
value = 't'
else:
value = 'f'
elif field_type == 'integer':
value = INTEGER_FORMAT % term
elif field_type == 'float':
value = xapian.sortable_serialise(term)
elif field_type == 'date' or field_type == 'datetime':
if field_type == 'date':
# http://stackoverflow.com/a/1937636/931303 and comments
term = datetime.datetime.combine(term, datetime.time())
value = strf(term)
else: # field_type == 'text'
value = _to_xapian_term(term)
return value | def _term_to_xapian_value(term, field_type) | Converts a term to a serialized
Xapian value based on the field_type. | 2.977895 | 2.945089 | 1.011139 |
assert field_type in FIELD_TYPES
if field_type == 'boolean':
if value == 't':
return True
elif value == 'f':
return False
else:
InvalidIndexError('Field type "%d" does not accept value "%s"' % (field_type, value))
elif field_type == 'integer':
return int(value)
elif field_type == 'float':
return xapian.sortable_unserialise(value)
elif field_type == 'date' or field_type == 'datetime':
datetime_value = datetime.datetime.strptime(value, DATETIME_FORMAT)
if field_type == 'datetime':
return datetime_value
else:
return datetime_value.date()
else: # field_type == 'text'
return value | def _from_xapian_value(value, field_type) | Converts a serialized Xapian value
to Python equivalent based on the field_type.
Doesn't accept multivalued fields. | 2.540715 | 2.577817 | 0.985607 |
fields = connections[self.connection_alias].get_unified_index().all_searchfields()
if self._fields != fields:
self._fields = fields
self._content_field_name, self._schema = self.build_schema(self._fields) | def _update_cache(self) | To avoid build_schema every time, we cache
some values: they only change when a SearchIndex
changes, which typically restarts the Python. | 6.919192 | 4.281548 | 1.616049 |
database = self._database(writable=True)
database.delete_document(TERM_PREFIXES[ID] + get_identifier(obj))
database.close() | def remove(self, obj, commit=True) | Remove indexes for `obj` from the database.
We delete all instances of `Q<app_name>.<model_name>.<pk>` which
should be unique to this object.
Optional arguments:
`commit` -- ignored | 20.753132 | 31.16362 | 0.665941 |
if not models:
# Because there does not appear to be a "clear all" method,
# it's much quicker to remove the contents of the `self.path`
# folder than it is to remove each document one at a time.
if os.path.exists(self.path):
shutil.rmtree(self.path)
else:
database = self._database(writable=True)
for model in models:
database.delete_document(TERM_PREFIXES[DJANGO_CT] + get_model_ct(model))
database.close() | def clear(self, models=(), commit=True) | Clear all instances of `models` from the database or all models, if
not specified.
Optional Arguments:
`models` -- Models to clear from the database (default = [])
If `models` is empty, an empty query is executed which matches all
documents in the database. Afterwards, each match is deleted.
Otherwise, for each model, a `delete_document` call is issued with
the term `XCONTENTTYPE<app_name>.<model_name>`. This will delete
all documents with the specified model type. | 6.52061 | 5.889588 | 1.107142 |
registered_models_ct = self.build_models_list()
if registered_models_ct:
restrictions = [xapian.Query('%s%s' % (TERM_PREFIXES[DJANGO_CT], model_ct))
for model_ct in registered_models_ct]
limit_query = xapian.Query(xapian.Query.OP_OR, restrictions)
query = xapian.Query(xapian.Query.OP_AND, query, limit_query)
return query | def _build_models_query(self, query) | Builds a query from `query` that filters to documents only from registered models. | 4.860382 | 4.480271 | 1.084841 |
if field_names:
for field_name in field_names:
try:
self.column[field_name]
except KeyError:
raise InvalidIndexError('Trying to use non indexed field "%s"' % field_name) | def _check_field_names(self, field_names) | Raises InvalidIndexError if any of a field_name in field_names is
not indexed. | 4.393193 | 2.922874 | 1.503039 |
database = self._database()
if result_class is None:
result_class = SearchResult
query = xapian.Query(TERM_PREFIXES[ID] + get_identifier(model_instance))
enquire = xapian.Enquire(database)
enquire.set_query(query)
rset = xapian.RSet()
if not end_offset:
end_offset = database.get_doccount()
match = None
for match in self._get_enquire_mset(database, enquire, 0, end_offset):
rset.add_document(match.docid)
if match is None:
if not self.silently_fail:
raise InvalidIndexError('Instance %s with id "%d" not indexed' %
(get_identifier(model_instance), model_instance.id))
else:
return {'results': [],
'hits': 0}
query = xapian.Query(
xapian.Query.OP_ELITE_SET,
[expand.term for expand in enquire.get_eset(match.document.termlist_count(), rset, XHExpandDecider())],
match.document.termlist_count()
)
query = xapian.Query(
xapian.Query.OP_AND_NOT, [query, TERM_PREFIXES[ID] + get_identifier(model_instance)]
)
if limit_to_registered_models:
query = self._build_models_query(query)
if additional_query:
query = xapian.Query(
xapian.Query.OP_AND, query, additional_query
)
enquire.set_query(query)
results = []
matches = self._get_enquire_mset(database, enquire, start_offset, end_offset)
for match in matches:
app_label, model_name, pk, model_data = pickle.loads(self._get_document_data(database, match.document))
results.append(
result_class(app_label, model_name, pk, match.percent, **model_data)
)
return {
'results': results,
'hits': self._get_hit_count(database, enquire),
'facets': {
'fields': {},
'dates': {},
'queries': {},
},
'spelling_suggestion': None,
} | def more_like_this(self, model_instance, additional_query=None,
start_offset=0, end_offset=None,
limit_to_registered_models=True, result_class=None, **kwargs) | Given a model instance, returns a result set of similar documents.
Required arguments:
`model_instance` -- The model instance to use as a basis for
retrieving similar documents.
Optional arguments:
`additional_query` -- An additional query to narrow results
`start_offset` -- The starting offset (default=0)
`end_offset` -- The ending offset (default=None), if None, then all documents
`limit_to_registered_models` -- Limit returned results to models registered in the search (default = True)
Returns:
A dictionary with the following keys:
`results` -- A list of `SearchResult`
`hits` -- The total available results
Opens a database connection, then builds a simple query using the
`model_instance` to build the unique identifier.
For each document retrieved(should always be one), adds an entry into
an RSet (relevance set) with the document id, then, uses the RSet
to query for an ESet (A set of terms that can be used to suggest
expansions to the original query), omitting any document that was in
the original query.
Finally, processes the resulting matches and returns. | 3.517907 | 3.279053 | 1.072842 |
if query_string == '*':
return xapian.Query('') # Match everything
elif query_string == '':
return xapian.Query() # Match nothing
qp = xapian.QueryParser()
qp.set_database(self._database())
qp.set_stemmer(xapian.Stem(self.language))
qp.set_stemming_strategy(self.stemming_strategy)
qp.set_default_op(XAPIAN_OPTS[DEFAULT_OPERATOR])
qp.add_boolean_prefix(DJANGO_CT, TERM_PREFIXES[DJANGO_CT])
for field_dict in self.schema:
# since 'django_ct' has a boolean_prefix,
# we ignore it here.
if field_dict['field_name'] == DJANGO_CT:
continue
qp.add_prefix(
field_dict['field_name'],
TERM_PREFIXES['field'] + field_dict['field_name'].upper()
)
vrp = XHValueRangeProcessor(self)
qp.add_valuerangeprocessor(vrp)
return qp.parse_query(query_string, self.flags) | def parse_query(self, query_string) | Given a `query_string`, will attempt to return a xapian.Query
Required arguments:
``query_string`` -- A query string to parse
Returns a xapian.Query | 3.937398 | 4.066567 | 0.968236 |
content_field_name = ''
schema_fields = [
{'field_name': ID,
'type': 'text',
'multi_valued': 'false',
'column': 0},
{'field_name': DJANGO_ID,
'type': 'integer',
'multi_valued': 'false',
'column': 1},
{'field_name': DJANGO_CT,
'type': 'text',
'multi_valued': 'false',
'column': 2},
]
self._columns[ID] = 0
self._columns[DJANGO_ID] = 1
self._columns[DJANGO_CT] = 2
column = len(schema_fields)
for field_name, field_class in sorted(list(fields.items()), key=lambda n: n[0]):
if field_class.document is True:
content_field_name = field_class.index_fieldname
if field_class.indexed is True:
field_data = {
'field_name': field_class.index_fieldname,
'type': 'text',
'multi_valued': 'false',
'column': column,
}
if field_class.field_type == 'date':
field_data['type'] = 'date'
elif field_class.field_type == 'datetime':
field_data['type'] = 'datetime'
elif field_class.field_type == 'integer':
field_data['type'] = 'integer'
elif field_class.field_type == 'float':
field_data['type'] = 'float'
elif field_class.field_type == 'boolean':
field_data['type'] = 'boolean'
elif field_class.field_type == 'ngram':
field_data['type'] = 'ngram'
elif field_class.field_type == 'edge_ngram':
field_data['type'] = 'edge_ngram'
if field_class.is_multivalued:
field_data['multi_valued'] = 'true'
schema_fields.append(field_data)
self._columns[field_data['field_name']] = column
column += 1
return content_field_name, schema_fields | def build_schema(self, fields) | Build the schema from fields.
:param fields: A list of fields in the index
:returns: list of dictionaries
Each dictionary has the keys
field_name: The name of the field index
type: what type of value it is
'multi_valued': if it allows more than one value
'column': a number identifying it
'type': the type of the field
'multi_valued': 'false', 'column': 0} | 1.876456 | 1.746352 | 1.074501 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.