INSTRUCTION stringlengths 1 8.43k | RESPONSE stringlengths 75 104k |
|---|---|
Updates the status of this invoice based upon the total payments. | def update_status(self):
''' Updates the status of this invoice based upon the total
payments.'''
old_status = self.invoice.status
total_paid = self.invoice.total_payments()
num_payments = commerce.PaymentBase.objects.filter(
invoice=self.invoice,
).count()
remainder = self.invoice.value - total_paid
if old_status == commerce.Invoice.STATUS_UNPAID:
# Invoice had an amount owing
if remainder <= 0:
# Invoice no longer has amount owing
self._mark_paid()
elif total_paid == 0 and num_payments > 0:
# Invoice has multiple payments totalling zero
self._mark_void()
elif old_status == commerce.Invoice.STATUS_PAID:
if remainder > 0:
# Invoice went from having a remainder of zero or less
# to having a positive remainder -- must be a refund
self._mark_refunded()
elif old_status == commerce.Invoice.STATUS_REFUNDED:
# Should not ever change from here
pass
elif old_status == commerce.Invoice.STATUS_VOID:
# Should not ever change from here
pass
# Generate credit notes from residual payments
residual = 0
if self.invoice.is_paid:
if remainder < 0:
residual = 0 - remainder
elif self.invoice.is_void or self.invoice.is_refunded:
residual = total_paid
if residual != 0:
CreditNoteController.generate_from_invoice(self.invoice, residual)
self.email_on_invoice_change(
self.invoice,
old_status,
self.invoice.status,
) |
Marks the invoice as paid and updates the attached cart if necessary. | def _mark_paid(self):
''' Marks the invoice as paid, and updates the attached cart if
necessary. '''
cart = self.invoice.cart
if cart:
cart.status = commerce.Cart.STATUS_PAID
cart.save()
self.invoice.status = commerce.Invoice.STATUS_PAID
self.invoice.save() |
Marks the invoice as refunded and updates the attached cart if necessary. | def _mark_refunded(self):
''' Marks the invoice as refunded, and updates the attached cart if
necessary. '''
self._release_cart()
self.invoice.status = commerce.Invoice.STATUS_REFUNDED
self.invoice.save() |
Marks the invoice as refunded and updates the attached cart if necessary. | def _mark_void(self):
''' Marks the invoice as refunded, and updates the attached cart if
necessary. '''
self.invoice.status = commerce.Invoice.STATUS_VOID
self.invoice.save() |
Returns true if there is no cart or if the revision of this invoice matches the current revision of the cart. | def _invoice_matches_cart(self):
''' Returns true if there is no cart, or if the revision of this
invoice matches the current revision of the cart. '''
self._refresh()
cart = self.invoice.cart
if not cart:
return True
return cart.revision == self.invoice.cart_revision |
Voids this invoice if the attached cart is no longer valid because the cart revision has changed or the reservations have expired. | def update_validity(self):
''' Voids this invoice if the attached cart is no longer valid because
the cart revision has changed, or the reservations have expired. '''
is_valid = self._invoice_matches_cart()
cart = self.invoice.cart
if self.invoice.is_unpaid and is_valid and cart:
try:
CartController(cart).validate_cart()
except ValidationError:
is_valid = False
if not is_valid:
if self.invoice.total_payments() > 0:
# Free up the payments made to this invoice
self.refund()
else:
self.void() |
Voids the invoice if it is valid to do so. | def void(self):
''' Voids the invoice if it is valid to do so. '''
if self.invoice.total_payments() > 0:
raise ValidationError("Invoices with payments must be refunded.")
elif self.invoice.is_refunded:
raise ValidationError("Refunded invoices may not be voided.")
if self.invoice.is_paid:
self._release_cart()
self._mark_void() |
Refunds the invoice by generating a CreditNote for the value of all of the payments against the cart. | def refund(self):
''' Refunds the invoice by generating a CreditNote for the value of
all of the payments against the cart.
The invoice is marked as refunded, and the underlying cart is marked
as released.
'''
if self.invoice.is_void:
raise ValidationError("Void invoices cannot be refunded")
# Raises a credit note fot the value of the invoice.
amount = self.invoice.total_payments()
if amount == 0:
self.void()
return
CreditNoteController.generate_from_invoice(self.invoice, amount)
self.update_status() |
Sends out an e - mail notifying the user about something to do with that invoice. | def email(cls, invoice, kind):
''' Sends out an e-mail notifying the user about something to do
with that invoice. '''
context = {
"invoice": invoice,
}
send_email([invoice.user.email], kind, context=context) |
Sends out all of the necessary notifications that the status of the invoice has changed to: | def email_on_invoice_change(cls, invoice, old_status, new_status):
''' Sends out all of the necessary notifications that the status of the
invoice has changed to:
- Invoice is now paid
- Invoice is now refunded
'''
# The statuses that we don't care about.
silent_status = [
commerce.Invoice.STATUS_VOID,
commerce.Invoice.STATUS_UNPAID,
]
if old_status == new_status:
return
if False and new_status in silent_status:
pass
cls.email(invoice, "invoice_updated") |
Update the object with new data. | def update(self, data):
"""Update the object with new data."""
fields = [
'id',
'status',
'type',
'persistence',
'date_start',
'date_finish',
'date_created',
'date_modified',
'checksum',
'processor_name',
'input',
'input_schema',
'output',
'output_schema',
'static',
'static_schema',
'var',
'var_template',
]
self.annotation = {}
for f in fields:
setattr(self, f, data[f])
self.name = data['static']['name'] if 'name' in data['static'] else ''
self.annotation.update(self._flatten_field(data['input'], data['input_schema'], 'input'))
self.annotation.update(self._flatten_field(data['output'], data['output_schema'], 'output'))
self.annotation.update(self._flatten_field(data['static'], data['static_schema'], 'static'))
self.annotation.update(self._flatten_field(data['var'], data['var_template'], 'var')) |
Reduce dicts of dicts to dot separated keys. | def _flatten_field(self, field, schema, path):
"""Reduce dicts of dicts to dot separated keys."""
flat = {}
for field_schema, fields, path in iterate_schema(field, schema, path):
name = field_schema['name']
typ = field_schema['type']
label = field_schema['label']
value = fields[name] if name in fields else None
flat[path] = {'name': name, 'value': value, 'type': typ, 'label': label}
return flat |
Print annotation key: value pairs to standard output. | def print_annotation(self):
"""Print annotation "key: value" pairs to standard output."""
for path, ann in self.annotation.items():
print("{}: {}".format(path, ann['value'])) |
Print file fields to standard output. | def print_downloads(self):
"""Print file fields to standard output."""
for path, ann in self.annotation.items():
if path.startswith('output') and ann['type'] == 'basic:file:':
print("{}: {}".format(path, ann['value']['file'])) |
Download a file. | def download(self, field):
"""Download a file.
:param field: file field to download
:type field: string
:rtype: a file handle
"""
if not field.startswith('output'):
raise ValueError("Only processor results (output.* fields) can be downloaded")
if field not in self.annotation:
raise ValueError("Download field {} does not exist".format(field))
ann = self.annotation[field]
if ann['type'] != 'basic:file:':
raise ValueError("Only basic:file: field can be downloaded")
return next(self.gencloud.download([self.id], field)) |
Add arguments to the parser for collection in app. args. | def add_arguments(cls, parser):
"""Add arguments to the parser for collection in app.args.
Args:
parser:
`argparse.ArgumentParser`. Parser.
Arguments added here are server on
self.args.
"""
parser.add_argument(
'-t', '--title',
action='store',
nargs='?',
const='',
dest='title',
help="[issue] task/issue title.",
)
parser.add_argument(
'-b', '--body',
action='store',
nargs='?',
const='',
dest='body',
help="[issue] task/issue body.",
)
pass |
Return a list: obj: GenProject projects. | def projects(self):
"""Return a list :obj:`GenProject` projects.
:rtype: list of :obj:`GenProject` projects
"""
if not ('projects' in self.cache and self.cache['projects']):
self.cache['projects'] = {c['id']: GenProject(c, self) for c in self.api.case.get()['objects']}
return self.cache['projects'] |
Return a list of Data objects for given project. | def project_data(self, project):
"""Return a list of Data objects for given project.
:param project: ObjectId or slug of Genesis project
:type project: string
:rtype: list of Data objects
"""
projobjects = self.cache['project_objects']
objects = self.cache['objects']
project_id = str(project)
if not re.match('^[0-9a-fA-F]{24}$', project_id):
# project_id is a slug
projects = self.api.case.get(url_slug=project_id)['objects']
if len(projects) != 1:
raise ValueError(msg='Attribute project not a slug or ObjectId: {}'.format(project_id))
project_id = str(projects[0]['id'])
if project_id not in projobjects:
projobjects[project_id] = []
data = self.api.data.get(case_ids__contains=project_id)['objects']
for d in data:
_id = d['id']
if _id in objects:
# Update existing object
objects[_id].update(d)
else:
# Insert new object
objects[_id] = GenData(d, self)
projobjects[project_id].append(objects[_id])
# Hydrate reference fields
for d in projobjects[project_id]:
while True:
ref_annotation = {}
remove_annotation = []
for path, ann in d.annotation.items():
if ann['type'].startswith('data:'):
# Referenced data object found
# Copy annotation
if ann['value'] in self.cache['objects']:
annotation = self.cache['objects'][ann['value']].annotation
ref_annotation.update({path + '.' + k: v for k, v in annotation.items()})
remove_annotation.append(path)
if ref_annotation:
d.annotation.update(ref_annotation)
for path in remove_annotation:
del d.annotation[path]
else:
break
return projobjects[project_id] |
Query for Data object annotation. | def data(self, **query):
"""Query for Data object annotation."""
objects = self.cache['objects']
data = self.api.data.get(**query)['objects']
data_objects = []
for d in data:
_id = d['id']
if _id in objects:
# Update existing object
objects[_id].update(d)
else:
# Insert new object
objects[_id] = GenData(d, self)
data_objects.append(objects[_id])
# Hydrate reference fields
for d in data_objects:
count += 1
while True:
ref_annotation = {}
remove_annotation = []
for path, ann in d.annotation.items():
if ann['type'].startswith('data:'):
# Referenced data object found
# Copy annotation
_id = ann['value']
if _id not in objects:
try:
d_tmp = self.api.data(_id).get()
except slumber.exceptions.HttpClientError as ex:
if ex.response.status_code == 404:
continue
else:
raise ex
objects[_id] = GenData(d_tmp, self)
annotation = objects[_id].annotation
ref_annotation.update({path + '.' + k: v for k, v in annotation.items()})
remove_annotation.append(path)
if ref_annotation:
d.annotation.update(ref_annotation)
for path in remove_annotation:
del d.annotation[path]
else:
break
return data_objects |
Return a list of Processor objects. | def processors(self, processor_name=None):
"""Return a list of Processor objects.
:param project_id: ObjectId of Genesis project
:type project_id: string
:rtype: list of Processor objects
"""
if processor_name:
return self.api.processor.get(name=processor_name)['objects']
else:
return self.api.processor.get()['objects'] |
Print processor input fields and types. | def print_processor_inputs(self, processor_name):
"""Print processor input fields and types.
:param processor_name: Processor object name
:type processor_name: string
"""
p = self.processors(processor_name=processor_name)
if len(p) == 1:
p = p[0]
else:
Exception('Invalid processor name')
for field_schema, _, _ in iterate_schema({}, p['input_schema'], 'input'):
name = field_schema['name']
typ = field_schema['type']
# value = fields[name] if name in fields else None
print("{} -> {}".format(name, typ)) |
POST JSON data object to server | def rundata(self, strjson):
"""POST JSON data object to server"""
d = json.loads(strjson)
return self.api.data.post(d) |
Create an object of resource: | def create(self, data, resource='data'):
"""Create an object of resource:
* data
* project
* processor
* trigger
* template
:param data: Object values
:type data: dict
:param resource: Resource name
:type resource: string
"""
if isinstance(data, dict):
data = json.dumps(data)
if not isinstance(data, str):
raise ValueError(mgs='data must be dict, str or unicode')
resource = resource.lower()
if resource not in ('data', 'project', 'processor', 'trigger', 'template'):
raise ValueError(mgs='resource must be data, project, processor, trigger or template')
if resource == 'project':
resource = 'case'
url = urlparse.urljoin(self.url, '/api/v1/{}/'.format(resource))
return requests.post(url,
data=data,
auth=self.auth,
headers={
'cache-control': 'no-cache',
'content-type': 'application/json',
'accept': 'application/json, text/plain, */*',
'referer': self.url,
}) |
Upload files and data objects. | def upload(self, project_id, processor_name, **fields):
"""Upload files and data objects.
:param project_id: ObjectId of Genesis project
:type project_id: string
:param processor_name: Processor object name
:type processor_name: string
:param fields: Processor field-value pairs
:type fields: args
:rtype: HTTP Response object
"""
p = self.processors(processor_name=processor_name)
if len(p) == 1:
p = p[0]
else:
Exception('Invalid processor name {}'.format(processor_name))
for field_name, field_val in fields.items():
if field_name not in p['input_schema']:
Exception("Field {} not in processor {} inputs".format(field_name, p['name']))
if find_field(p['input_schema'], field_name)['type'].startswith('basic:file:'):
if not os.path.isfile(field_val):
Exception("File {} not found".format(field_val))
inputs = {}
for field_name, field_val in fields.items():
if find_field(p['input_schema'], field_name)['type'].startswith('basic:file:'):
file_temp = self._upload_file(field_val)
if not file_temp:
Exception("Upload failed for {}".format(field_val))
inputs[field_name] = {
'file': field_val,
'file_temp': file_temp
}
else:
inputs[field_name] = field_val
d = {
'status': 'uploading',
'case_ids': [project_id],
'processor_name': processor_name,
'input': inputs,
}
return self.create(d) |
Upload a single file on the platform. | def _upload_file(self, fn):
"""Upload a single file on the platform.
File is uploaded in chunks of 1,024 bytes.
:param fn: File path
:type fn: string
"""
size = os.path.getsize(fn)
counter = 0
base_name = os.path.basename(fn)
session_id = str(uuid.uuid4())
with open(fn, 'rb') as f:
while True:
response = None
chunk = f.read(CHUNK_SIZE)
if not chunk:
break
for i in range(5):
content_range = 'bytes {}-{}/{}'.format(counter * CHUNK_SIZE,
counter * CHUNK_SIZE + len(chunk) - 1, size)
if i > 0 and response is not None:
print("Chunk upload failed (error {}): repeating {}"
.format(response.status_code, content_range))
response = requests.post(urlparse.urljoin(self.url, 'upload/'),
auth=self.auth,
data=chunk,
headers={
'Content-Disposition': 'attachment; filename="{}"'.format(base_name),
'Content-Length': size,
'Content-Range': content_range,
'Content-Type': 'application/octet-stream',
'Session-Id': session_id})
if response.status_code in [200, 201]:
break
else:
# Upload of a chunk failed (5 retries)
return None
progress = 100. * (counter * CHUNK_SIZE + len(chunk)) / size
sys.stdout.write("\r{:.0f} % Uploading {}".format(progress, fn))
sys.stdout.flush()
counter += 1
print()
return session_id |
Download files of data objects. | def download(self, data_objects, field):
"""Download files of data objects.
:param data_objects: Data object ids
:type data_objects: list of UUID strings
:param field: Download field name
:type field: string
:rtype: generator of requests.Response objects
"""
if not field.startswith('output'):
raise ValueError("Only processor results (output.* fields) can be downloaded")
for o in data_objects:
o = str(o)
if re.match('^[0-9a-fA-F]{24}$', o) is None:
raise ValueError("Invalid object id {}".format(o))
if o not in self.cache['objects']:
self.cache['objects'][o] = GenData(self.api.data(o).get(), self)
if field not in self.cache['objects'][o].annotation:
raise ValueError("Download field {} does not exist".format(field))
ann = self.cache['objects'][o].annotation[field]
if ann['type'] != 'basic:file:':
raise ValueError("Only basic:file: field can be downloaded")
for o in data_objects:
ann = self.cache['objects'][o].annotation[field]
url = urlparse.urljoin(self.url, 'data/{}/{}'.format(o, ann['value']['file']))
yield requests.get(url, stream=True, auth=self.auth) |
Gets the subclasses of a class. | def get_subclasses(c):
"""Gets the subclasses of a class."""
subclasses = c.__subclasses__()
for d in list(subclasses):
subclasses.extend(get_subclasses(d))
return subclasses |
Add arguments to the parser for collection in app. args. | def add_arguments(cls, parser):
"""Add arguments to the parser for collection in app.args.
Args:
parser:
`argparse.ArgumentParser`. Parser.
Arguments added here are server on
self.args.
"""
parser.add_argument(
'-as-api', '--asana-api',
action='store',
nargs='?',
const='',
dest='asana_api',
help="[setting] asana api key.",
)
parser.add_argument(
'-gh-api', '--github-api',
action='store',
nargs='?',
const='',
dest='github_api',
help="[setting] github api token.",
)
parser.add_argument(
'--first-issue',
type=int,
action='store',
nargs='?',
const='',
help="[setting] only sync issues [FIRST_ISSUE] and above"
) |
Returns repository and project. | def get_repo_and_project(self):
"""Returns repository and project."""
app = self.app
# Get repo
repo = app.data.apply('github-repo', app.args.github_repo,
app.prompt_repo,
on_load=app.github.get_repo,
on_save=lambda r: r.id
)
assert repo, "repository not found."
# Get project
project = app.data.apply('asana-project', app.args.asana_project,
app.prompt_project,
on_load=app.asana.projects.find_by_id,
on_save=lambda p: p['id']
)
assert project, "project not found."
# Set first issue
first_issue = app.data.apply('first-issue', app.args.first_issue,
"set the first issue to sync with [1 for new repos]",
on_save=int)
assert first_issue
assert first_issue >= 0, "issue must be positive"
app.sync_data()
return repo, project |
for each variant yields evidence and associated phenotypes both current and suggested | def get_variant_phenotypes_with_suggested_changes(variant_id_list):
'''for each variant, yields evidence and associated phenotypes, both current and suggested'''
variants = civic.get_variants_by_ids(variant_id_list)
evidence = list()
for variant in variants:
evidence.extend(variant.evidence)
for e in evidence:
suggested_changes_url = f'https://civicdb.org/api/evidence_items/{e.id}/suggested_changes'
resp = requests.get(suggested_changes_url)
resp.raise_for_status()
suggested_changes = dict()
for suggested_change in resp.json():
pheno_changes = suggested_change['suggested_changes'].get('phenotype_ids', None)
if pheno_changes is None:
continue
a, b = pheno_changes
added = set(b) - set(a)
deleted = set(a) - set(b)
rid = suggested_change['id']
suggested_changes[rid] = {'added': added, 'deleted': deleted}
yield e, {'suggested_changes': suggested_changes, 'current': set([x.id for x in e.phenotypes])} |
for each variant yields evidence and merged phenotype from applying suggested changes to current | def get_variant_phenotypes_with_suggested_changes_merged(variant_id_list):
'''for each variant, yields evidence and merged phenotype from applying suggested changes to current'''
for evidence, phenotype_status in get_variant_phenotypes_with_suggested_changes(variant_id_list):
final = phenotype_status['current']
for rid in sorted(phenotype_status['suggested_changes']):
changes = phenotype_status['suggested_changes'][rid]
final = final - changes['deleted']
final = final | changes['added']
if final:
yield evidence, final |
Search the cache for variants matching provided coordinates using the corresponding search mode. | def search_variants_by_coordinates(coordinate_query, search_mode='any'):
"""
Search the cache for variants matching provided coordinates using the corresponding search mode.
:param coordinate_query: A civic CoordinateQuery object
start: the genomic start coordinate of the query
stop: the genomic end coordinate of the query
chr: the GRCh37 chromosome of the query (e.g. "7", "X")
alt: the alternate allele at the coordinate [optional]
:param search_mode: ['any', 'include_smaller', 'include_larger', 'exact']
any: any overlap between a query and a variant is a match
include_smaller: variants must fit within the coordinates of the query
include_larger: variants must encompass the coordinates of the query
exact: variants must match coordinates precisely, as well as alternate
allele, if provided
search_mode is 'exact' by default
:return: Returns a list of variant hashes matching the coordinates and search_mode
"""
get_all_variants()
ct = COORDINATE_TABLE
start_idx = COORDINATE_TABLE_START
stop_idx = COORDINATE_TABLE_STOP
chr_idx = COORDINATE_TABLE_CHR
start = int(coordinate_query.start)
stop = int(coordinate_query.stop)
chromosome = str(coordinate_query.chr)
# overlapping = (start <= ct.stop) & (stop >= ct.start)
left_idx = chr_idx.searchsorted(chromosome)
right_idx = chr_idx.searchsorted(chromosome, side='right')
chr_ct_idx = chr_idx[left_idx:right_idx].index
right_idx = start_idx.searchsorted(stop, side='right')
start_ct_idx = start_idx[:right_idx].index
left_idx = stop_idx.searchsorted(start)
stop_ct_idx = stop_idx[left_idx:].index
match_idx = chr_ct_idx & start_ct_idx & stop_ct_idx
m_df = ct.loc[match_idx, ]
if search_mode == 'any':
var_digests = m_df.v_hash.to_list()
return [CACHE[v] for v in var_digests]
elif search_mode == 'include_smaller':
match_idx = (start <= m_df.start) & (stop >= m_df.stop)
elif search_mode == 'include_larger':
match_idx = (start >= m_df.start) & (stop <= m_df.stop)
elif search_mode == 'exact':
match_idx = (start == m_df.stop) & (stop == m_df.start)
if coordinate_query.alt:
match_idx = match_idx & (coordinate_query.alt == m_df.alt)
else:
raise ValueError("unexpected search mode")
var_digests = m_df.loc[match_idx,].v_hash.to_list()
return [CACHE[v] for v in var_digests] |
An interator to search the cache for variants matching the set of sorted coordinates and yield matches corresponding to the search mode. | def bulk_search_variants_by_coordinates(sorted_queries, search_mode='any'):
"""
An interator to search the cache for variants matching the set of sorted coordinates and yield
matches corresponding to the search mode.
:param sorted_queries: A list of civic CoordinateQuery objects, sorted by coordinate.
start: the genomic start coordinate of the query
stop: the genomic end coordinate of the query
chr: the GRCh37 chromosome of the query (e.g. "7", "X")
alt: the alternate allele at the coordinate [optional]
:param search_mode: ['any', 'include_smaller', 'include_larger', 'exact']
any: any overlap between a query and a variant is a match
include_smaller: variants must fit within the coordinates of the query
include_larger: variants must encompass the coordinates of the query
exact: variants must match coordinates precisely, as well as alternate
allele, if provided
search_mode is 'exact' by default
:yield: Yields (query, match) tuples for each identified match
"""
def is_sorted(prev_q, current_q):
if prev_q['chr'] < current_q['chr']:
return True
if prev_q['chr'] > current_q['chr']:
return False
if prev_q['start'] < current_q['start']:
return True
if prev_q['start'] > current_q['start']:
return False
if prev_q['stop'] < current_q['stop']:
return True
if prev_q['stop'] > current_q['stop']:
return False
return True
ct_pointer = 0
query_pointer = 0
last_query_pointer = -1
match_start = None
ct = MODULE.COORDINATE_TABLE
matches = defaultdict(list)
Match = namedtuple('Match', ct.columns)
while query_pointer < len(sorted_queries) and ct_pointer < len(ct):
if last_query_pointer != query_pointer:
q = sorted_queries[query_pointer]
if match_start is not None:
ct_pointer = match_start
match_start = None
last_query_pointer = query_pointer
c = ct.iloc[ct_pointer]
q_chr = str(q.chr)
c_chr = c.chr
if q_chr < c_chr:
query_pointer += 1
continue
if q_chr > c_chr:
ct_pointer += 1
continue
q_start = int(q.start)
c_start = c.start
q_stop = int(q.stop)
c_stop = c.stop
if q_start > c_stop:
ct_pointer += 1
continue
if q_stop < c_start:
query_pointer += 1
continue
if search_mode == 'any':
matches[q].append(c.to_dict())
elif search_mode == 'exact' and q_start == c_start and q_stop == c_stop:
q_alt = q.alt
c_alt = c.alt
if not (q_alt and c_alt and q_alt != c_alt):
matches[q].append(Match(**c.to_dict()))
elif search_mode == 'include_smaller':
raise NotImplementedError
elif search_mode == 'include_larger':
raise NotImplementedError
if match_start is None:
match_start = ct_pointer
ct_pointer += 1
return dict(matches) |
Updates record and returns True if record is complete after update else False. | def update(self, allow_partial=True, force=False, **kwargs):
"""Updates record and returns True if record is complete after update, else False."""
if kwargs:
self.__init__(partial=allow_partial, force=force, **kwargs)
return not self._partial
if not force and CACHE.get(hash(self)):
cached = CACHE[hash(self)]
for field in self._SIMPLE_FIELDS | self._COMPLEX_FIELDS:
v = getattr(cached, field)
setattr(self, field, v)
self._partial = False
logging.info(f'Loading {str(self)} from cache')
return True
resp_dict = element_lookup_by_id(self.type, self.id)
self.__init__(partial=False, **resp_dict)
return True |
Returns a unique list of seq | def uniqify(cls, seq):
"""Returns a unique list of seq"""
seen = set()
seen_add = seen.add
return [ x for x in seq if x not in seen and not seen_add(x)] |
Connects to Github and Asana and authenticates via OAuth. | def authenticate(self):
"""Connects to Github and Asana and authenticates via OAuth."""
if self.oauth:
return False
# Save asana.
self.settings.apply('api-asana', self.args.asana_api,
"enter asana api key")
# Save github.com
self.settings.apply('api-github', self.args.github_api,
"enter github.com token")
logging.debug("authenticating asana api.")
self.asana = Client.basic_auth(self.settings['api-asana'])
self.asana_errors = asana_errors
self.asana_me = self.asana.users.me()
logging.debug("authenticating github api")
self.github = Github(self.settings['api-github'])
self.github_user = self.github.get_user()
self.oauth = True |
Given a list of values and names accepts the index value or name. | def _list_select(cls, lst, prompt, offset=0):
"""Given a list of values and names, accepts the index value or name."""
inp = raw_input("select %s: " % prompt)
assert inp, "value required."
try:
return lst[int(inp)+offset]
except ValueError:
return inp
except IndexError:
assert False, "bad value." |
Saves a issue data ( tasks etc. ) to local data. | def save_issue_data_task(self, issue, task_id, namespace='open'):
"""Saves a issue data (tasks, etc.) to local data.
Args:
issue:
`int`. Github issue number.
task:
`int`. Asana task ID.
namespace:
`str`. Namespace for storing this issue.
"""
issue_data = self.get_saved_issue_data(issue, namespace)
if not issue_data.has_key('tasks'):
issue_data['tasks'] = [task_id]
elif task_id not in issue_data['tasks']:
issue_data['tasks'].append(task_id) |
Returns issue data from local data. | def get_saved_issue_data(self, issue, namespace='open'):
"""Returns issue data from local data.
Args:
issue:
`int`. Github issue number.
namespace:
`str`. Namespace for storing this issue.
"""
if isinstance(issue, int):
issue_number = str(issue)
elif isinstance(issue, basestring):
issue_number = issue
else:
issue_number = issue.number
issue_data_key = self._issue_data_key(namespace)
issue_data = self.data.get(issue_data_key,
{})
_data = issue_data.get(str(issue_number), {})
issue_data[str(issue_number)] = _data
return _data |
Moves an issue_data from one namespace to another. | def move_saved_issue_data(self, issue, ns, other_ns):
"""Moves an issue_data from one namespace to another."""
if isinstance(issue, int):
issue_number = str(issue)
elif isinstance(issue, basestring):
issue_number = issue
else:
issue_number = issue.number
issue_data_key = self._issue_data_key(ns)
other_issue_data_key = self._issue_data_key(other_ns)
issue_data = self.data.get(issue_data_key,
{})
other_issue_data = self.data.get(other_issue_data_key,
{})
_id = issue_data.pop(issue_number, None)
if _id:
other_issue_data[issue_number] = _id
self.data[other_issue_data_key] = other_issue_data
self.data[issue_data_key] = issue_data |
Returns task data from local data. | def get_saved_task_data(self, task):
"""Returns task data from local data.
Args:
task:
`int`. Asana task number.
"""
if isinstance(task, int):
task_number = str(task)
elif isinstance(task, basestring):
task_number = task
else:
task_number = task['id']
task_data_key = self._task_data_key()
task_data = self.data.get(task_data_key, {})
_data = task_data.get(str(task_number), {})
task_data[str(task_number)] = _data
return _data |
Retrieves a task from asana. | def get_asana_task(self, asana_task_id):
"""Retrieves a task from asana."""
try:
return self.asana.tasks.find_by_id(asana_task_id)
except asana_errors.NotFoundError:
return None
except asana_errors.ForbiddenError:
return None |
Save data. | def save(self):
"""Save data."""
with open(self.filename, 'wb') as file:
self.prune()
self.data['version'] = self.version
json.dump(self.data,
file,
sort_keys=True, indent=2) |
Applies a setting value to a key if the value is not None. | def apply(self, key, value, prompt=None,
on_load=lambda a: a, on_save=lambda a: a):
"""Applies a setting value to a key, if the value is not `None`.
Returns without prompting if either of the following:
* `value` is not `None`
* already present in the dictionary
Args:
prompt:
May either be a string to prompt via `raw_input` or a
method (callable) that returns the value.
on_load:
lambda. Value is passed through here after loaded.
on_save:
lambda. Value is saved as this value.
"""
# Reset value if flag exists without value
if value == '':
value = None
if key and self.data.has_key(key): del self.data[key]
# If value is explicitly set from args.
if value is not None:
value = on_load(value)
if key: self.data[key] = on_save(value)
return value
elif not key or not self.has_key(key):
if callable(prompt):
value = prompt()
elif prompt is not None:
value = raw_input(prompt + ": ")
if value is None:
if self.data.has_key(key): del self.data[key]
return None
self.data[key] = on_save(value)
return value
return on_load(self.data[key]) |
Add arguments to the parser for collection in app. args. | def add_arguments(cls, parser):
"""Add arguments to the parser for collection in app.args.
Args:
parser:
`argparse.ArgumentParser`. Parser.
Arguments added here are server on
self.args.
"""
parser.add_argument(
'-i', '--issue',
action='store',
nargs='?',
const='',
dest='issue',
help="[pr] issue #",
)
parser.add_argument(
'-br', '--branch',
action='store',
nargs='?',
const='',
dest='branch',
help="[pr] branch",
)
parser.add_argument(
'-tbr', '--target-branch',
action='store',
nargs='?',
const='',
default='master',
dest='target_branch',
help="[pr] name of branch to pull changes into\n(defaults to: master)",
) |
Decorator for retrying tasks with special cases. | def transport_task(func):
"""Decorator for retrying tasks with special cases."""
def wrapped_func(*args, **kwargs):
tries = 0
while True:
try:
try:
return func(*args, **kwargs)
except (asana_errors.InvalidRequestError,
asana_errors.NotFoundError), exc:
logging.warn("warning: invalid request: %r", exc)
except asana_errors.ForbiddenError, exc:
logging.warn("forbidden error: %r", exc)
except asana_errors.NotFoundError, exc:
logging.warn("not found error: %r", exc)
return None
except asana_errors.RetryableAsanaError, retry_exc:
tries += 1
logging.warn("retry exception %r on try %d", retry_exc, tries)
if tries >= 3:
raise
except Exception, exc:
logging.exception("Exception in transport.")
return
return wrapped_func |
Waits until queue is empty. | def flush(callback=None):
"""Waits until queue is empty."""
while True:
if shutdown_event.is_set():
return
if callable(callback):
callback()
try:
item = queue.get(timeout=1)
queue.put(item) # put it back, we're just peeking.
except Queue.Empty:
return |
Creates a task | def task_create(asana_workspace_id, name, notes, assignee, projects,
completed, **kwargs):
"""Creates a task"""
put("task_create",
asana_workspace_id=asana_workspace_id,
name=name,
notes=notes,
assignee=assignee,
projects=projects,
completed=completed,
**kwargs) |
Returns formatting for the tasks section of asana. | def format_task_numbers_with_links(tasks):
"""Returns formatting for the tasks section of asana."""
project_id = data.get('asana-project', None)
def _task_format(task_id):
if project_id:
asana_url = tool.ToolApp.make_asana_url(project_id, task_id)
return "[#%d](%s)" % (task_id, asana_url)
else:
return "#%d" % task_id
return "\n".join([_task_format(tid) for tid in tasks]) |
Creates a missing task. | def create_missing_task(self,
asana_workspace_id,
name,
assignee,
projects,
completed,
issue_number,
issue_html_url,
issue_state,
issue_body,
tasks,
labels,
label_tag_map):
"""Creates a missing task."""
task = self.asana.tasks.create_in_workspace(
asana_workspace_id,
{
'name': name,
'notes': issue_body,
'assignee': assignee,
'projects': projects,
'completed': completed,
})
# Announce task git issue
task_id = task['id']
put("create_story",
task_id=task_id,
text="Git Issue #%d: \n"
"%s" % (
issue_number,
issue_html_url,
)
)
put("apply_tasks_to_issue",
tasks=[task_id],
issue_number=issue_number,
issue_body=issue_body,
)
# Save task to drive
put_setting("save_issue_data_task",
issue=issue_number,
task_id=task_id,
namespace=issue_state)
tasks.append(task_id)
# Sync tags/labels
put("sync_tags",
tasks=tasks,
labels=labels,
label_tag_map=label_tag_map) |
Applies task numbers to an issue. | def apply_tasks_to_issue(self, tasks, issue_number, issue_body):
"""Applies task numbers to an issue."""
issue_body = issue_body
task_numbers = format_task_numbers_with_links(tasks)
if task_numbers:
new_body = ASANA_SECTION_RE.sub('', issue_body)
new_body = new_body + "\n## Asana Tasks:\n\n%s" % task_numbers
put("issue_edit",
issue_number=issue_number,
body=new_body)
return new_body
return issue_body |
Return a list of data types. | def data_types(self):
"""Return a list of data types."""
data = self.gencloud.project_data(self.id)
return sorted(set(d.type for d in data)) |
Query for Data object annotation. | def data(self, **query):
"""Query for Data object annotation."""
data = self.gencloud.project_data(self.id)
query['case_ids__contains'] = self.id
ids = set(d['id'] for d in self.gencloud.api.dataid.get(**query)['objects'])
return [d for d in data if d.id in ids] |
Send string to module level log | def ekm_log(logstr, priority=3):
""" Send string to module level log
Args:
logstr (str): string to print.
priority (int): priority, supports 3 (default) and 4 (special).
"""
if priority <= ekmmeters_log_level:
dt = datetime.datetime
stamp = datetime.datetime.now().strftime("%Y-%m-%d %H:%M.%f")
ekmmeters_log_func("[EKM Meter Debug Message: " + stamp + "] -> " + logstr)
pass |
Required initialization call wraps pyserial constructor. | def initPort(self):
""" Required initialization call, wraps pyserial constructor. """
try:
self.m_ser = serial.Serial(port=self.m_ttyport,
baudrate=self.m_baudrate,
timeout=0,
parity=serial.PARITY_EVEN,
stopbits=serial.STOPBITS_ONE,
bytesize=serial.SEVENBITS,
rtscts=False)
ekm_log("Pyserial version = " + serial.VERSION)
ekm_log("Port = " + self.m_ttyport)
ekm_log("Rate = " + str(self.m_baudrate))
time.sleep(self.m_init_wait)
return True
except:
ekm_log(traceback.format_exc(sys.exc_info()))
return False |
Passthrough for pyserial Serial. write (). | def write(self, output):
"""Passthrough for pyserial Serial.write().
Args:
output (str): Block to write to port
"""
view_str = output.encode('ascii', 'ignore')
if (len(view_str) > 0):
self.m_ser.write(view_str)
self.m_ser.flush()
self.m_ser.reset_input_buffer()
time.sleep(self.m_force_wait)
pass |
Optional polling loop control | def setPollingValues(self, max_waits, wait_sleep):
""" Optional polling loop control
Args:
max_waits (int): waits
wait_sleep (int): ms per wait
"""
self.m_max_waits = max_waits
self.m_wait_sleep = wait_sleep |
Poll for finished block or first byte ACK. Args: context ( str ): internal serial call context. | def getResponse(self, context=""):
""" Poll for finished block or first byte ACK.
Args:
context (str): internal serial call context.
Returns:
string: Response, implict cast from byte array.
"""
waits = 0 # allowed interval counter
response_str = "" # returned bytes in string default
try:
waits = 0 # allowed interval counter
while (waits < self.m_max_waits):
bytes_to_read = self.m_ser.inWaiting()
if bytes_to_read > 0:
next_chunk = str(self.m_ser.read(bytes_to_read)).encode('ascii', 'ignore')
response_str += next_chunk
if (len(response_str) == 255):
time.sleep(self.m_force_wait)
return response_str
if (len(response_str) == 1) and (response_str.encode('hex') == '06'):
time.sleep(self.m_force_wait)
return response_str
else: # hang out -- half shortest expected interval (50 ms)
waits += 1
time.sleep(self.m_force_wait)
response_str = ""
except:
ekm_log(traceback.format_exc(sys.exc_info()))
return response_str |
Use the serial block definitions in V3 and V4 to create one field list. | def combineAB(self):
""" Use the serial block definitions in V3 and V4 to create one field list. """
v4definition_meter = V4Meter()
v4definition_meter.makeAB()
defv4 = v4definition_meter.getReadBuffer()
v3definition_meter = V3Meter()
v3definition_meter.makeReturnFormat()
defv3 = v3definition_meter.getReadBuffer()
for fld in defv3:
if fld not in self.m_all_fields:
compare_fld = fld.upper()
if not "RESERVED" in compare_fld and not "CRC" in compare_fld:
self.m_all_fields[fld] = defv3[fld]
for fld in defv4:
if fld not in self.m_all_fields:
compare_fld = fld.upper()
if not "RESERVED" in compare_fld and not "CRC" in compare_fld:
self.m_all_fields[fld] = defv4[fld]
pass |
Translate FieldType to portable SQL Type. Override if needful. Args: fld_type ( int ):: class: ~ekmmeters. FieldType in serial block. fld_len ( int ): Binary length in serial block | def mapTypeToSql(fld_type=FieldType.NoType, fld_len=0):
""" Translate FieldType to portable SQL Type. Override if needful.
Args:
fld_type (int): :class:`~ekmmeters.FieldType` in serial block.
fld_len (int): Binary length in serial block
Returns:
string: Portable SQL type and length where appropriate.
"""
if fld_type == FieldType.Float:
return "FLOAT"
elif fld_type == FieldType.String:
return "VARCHAR(" + str(fld_len) + ")"
elif fld_type == FieldType.Int:
return "INT"
elif fld_type == FieldType.Hex:
return "VARCHAR(" + str(fld_len * 2) + ")"
elif fld_type == FieldType.PowerFactor:
return "VARCHAR(" + str(fld_len) + ")"
else:
ekm_log("Type " + str(type) + " not handled by mapTypeToSql, returned VARCHAR(255)")
return "VARCHAR(255)" |
Return query portion below CREATE. Args: qry_str ( str ): String as built. | def fillCreate(self, qry_str):
""" Return query portion below CREATE.
Args:
qry_str (str): String as built.
Returns:
string: Passed string with fields appended.
"""
count = 0
for fld in self.m_all_fields:
fld_type = self.m_all_fields[fld][MeterData.TypeValue]
fld_len = self.m_all_fields[fld][MeterData.SizeValue]
qry_spec = self.mapTypeToSql(fld_type, fld_len)
if count > 0:
qry_str += ", \n"
qry_str = qry_str + ' ' + fld + ' ' + qry_spec
count += 1
qry_str += (",\n\t" + Field.Time_Stamp + " BIGINT,\n\t" +
"Raw_A VARCHAR(512),\n\t" +
"Raw_B VARCHAR(512)\n)")
return qry_str |
Reasonably portable SQL CREATE for defined fields. Returns: string: Portable as possible SQL Create for all - reads table. | def sqlCreate(self):
""" Reasonably portable SQL CREATE for defined fields.
Returns:
string: Portable as possible SQL Create for all-reads table.
"""
count = 0
qry_str = "CREATE TABLE Meter_Reads ( \n\r"
qry_str = self.fillCreate(qry_str)
ekm_log(qry_str, 4)
return qry_str |
Reasonably portable SQL INSERT for from combined read buffer. Args: def_buf ( SerialBlock ): Database only serial block of all fields. raw_a ( str ): Raw A read as hex string. raw_b ( str ): Raw B read ( if exists otherwise empty ) as hex string. | def sqlInsert(def_buf, raw_a, raw_b):
""" Reasonably portable SQL INSERT for from combined read buffer.
Args:
def_buf (SerialBlock): Database only serial block of all fields.
raw_a (str): Raw A read as hex string.
raw_b (str): Raw B read (if exists, otherwise empty) as hex string.
Returns:
str: SQL insert for passed read buffer
"""
count = 0
qry_str = "INSERT INTO Meter_Reads ( \n\t"
for fld in def_buf:
if count > 0:
qry_str += ", \n\t"
qry_str = qry_str + fld
count += 1
qry_str += (",\n\t" + Field.Time_Stamp + ", \n\t" +
"Raw_A,\n\t" +
"Raw_B\n) \n" +
"VALUES( \n\t")
count = 0
for fld in def_buf:
if count > 0:
qry_str += ", \n\t"
fld_type = def_buf[fld][MeterData.TypeValue]
fld_str_content = def_buf[fld][MeterData.StringValue]
delim = ""
if (fld_type == FieldType.Hex) or \
(fld_type == FieldType.String) or \
(fld_type == FieldType.PowerFactor):
delim = "'"
qry_str = qry_str + delim + fld_str_content + delim
count += 1
time_val = int(time.time() * 1000)
qry_str = (qry_str + ",\n\t" + str(time_val) + ",\n\t'" +
binascii.b2a_hex(raw_a) + "'" + ",\n\t'" +
binascii.b2a_hex(raw_b) + "'\n);")
ekm_log(qry_str, 4)
return qry_str |
Call overridden dbExec () with built insert statement. Args: def_buf ( SerialBlock ): Block of read buffer fields to write. raw_a ( str ): Hex string of raw A read. raw_b ( str ): Hex string of raw B read or empty. | def dbInsert(self, def_buf, raw_a, raw_b):
""" Call overridden dbExec() with built insert statement.
Args:
def_buf (SerialBlock): Block of read buffer fields to write.
raw_a (str): Hex string of raw A read.
raw_b (str): Hex string of raw B read or empty.
"""
self.dbExec(self.sqlInsert(def_buf, raw_a, raw_b)) |
Required override of dbExec () from MeterDB () run query. Args: query_str ( str ): query to run | def dbExec(self, query_str):
""" Required override of dbExec() from MeterDB(), run query.
Args:
query_str (str): query to run
"""
try:
connection = sqlite3.connect(self.m_connection_string)
cursor = connection.cursor()
cursor.execute(query_str)
connection.commit()
cursor.close()
connection.close()
return True
except:
ekm_log(traceback.format_exc(sys.exc_info()))
return False
pass |
Sqlite callback accepting the cursor and the original row as a tuple. | def dict_factory(self, cursor, row):
""" Sqlite callback accepting the cursor and the original row as a tuple.
Simple return of JSON safe types.
Args:
cursor (sqlite cursor): Original cursory
row (sqlite row tuple): Original row.
Returns:
dict: modified row.
"""
d = {}
for idx, col in enumerate(cursor.description):
val = row[idx]
name = col[0]
if name == Field.Time_Stamp:
d[col[0]] = str(val)
continue
if name == "Raw_A" or name == "Raw_B": # or name == Field.Meter_Time:
continue
if name not in self.m_all_fields:
continue
if (str(val) != "None") and ((val > 0) or (val < 0)):
d[name] = str(val)
return d |
Sqlite callback accepting the cursor and the original row as a tuple. | def raw_dict_factory(cursor, row):
""" Sqlite callback accepting the cursor and the original row as a tuple.
Simple return of JSON safe types, including raw read hex strings.
Args:
cursor (sqlite cursor): Original cursory
row (sqlite row tuple): Original row.
Returns:
dict: modified row.
"""
d = {}
for idx, col in enumerate(cursor.description):
val = row[idx]
name = col[0]
if name == Field.Time_Stamp or name == Field.Meter_Address:
d[name] = str(val)
continue
if name == "Raw_A" or name == "Raw_B":
d[name] = str(val)
continue
return d |
Simple since Time_Stamp query returned as JSON records. | def renderJsonReadsSince(self, timestamp, meter):
""" Simple since Time_Stamp query returned as JSON records.
Args:
timestamp (int): Epoch time in seconds.
meter (str): 12 character meter address to query
Returns:
str: JSON rendered read records.
"""
result = ""
try:
connection = sqlite3.connect(self.m_connection_string)
connection.row_factory = self.dict_factory
select_cursor = connection.cursor()
select_cursor.execute("select * from Meter_Reads where " + Field.Time_Stamp +
" > " + str(timestamp) + " and " + Field.Meter_Address +
"= '" + meter + "';")
reads = select_cursor.fetchall()
result = json.dumps(reads, indent=4)
except:
ekm_log(traceback.format_exc(sys.exc_info()))
return result |
Set context string for serial command. Private setter. | def setContext(self, context_str):
""" Set context string for serial command. Private setter.
Args:
context_str (str): Command specific string.
"""
if (len(self.m_context) == 0) and (len(context_str) >= 7):
if context_str[0:7] != "request":
ekm_log("Context: " + context_str)
self.m_context = context_str |
Drop in pure python replacement for ekmcrc. c extension. | def calc_crc16(buf):
""" Drop in pure python replacement for ekmcrc.c extension.
Args:
buf (bytes): String or byte array (implicit Python 2.7 cast)
Returns:
str: 16 bit CRC per EKM Omnimeters formatted as hex string.
"""
crc_table = [0x0000, 0xc0c1, 0xc181, 0x0140, 0xc301, 0x03c0, 0x0280, 0xc241,
0xc601, 0x06c0, 0x0780, 0xc741, 0x0500, 0xc5c1, 0xc481, 0x0440,
0xcc01, 0x0cc0, 0x0d80, 0xcd41, 0x0f00, 0xcfc1, 0xce81, 0x0e40,
0x0a00, 0xcac1, 0xcb81, 0x0b40, 0xc901, 0x09c0, 0x0880, 0xc841,
0xd801, 0x18c0, 0x1980, 0xd941, 0x1b00, 0xdbc1, 0xda81, 0x1a40,
0x1e00, 0xdec1, 0xdf81, 0x1f40, 0xdd01, 0x1dc0, 0x1c80, 0xdc41,
0x1400, 0xd4c1, 0xd581, 0x1540, 0xd701, 0x17c0, 0x1680, 0xd641,
0xd201, 0x12c0, 0x1380, 0xd341, 0x1100, 0xd1c1, 0xd081, 0x1040,
0xf001, 0x30c0, 0x3180, 0xf141, 0x3300, 0xf3c1, 0xf281, 0x3240,
0x3600, 0xf6c1, 0xf781, 0x3740, 0xf501, 0x35c0, 0x3480, 0xf441,
0x3c00, 0xfcc1, 0xfd81, 0x3d40, 0xff01, 0x3fc0, 0x3e80, 0xfe41,
0xfa01, 0x3ac0, 0x3b80, 0xfb41, 0x3900, 0xf9c1, 0xf881, 0x3840,
0x2800, 0xe8c1, 0xe981, 0x2940, 0xeb01, 0x2bc0, 0x2a80, 0xea41,
0xee01, 0x2ec0, 0x2f80, 0xef41, 0x2d00, 0xedc1, 0xec81, 0x2c40,
0xe401, 0x24c0, 0x2580, 0xe541, 0x2700, 0xe7c1, 0xe681, 0x2640,
0x2200, 0xe2c1, 0xe381, 0x2340, 0xe101, 0x21c0, 0x2080, 0xe041,
0xa001, 0x60c0, 0x6180, 0xa141, 0x6300, 0xa3c1, 0xa281, 0x6240,
0x6600, 0xa6c1, 0xa781, 0x6740, 0xa501, 0x65c0, 0x6480, 0xa441,
0x6c00, 0xacc1, 0xad81, 0x6d40, 0xaf01, 0x6fc0, 0x6e80, 0xae41,
0xaa01, 0x6ac0, 0x6b80, 0xab41, 0x6900, 0xa9c1, 0xa881, 0x6840,
0x7800, 0xb8c1, 0xb981, 0x7940, 0xbb01, 0x7bc0, 0x7a80, 0xba41,
0xbe01, 0x7ec0, 0x7f80, 0xbf41, 0x7d00, 0xbdc1, 0xbc81, 0x7c40,
0xb401, 0x74c0, 0x7580, 0xb541, 0x7700, 0xb7c1, 0xb681, 0x7640,
0x7200, 0xb2c1, 0xb381, 0x7340, 0xb101, 0x71c0, 0x7080, 0xb041,
0x5000, 0x90c1, 0x9181, 0x5140, 0x9301, 0x53c0, 0x5280, 0x9241,
0x9601, 0x56c0, 0x5780, 0x9741, 0x5500, 0x95c1, 0x9481, 0x5440,
0x9c01, 0x5cc0, 0x5d80, 0x9d41, 0x5f00, 0x9fc1, 0x9e81, 0x5e40,
0x5a00, 0x9ac1, 0x9b81, 0x5b40, 0x9901, 0x59c0, 0x5880, 0x9841,
0x8801, 0x48c0, 0x4980, 0x8941, 0x4b00, 0x8bc1, 0x8a81, 0x4a40,
0x4e00, 0x8ec1, 0x8f81, 0x4f40, 0x8d01, 0x4dc0, 0x4c80, 0x8c41,
0x4400, 0x84c1, 0x8581, 0x4540, 0x8701, 0x47c0, 0x4680, 0x8641,
0x8201, 0x42c0, 0x4380, 0x8341, 0x4100, 0x81c1, 0x8081, 0x4040]
crc = 0xffff
for c in buf:
index = (crc ^ ord(c)) & 0xff
crct = crc_table[index]
crc = (crc >> 8) ^ crct
crc = (crc << 8) | (crc >> 8)
crc &= 0x7F7F
return "%04x" % crc |
Simple wrap to calc legacy PF value | def calcPF(pf):
""" Simple wrap to calc legacy PF value
Args:
pf: meter power factor reading
Returns:
int: legacy push pf
"""
pf_y = pf[:1]
pf_x = pf[1:]
result = 100
if pf_y == CosTheta.CapacitiveLead:
result = 200 - int(pf_x)
elif pf_y == CosTheta.InductiveLag:
result = int(pf_x)
return result |
Serial call to set max demand period. | def setMaxDemandPeriod(self, period, password="00000000"):
""" Serial call to set max demand period.
Args:
period (int): : as int.
password (str): Optional password.
Returns:
bool: True on completion with ACK.
"""
result = False
self.setContext("setMaxDemandPeriod")
try:
if period < 1 or period > 3:
self.writeCmdMsg("Correct parameter: 1 = 15 minute, 2 = 30 minute, 3 = hour")
self.setContext("")
return result
if not self.request(False):
self.writeCmdMsg("Bad read CRC on setting")
else:
if not self.serialCmdPwdAuth(password):
self.writeCmdMsg("Password failure")
else:
req_str = "015731023030353028" + binascii.hexlify(str(period)).zfill(2) + "2903"
req_str += self.calc_crc16(req_str[2:].decode("hex"))
self.m_serial_port.write(req_str.decode("hex"))
if self.m_serial_port.getResponse(self.getContext()).encode("hex") == "06":
self.writeCmdMsg("Success(setMaxDemandPeriod): 06 returned.")
result = True
self.serialPostEnd()
except:
ekm_log(traceback.format_exc(sys.exc_info()))
self.setContext("")
return result |
Serial Call to set meter password. USE WITH CAUTION. | def setMeterPassword(self, new_pwd, pwd="00000000"):
""" Serial Call to set meter password. USE WITH CAUTION.
Args:
new_pwd (str): 8 digit numeric password to set
pwd (str): Old 8 digit numeric password.
Returns:
bool: True on completion with ACK.
"""
result = False
self.setContext("setMeterPassword")
try:
if len(new_pwd) != 8 or len(pwd) != 8:
self.writeCmdMsg("Passwords must be exactly eight characters.")
self.setContext("")
return result
if not self.request(False):
self.writeCmdMsg("Pre command read failed: check serial line.")
else:
if not self.serialCmdPwdAuth(pwd):
self.writeCmdMsg("Password failure")
else:
req_pwd = binascii.hexlify(new_pwd.zfill(8))
req_str = "015731023030323028" + req_pwd + "2903"
req_str += self.calc_crc16(req_str[2:].decode("hex"))
self.m_serial_port.write(req_str.decode("hex"))
if self.m_serial_port.getResponse(self.getContext()).encode("hex") == "06":
self.writeCmdMsg("Success(setMeterPassword): 06 returned.")
result = True
self.serialPostEnd()
except:
ekm_log(traceback.format_exc(sys.exc_info()))
self.setContext("")
return result |
Wrapper for struct. unpack with SerialBlock buffer definitionns. | def unpackStruct(self, data, def_buf):
""" Wrapper for struct.unpack with SerialBlock buffer definitionns.
Args:
data (str): Implicit cast bytes to str, serial port return.
def_buf (SerialBlock): Block object holding field lengths.
Returns:
tuple: parsed result of struct.unpack() with field definitions.
"""
struct_str = "="
for fld in def_buf:
if not def_buf[fld][MeterData.CalculatedFlag]:
struct_str = struct_str + str(def_buf[fld][MeterData.SizeValue]) + "s"
if len(data) == 255:
contents = struct.unpack(struct_str, str(data))
else:
self.writeCmdMsg("Length error. Len() size = " + str(len(data)))
contents = ()
return contents |
Move data from raw tuple into scaled and conveted values. | def convertData(self, contents, def_buf, kwh_scale=ScaleKWH.EmptyScale):
""" Move data from raw tuple into scaled and conveted values.
Args:
contents (tuple): Breakout of passed block from unpackStruct().
def_buf (): Read buffer destination.
kwh_scale (int): :class:`~ekmmeters.ScaleKWH` as int, from Field.kWhScale`
Returns:
bool: True on completion.
"""
log_str = ""
count = 0
# getting scale does not require a full read. It does require that the
# reads have the scale value in the first block read. This requirement
# is filled by default in V3 and V4 requests
if kwh_scale == ScaleKWH.EmptyScale:
scale_offset = int(def_buf.keys().index(Field.kWh_Scale))
self.m_kwh_precision = kwh_scale = int(contents[scale_offset])
for fld in def_buf:
if def_buf[fld][MeterData.CalculatedFlag]:
count += 1
continue
if len(contents) == 0:
count += 1
continue
try: # scrub up messes on a field by field basis
raw_data = contents[count]
fld_type = def_buf[fld][MeterData.TypeValue]
fld_scale = def_buf[fld][MeterData.ScaleValue]
if fld_type == FieldType.Float:
float_data = float(str(raw_data))
divisor = 1
if fld_scale == ScaleType.KWH:
divisor = 1
if kwh_scale == ScaleKWH.Scale10:
divisor = 10
elif kwh_scale == ScaleKWH.Scale100:
divisor = 100
elif (kwh_scale != ScaleKWH.NoScale) and (kwh_scale != ScaleKWH.EmptyScale):
ekm_log("Unrecognized kwh scale.")
elif fld_scale == ScaleType.Div10:
divisor = 10
elif fld_scale == ScaleType.Div100:
divisor = 100
elif fld_scale != ScaleType.No:
ekm_log("Unrecognized float scale.")
float_data /= divisor
float_data_str = str(float_data)
def_buf[fld][MeterData.StringValue] = float_data_str
def_buf[fld][MeterData.NativeValue] = float_data
elif fld_type == FieldType.Hex:
hex_data = raw_data.encode('hex')
def_buf[fld][MeterData.StringValue] = hex_data
def_buf[fld][MeterData.NativeValue] = hex_data
elif fld_type == FieldType.Int:
integer_data = int(raw_data)
integer_data_str = str(integer_data)
if len(integer_data_str) == 0:
integer_data_str = str(0)
def_buf[fld][MeterData.StringValue] = integer_data_str
def_buf[fld][MeterData.NativeValue] = integer_data
elif fld_type == FieldType.String:
string_data = str(raw_data)
def_buf[fld][MeterData.StringValue] = string_data
def_buf[fld][MeterData.NativeValue] = string_data
elif fld_type == FieldType.PowerFactor:
def_buf[fld][MeterData.StringValue] = str(raw_data)
def_buf[fld][MeterData.NativeValue] = str(raw_data)
else:
ekm_log("Unrecognized field type")
log_str = log_str + '"' + fld + '": "' + def_buf[fld][MeterData.StringValue] + '"\n'
except:
ekm_log("Exception on Field:" + str(fld))
ekm_log(traceback.format_exc(sys.exc_info()))
self.writeCmdMsg("Exception on Field:" + str(fld))
count += 1
return True |
Translate the passed serial block into string only JSON. | def jsonRender(self, def_buf):
""" Translate the passed serial block into string only JSON.
Args:
def_buf (SerialBlock): Any :class:`~ekmmeters.SerialBlock` object.
Returns:
str: JSON rendering of meter record.
"""
try:
ret_dict = SerialBlock()
ret_dict[Field.Meter_Address] = self.getMeterAddress()
for fld in def_buf:
compare_fld = fld.upper()
if not "RESERVED" in compare_fld and not "CRC" in compare_fld:
ret_dict[str(fld)] = def_buf[fld][MeterData.StringValue]
except:
ekm_log(traceback.format_exc(sys.exc_info()))
return ""
return json.dumps(ret_dict, indent=4) |
Internal read CRC wrapper. | def crcMeterRead(self, raw_read, def_buf):
""" Internal read CRC wrapper.
Args:
raw_read (str): Bytes with implicit string cast from serial read
def_buf (SerialBlock): Populated read buffer.
Returns:
bool: True if passed CRC equals calculated CRC.
"""
try:
if len(raw_read) == 0:
ekm_log("(" + self.m_context + ") Empty return read.")
return False
sent_crc = self.calc_crc16(raw_read[1:-2])
logstr = "(" + self.m_context + ")CRC sent = " + str(def_buf["crc16"][MeterData.StringValue])
logstr += " CRC calc = " + sent_crc
ekm_log(logstr)
if int(def_buf["crc16"][MeterData.StringValue], 16) == int(sent_crc, 16):
return True
# A cross simple test lines on a USB serial adapter, these occur every
# 1000 to 2000 reads, and they show up here as a bad unpack or
# a bad crc type call. In either case, we suppress them a log will
# become quite large. ekmcrc errors come through as type errors.
# Failures of int type conversion in 16 bit conversion occur as value
# errors.
except struct.error:
ekm_log(str(sys.exc_info()))
for frame in traceback.extract_tb(sys.exc_info()[2]):
fname, lineno, fn, text = frame
ekm_log("Error in %s on line %d" % (fname, lineno))
return False
except TypeError:
ekm_log(str(sys.exc_info()))
for frame in traceback.extract_tb(sys.exc_info()[2]):
fname, lineno, fn, text = frame
ekm_log("Error in %s on line %d" % (fname, lineno))
return False
except ValueError:
ekm_log(str(sys.exc_info()))
for frame in traceback.extract_tb(sys.exc_info()[2]):
fname, lineno, fn, text = frame
ekm_log("Error in %s on line %d" % (fname, lineno))
return False
return False |
Break out a date from Omnimeter read. | def splitEkmDate(dateint):
"""Break out a date from Omnimeter read.
Note a corrupt date will raise an exception when you
convert it to int to hand to this method.
Args:
dateint (int): Omnimeter datetime as int.
Returns:
tuple: Named tuple which breaks out as followws:
========== =====================
yy Last 2 digits of year
mm Month 1-12
dd Day 1-31
weekday Zero based weekday
hh Hour 0-23
minutes Minutes 0-59
ss Seconds 0-59
========== =====================
"""
date_str = str(dateint)
dt = namedtuple('EkmDate', ['yy', 'mm', 'dd', 'weekday', 'hh', 'minutes', 'ss'])
if len(date_str) != 14:
dt.yy = dt.mm = dt.dd = dt.weekday = dt.hh = dt.minutes = dt.ss = 0
return dt
dt.yy = int(date_str[0:2])
dt.mm = int(date_str[2:4])
dt.dd = int(date_str[4:6])
dt.weekday = int(date_str[6:8])
dt.hh = int(date_str[8:10])
dt.minutes = int(date_str[10:12])
dt.ss = int(date_str[12:14])
return dt |
Remove an observer from the meter update () chain. | def unregisterObserver(self, observer):
""" Remove an observer from the meter update() chain.
Args:
observer (MeterObserver): Subclassed MeterObserver.
"""
if observer in self.m_observers:
self.m_observers.remove(observer)
pass |
Initialize first tariff schedule: class: ~ekmmeters. SerialBlock. | def initSchd_1_to_4(self):
""" Initialize first tariff schedule :class:`~ekmmeters.SerialBlock`. """
self.m_schd_1_to_4["reserved_40"] = [6, FieldType.Hex, ScaleType.No, "", 0, False, False]
self.m_schd_1_to_4["Schedule_1_Period_1_Hour"] = [2, FieldType.Int, ScaleType.No, "", 0, False, True]
self.m_schd_1_to_4["Schedule_1_Period_1_Min"] = [2, FieldType.Int, ScaleType.No, "", 0, False, True]
self.m_schd_1_to_4["Schedule_1_Period_1_Tariff"] = [2, FieldType.Int, ScaleType.No, "", 0, False, True]
self.m_schd_1_to_4["Schedule_1_Period_2_Hour"] = [2, FieldType.Int, ScaleType.No, "", 0, False, True]
self.m_schd_1_to_4["Schedule_1_Period_2_Min"] = [2, FieldType.Int, ScaleType.No, "", 0, False, True]
self.m_schd_1_to_4["Schedule_1_Period_2_Tariff"] = [2, FieldType.Int, ScaleType.No, "", 0, False, True]
self.m_schd_1_to_4["Schedule_1_Period_3_Hour"] = [2, FieldType.Int, ScaleType.No, "", 0, False, True]
self.m_schd_1_to_4["Schedule_1_Period_3_Min"] = [2, FieldType.Int, ScaleType.No, "", 0, False, True]
self.m_schd_1_to_4["Schedule_1_Period_3_Tariff"] = [2, FieldType.Int, ScaleType.No, "", 0, False, True]
self.m_schd_1_to_4["Schedule_1_Period_4_Hour"] = [2, FieldType.Int, ScaleType.No, "", 0, False, True]
self.m_schd_1_to_4["Schedule_1_Period_4_Min"] = [2, FieldType.Int, ScaleType.No, "", 0, False, True]
self.m_schd_1_to_4["Schedule_1_Period_4_Tariff"] = [2, FieldType.Int, ScaleType.No, "", 0, False, True]
self.m_schd_1_to_4["reserved_41"] = [24, FieldType.Hex, ScaleType.No, "", 0, False, True]
self.m_schd_1_to_4["Schedule_2_Period_1_Hour"] = [2, FieldType.Int, ScaleType.No, "", 0, False, True]
self.m_schd_1_to_4["Schedule_2_Period_1_Min"] = [2, FieldType.Int, ScaleType.No, "", 0, False, True]
self.m_schd_1_to_4["Schedule_2_Period_1_Tariff"] = [2, FieldType.Int, ScaleType.No, "", 0, False, True]
self.m_schd_1_to_4["Schedule_2_Period_2_Hour"] = [2, FieldType.Int, ScaleType.No, "", 0, False, True]
self.m_schd_1_to_4["Schedule_2_Period_2_Min"] = [2, FieldType.Int, ScaleType.No, "", 0, False, True]
self.m_schd_1_to_4["Schedule_2_Period_2_Tariff"] = [2, FieldType.Int, ScaleType.No, "", 0, False, True]
self.m_schd_1_to_4["Schedule_2_Period_3_Hour"] = [2, FieldType.Int, ScaleType.No, "", 0, False, True]
self.m_schd_1_to_4["Schedule_2_Period_3_Min"] = [2, FieldType.Int, ScaleType.No, "", 0, False, True]
self.m_schd_1_to_4["Schedule_2_Period_3_Tariff"] = [2, FieldType.Int, ScaleType.No, "", 0, False, True]
self.m_schd_1_to_4["Schedule_2_Period_4_Hour"] = [2, FieldType.Int, ScaleType.No, "", 0, False, True]
self.m_schd_1_to_4["Schedule_2_Period_4_Min"] = [2, FieldType.Int, ScaleType.No, "", 0, False, True]
self.m_schd_1_to_4["Schedule_2_Period_4_Tariff"] = [2, FieldType.Int, ScaleType.No, "", 0, False, True]
self.m_schd_1_to_4["reserved_42"] = [24, FieldType.Hex, ScaleType.No, "", 0, False, True]
self.m_schd_1_to_4["Schedule_3_Period_1_Hour"] = [2, FieldType.Int, ScaleType.No, "", 0, False, True]
self.m_schd_1_to_4["Schedule_3_Period_1_Min"] = [2, FieldType.Int, ScaleType.No, "", 0, False, True]
self.m_schd_1_to_4["Schedule_3_Period_1_Tariff"] = [2, FieldType.Int, ScaleType.No, "", 0, False, True]
self.m_schd_1_to_4["Schedule_3_Period_2_Hour"] = [2, FieldType.Int, ScaleType.No, "", 0, False, True]
self.m_schd_1_to_4["Schedule_3_Period_2_Min"] = [2, FieldType.Int, ScaleType.No, "", 0, False, True]
self.m_schd_1_to_4["Schedule_3_Period_2_Tariff"] = [2, FieldType.Int, ScaleType.No, "", 0, False, True]
self.m_schd_1_to_4["Schedule_3_Period_3_Hour"] = [2, FieldType.Int, ScaleType.No, "", 0, False, True]
self.m_schd_1_to_4["Schedule_3_Period_3_Min"] = [2, FieldType.Int, ScaleType.No, "", 0, False, True]
self.m_schd_1_to_4["Schedule_3_Period_3_Tariff"] = [2, FieldType.Int, ScaleType.No, "", 0, False, True]
self.m_schd_1_to_4["Schedule_3_Period_4_Hour"] = [2, FieldType.Int, ScaleType.No, "", 0, False, True]
self.m_schd_1_to_4["Schedule_3_Period_4_Min"] = [2, FieldType.Int, ScaleType.No, "", 0, False, True]
self.m_schd_1_to_4["Schedule_3_Period_4_Tariff"] = [2, FieldType.Int, ScaleType.No, "", 0, False, True]
self.m_schd_1_to_4["reserved_43"] = [24, FieldType.Hex, ScaleType.No, "", 0, False, True]
self.m_schd_1_to_4["Schedule_4_Period_1_Hour"] = [2, FieldType.Int, ScaleType.No, "", 0, False, True]
self.m_schd_1_to_4["Schedule_4_Period_1_Min"] = [2, FieldType.Int, ScaleType.No, "", 0, False, True]
self.m_schd_1_to_4["Schedule_4_Period_1_Tariff"] = [2, FieldType.Int, ScaleType.No, "", 0, False, True]
self.m_schd_1_to_4["Schedule_4_Period_2_Hour"] = [2, FieldType.Int, ScaleType.No, "", 0, False, True]
self.m_schd_1_to_4["Schedule_4_Period_2_Min"] = [2, FieldType.Int, ScaleType.No, "", 0, False, True]
self.m_schd_1_to_4["Schedule_4_Period_2_Tariff"] = [2, FieldType.Int, ScaleType.No, "", 0, False, True]
self.m_schd_1_to_4["Schedule_4_Period_3_Hour"] = [2, FieldType.Int, ScaleType.No, "", 0, False, True]
self.m_schd_1_to_4["Schedule_4_Period_3_Min"] = [2, FieldType.Int, ScaleType.No, "", 0, False, True]
self.m_schd_1_to_4["Schedule_4_Period_3_Tariff"] = [2, FieldType.Int, ScaleType.No, "", 0, False, True]
self.m_schd_1_to_4["Schedule_4_Period_4_Hour"] = [2, FieldType.Int, ScaleType.No, "", 0, False, True]
self.m_schd_1_to_4["Schedule_4_Period_4_Min"] = [2, FieldType.Int, ScaleType.No, "", 0, False, True]
self.m_schd_1_to_4["Schedule_4_Period_4_Tariff"] = [2, FieldType.Int, ScaleType.No, "", 0, False, True]
self.m_schd_1_to_4["reserved_44"] = [79, FieldType.Hex, ScaleType.No, "", 0, False, True]
self.m_schd_1_to_4["crc16"] = [2, FieldType.Hex, ScaleType.No, "", 0, False, False]
pass |
Initialize second ( and last ) tariff schedule: class: ~ekmmeters. SerialBlock. | def initSchd_5_to_6(self):
""" Initialize second(and last) tariff schedule :class:`~ekmmeters.SerialBlock`. """
self.m_schd_5_to_6["reserved_30"] = [6, FieldType.Hex, ScaleType.No, "", 0, False, False]
self.m_schd_5_to_6["Schedule_5_Period_1_Hour"] = [2, FieldType.Int, ScaleType.No, "", 0, False, True]
self.m_schd_5_to_6["Schedule_5_Period_1_Min"] = [2, FieldType.Int, ScaleType.No, "", 0, False, True]
self.m_schd_5_to_6["Schedule_5_Period_1_Tariff"] = [2, FieldType.Int, ScaleType.No, "", 0, False, True]
self.m_schd_5_to_6["Schedule_5_Period_2_Hour"] = [2, FieldType.Int, ScaleType.No, "", 0, False, True]
self.m_schd_5_to_6["Schedule_5_Period_2_Min"] = [2, FieldType.Int, ScaleType.No, "", 0, False, True]
self.m_schd_5_to_6["Schedule_5_Period_2_Tariff"] = [2, FieldType.Int, ScaleType.No, "", 0, False, True]
self.m_schd_5_to_6["Schedule_5_Period_3_Hour"] = [2, FieldType.Int, ScaleType.No, "", 0, False, True]
self.m_schd_5_to_6["Schedule_5_Period_3_Min"] = [2, FieldType.Int, ScaleType.No, "", 0, False, True]
self.m_schd_5_to_6["Schedule_5_Period_3_Tariff"] = [2, FieldType.Int, ScaleType.No, "", 0, False, True]
self.m_schd_5_to_6["Schedule_5_Period_4_Hour"] = [2, FieldType.Int, ScaleType.No, "", 0, False, True]
self.m_schd_5_to_6["Schedule_5_Period_4_Min"] = [2, FieldType.Int, ScaleType.No, "", 0, False, True]
self.m_schd_5_to_6["Schedule_5_Period_4_Tariff"] = [2, FieldType.Int, ScaleType.No, "", 0, False, True]
self.m_schd_5_to_6["reserved_31"] = [24, FieldType.Hex, ScaleType.No, "", 0, False, True]
self.m_schd_5_to_6["Schedule_6_Period_1_Hour"] = [2, FieldType.Int, ScaleType.No, "", 0, False, True]
self.m_schd_5_to_6["Schedule_6_Period_1_Min"] = [2, FieldType.Int, ScaleType.No, "", 0, False, True]
self.m_schd_5_to_6["Schedule_6_Period_1_Tariff"] = [2, FieldType.Int, ScaleType.No, "", 0, False, True]
self.m_schd_5_to_6["Schedule_6_Period_2_Hour"] = [2, FieldType.Int, ScaleType.No, "", 0, False, True]
self.m_schd_5_to_6["Schedule_6_Period_2_Min"] = [2, FieldType.Int, ScaleType.No, "", 0, False, True]
self.m_schd_5_to_6["Schedule_6_Period_2_Tariff"] = [2, FieldType.Int, ScaleType.No, "", 0, False, True]
self.m_schd_5_to_6["Schedule_6_Period_3_Hour"] = [2, FieldType.Int, ScaleType.No, "", 0, False, True]
self.m_schd_5_to_6["Schedule_6_Period_3_Min"] = [2, FieldType.Int, ScaleType.No, "", 0, False, True]
self.m_schd_5_to_6["Schedule_6_Period_3_Tariff"] = [2, FieldType.Int, ScaleType.No, "", 0, False, True]
self.m_schd_5_to_6["Schedule_6_Period_4_Hour"] = [2, FieldType.Int, ScaleType.No, "", 0, False, True]
self.m_schd_5_to_6["Schedule_6_Period_4_Min"] = [2, FieldType.Int, ScaleType.No, "", 0, False, True]
self.m_schd_5_to_6["Schedule_6_Period_4_Tariff"] = [2, FieldType.Int, ScaleType.No, "", 0, False, True]
self.m_schd_5_to_6["reserved_32"] = [24, FieldType.Hex, ScaleType.No, "", 0, False, True]
self.m_schd_5_to_6["reserved_33"] = [24, FieldType.Hex, ScaleType.No, "", 0, False, True]
self.m_schd_5_to_6["reserved_34"] = [24, FieldType.Hex, ScaleType.No, "", 0, False, True]
self.m_schd_5_to_6["reserved_35"] = [24, FieldType.Hex, ScaleType.No, "", 0, False, True]
self.m_schd_5_to_6["reserved_36"] = [79, FieldType.Hex, ScaleType.No, "", 0, False, True]
self.m_schd_5_to_6["crc16"] = [2, FieldType.Hex, ScaleType.No, "", 0, False, False]
pass |
Return the requested tariff schedule: class: ~ekmmeters. SerialBlock for meter. | def getSchedulesBuffer(self, period_group):
""" Return the requested tariff schedule :class:`~ekmmeters.SerialBlock` for meter.
Args:
period_group (int): A :class:`~ekmmeters.ReadSchedules` value.
Returns:
SerialBlock: The requested tariff schedules for meter.
"""
empty_return = SerialBlock()
if period_group == ReadSchedules.Schedules_1_To_4:
return self.m_schd_1_to_4
elif period_group == ReadSchedules.Schedules_5_To_6:
return self.m_schd_5_to_6
else:
return empty_return |
Initialize holidays: class: ~ekmmeters. SerialBlock | def initHldyDates(self):
""" Initialize holidays :class:`~ekmmeters.SerialBlock` """
self.m_hldy["reserved_20"] = [6, FieldType.Hex, ScaleType.No, "", 0, False, False]
self.m_hldy["Holiday_1_Mon"] = [2, FieldType.Int, ScaleType.No, "", 0, False, True]
self.m_hldy["Holiday_1_Day"] = [2, FieldType.Int, ScaleType.No, "", 0, False, True]
self.m_hldy["Holiday_2_Mon"] = [2, FieldType.Int, ScaleType.No, "", 0, False, True]
self.m_hldy["Holiday_2_Day"] = [2, FieldType.Int, ScaleType.No, "", 0, False, True]
self.m_hldy["Holiday_3_Mon"] = [2, FieldType.Int, ScaleType.No, "", 0, False, True]
self.m_hldy["Holiday_3_Day"] = [2, FieldType.Int, ScaleType.No, "", 0, False, True]
self.m_hldy["Holiday_4_Mon"] = [2, FieldType.Int, ScaleType.No, "", 0, False, True]
self.m_hldy["Holiday_4_Day"] = [2, FieldType.Int, ScaleType.No, "", 0, False, True]
self.m_hldy["Holiday_5_Mon"] = [2, FieldType.Int, ScaleType.No, "", 0, False, True]
self.m_hldy["Holiday_5_Day"] = [2, FieldType.Int, ScaleType.No, "", 0, False, True]
self.m_hldy["Holiday_6_Mon"] = [2, FieldType.Int, ScaleType.No, "", 0, False, True]
self.m_hldy["Holiday_6_Day"] = [2, FieldType.Int, ScaleType.No, "", 0, False, True]
self.m_hldy["Holiday_7_Mon"] = [2, FieldType.Int, ScaleType.No, "", 0, False, True]
self.m_hldy["Holiday_7_Day"] = [2, FieldType.Int, ScaleType.No, "", 0, False, True]
self.m_hldy["Holiday_8_Mon"] = [2, FieldType.Int, ScaleType.No, "", 0, False, True]
self.m_hldy["Holiday_8_Day"] = [2, FieldType.Int, ScaleType.No, "", 0, False, True]
self.m_hldy["Holiday_9_Mon"] = [2, FieldType.Int, ScaleType.No, "", 0, False, True]
self.m_hldy["Holiday_9_Day"] = [2, FieldType.Int, ScaleType.No, "", 0, False, True]
self.m_hldy["Holiday_10_Mon"] = [2, FieldType.Int, ScaleType.No, "", 0, False, True]
self.m_hldy["Holiday_10_Day"] = [2, FieldType.Int, ScaleType.No, "", 0, False, True]
self.m_hldy["Holiday_11_Mon"] = [2, FieldType.Int, ScaleType.No, "", 0, False, True]
self.m_hldy["Holiday_11_Day"] = [2, FieldType.Int, ScaleType.No, "", 0, False, True]
self.m_hldy["Holiday_12_Mon"] = [2, FieldType.Int, ScaleType.No, "", 0, False, True]
self.m_hldy["Holiday_12_Day"] = [2, FieldType.Int, ScaleType.No, "", 0, False, True]
self.m_hldy["Holiday_13_Mon"] = [2, FieldType.Int, ScaleType.No, "", 0, False, True]
self.m_hldy["Holiday_13_Day"] = [2, FieldType.Int, ScaleType.No, "", 0, False, True]
self.m_hldy["Holiday_14_Mon"] = [2, FieldType.Int, ScaleType.No, "", 0, False, True]
self.m_hldy["Holiday_14_Day"] = [2, FieldType.Int, ScaleType.No, "", 0, False, True]
self.m_hldy["Holiday_15_Mon"] = [2, FieldType.Int, ScaleType.No, "", 0, False, True]
self.m_hldy["Holiday_15_Day"] = [2, FieldType.Int, ScaleType.No, "", 0, False, True]
self.m_hldy["Holiday_16_Mon"] = [2, FieldType.Int, ScaleType.No, "", 0, False, True]
self.m_hldy["Holiday_16_Day"] = [2, FieldType.Int, ScaleType.No, "", 0, False, True]
self.m_hldy["Holiday_17_Mon"] = [2, FieldType.Int, ScaleType.No, "", 0, False, True]
self.m_hldy["Holiday_17_Day"] = [2, FieldType.Int, ScaleType.No, "", 0, False, True]
self.m_hldy["Holiday_18_Mon"] = [2, FieldType.Int, ScaleType.No, "", 0, False, True]
self.m_hldy["Holiday_18_Day"] = [2, FieldType.Int, ScaleType.No, "", 0, False, True]
self.m_hldy["Holiday_19_Mon"] = [2, FieldType.Int, ScaleType.No, "", 0, False, True]
self.m_hldy["Holiday_19_Day"] = [2, FieldType.Int, ScaleType.No, "", 0, False, True]
self.m_hldy["Holiday_20_Mon"] = [2, FieldType.Int, ScaleType.No, "", 0, False, True]
self.m_hldy["Holiday_20_Day"] = [2, FieldType.Int, ScaleType.No, "", 0, False, True]
self.m_hldy["Weekend_Schd"] = [2, FieldType.Int, ScaleType.No, "", 0, False, True]
self.m_hldy["Holiday_Schd"] = [2, FieldType.Int, ScaleType.No, "", 0, False, True]
self.m_hldy["reserved_21"] = [163, FieldType.Hex, ScaleType.No, "", 0, False, False]
self.m_hldy["crc16"] = [2, FieldType.Hex, ScaleType.No, "", 0, False, False]
pass |
Initialize first month tariff: class: ~ekmmeters. SerialBlock for meter | def initMons(self):
""" Initialize first month tariff :class:`~ekmmeters.SerialBlock` for meter """
self.m_mons["reserved_echo_cmd"] = [6, FieldType.Hex, ScaleType.No, "", 0, False, False]
self.m_mons["Month_1_Tot"] = [8, FieldType.Float, ScaleType.KWH, "", 0, False, False]
self.m_mons["Month_1_Tariff_1"] = [8, FieldType.Float, ScaleType.KWH, "", 0, False, False]
self.m_mons["Month_1_Tariff_2"] = [8, FieldType.Float, ScaleType.KWH, "", 0, False, False]
self.m_mons["Month_1_Tariff_3"] = [8, FieldType.Float, ScaleType.KWH, "", 0, False, False]
self.m_mons["Month_1_Tariff_4"] = [8, FieldType.Float, ScaleType.KWH, "", 0, False, False]
self.m_mons["Month_2_Tot"] = [8, FieldType.Float, ScaleType.KWH, "", 0, False, False]
self.m_mons["Month_2_Tariff_1"] = [8, FieldType.Float, ScaleType.KWH, "", 0, False, False]
self.m_mons["Month_2_Tariff_2"] = [8, FieldType.Float, ScaleType.KWH, "", 0, False, False]
self.m_mons["Month_2_Tariff_3"] = [8, FieldType.Float, ScaleType.KWH, "", 0, False, False]
self.m_mons["Month_2_Tariff_4"] = [8, FieldType.Float, ScaleType.KWH, "", 0, False, False]
self.m_mons["Month_3_Tot"] = [8, FieldType.Float, ScaleType.KWH, "", 0, False, False]
self.m_mons["Month_3_Tariff_1"] = [8, FieldType.Float, ScaleType.KWH, "", 0, False, False]
self.m_mons["Month_3_Tariff_2"] = [8, FieldType.Float, ScaleType.KWH, "", 0, False, False]
self.m_mons["Month_3_Tariff_3"] = [8, FieldType.Float, ScaleType.KWH, "", 0, False, False]
self.m_mons["Month_3_Tariff_4"] = [8, FieldType.Float, ScaleType.KWH, "", 0, False, False]
self.m_mons["Month_4_Tot"] = [8, FieldType.Float, ScaleType.KWH, "", 0, False, False]
self.m_mons["Month_4_Tariff_1"] = [8, FieldType.Float, ScaleType.KWH, "", 0, False, False]
self.m_mons["Month_4_Tariff_2"] = [8, FieldType.Float, ScaleType.KWH, "", 0, False, False]
self.m_mons["Month_4_Tariff_3"] = [8, FieldType.Float, ScaleType.KWH, "", 0, False, False]
self.m_mons["Month_4_Tariff_4"] = [8, FieldType.Float, ScaleType.KWH, "", 0, False, False]
self.m_mons["Month_5_Tot"] = [8, FieldType.Float, ScaleType.KWH, "", 0, False, False]
self.m_mons["Month_5_Tariff_1"] = [8, FieldType.Float, ScaleType.KWH, "", 0, False, False]
self.m_mons["Month_5_Tariff_2"] = [8, FieldType.Float, ScaleType.KWH, "", 0, False, False]
self.m_mons["Month_5_Tariff_3"] = [8, FieldType.Float, ScaleType.KWH, "", 0, False, False]
self.m_mons["Month_5_Tariff_4"] = [8, FieldType.Float, ScaleType.KWH, "", 0, False, False]
self.m_mons["Month_6_Tot"] = [8, FieldType.Float, ScaleType.KWH, "", 0, False, False]
self.m_mons["Month_6_Tariff_1"] = [8, FieldType.Float, ScaleType.KWH, "", 0, False, False]
self.m_mons["Month_6_Tariff_2"] = [8, FieldType.Float, ScaleType.KWH, "", 0, False, False]
self.m_mons["Month_6_Tariff_3"] = [8, FieldType.Float, ScaleType.KWH, "", 0, False, False]
self.m_mons["Month_6_Tariff_4"] = [8, FieldType.Float, ScaleType.KWH, "", 0, False, False]
self.m_mons["reserved_1"] = [7, FieldType.Hex, ScaleType.No, "", 0, False, False]
self.m_mons["crc16"] = [2, FieldType.Hex, ScaleType.No, "", 0, False, False]
pass |
Initialize second ( and last ) month tarifff: class: ~ekmmeters. SerialBlock for meter. | def initRevMons(self):
""" Initialize second (and last) month tarifff :class:`~ekmmeters.SerialBlock` for meter. """
self.m_rev_mons["reserved_echo_cmd"] = [6, FieldType.Hex, ScaleType.No, "", 0, False, False]
self.m_rev_mons["Month_1_Tot"] = [8, FieldType.Float, ScaleType.KWH, "", 0, False, False]
self.m_rev_mons["Month_1_Tariff_1"] = [8, FieldType.Float, ScaleType.KWH, "", 0, False, False]
self.m_rev_mons["Month_1_Tariff_2"] = [8, FieldType.Float, ScaleType.KWH, "", 0, False, False]
self.m_rev_mons["Month_1_Tariff_3"] = [8, FieldType.Float, ScaleType.KWH, "", 0, False, False]
self.m_rev_mons["Month_1_Tariff_4"] = [8, FieldType.Float, ScaleType.KWH, "", 0, False, False]
self.m_rev_mons["Month_2_Tot"] = [8, FieldType.Float, ScaleType.KWH, "", 0, False, False]
self.m_rev_mons["Month_2_Tariff_1"] = [8, FieldType.Float, ScaleType.KWH, "", 0, False, False]
self.m_rev_mons["Month_2_Tariff_2"] = [8, FieldType.Float, ScaleType.KWH, "", 0, False, False]
self.m_rev_mons["Month_2_Tariff_3"] = [8, FieldType.Float, ScaleType.KWH, "", 0, False, False]
self.m_rev_mons["Month_2_Tariff_4"] = [8, FieldType.Float, ScaleType.KWH, "", 0, False, False]
self.m_rev_mons["Month_3_Tot"] = [8, FieldType.Float, ScaleType.KWH, "", 0, False, False]
self.m_rev_mons["Month_3_Tariff_1"] = [8, FieldType.Float, ScaleType.KWH, "", 0, False, False]
self.m_rev_mons["Month_3_Tariff_2"] = [8, FieldType.Float, ScaleType.KWH, "", 0, False, False]
self.m_rev_mons["Month_3_Tariff_3"] = [8, FieldType.Float, ScaleType.KWH, "", 0, False, False]
self.m_rev_mons["Month_3_Tariff_4"] = [8, FieldType.Float, ScaleType.KWH, "", 0, False, False]
self.m_rev_mons["Month_4_Tot"] = [8, FieldType.Float, ScaleType.KWH, "", 0, False, False]
self.m_rev_mons["Month_4_Tariff_1"] = [8, FieldType.Float, ScaleType.KWH, "", 0, False, False]
self.m_rev_mons["Month_4_Tariff_2"] = [8, FieldType.Float, ScaleType.KWH, "", 0, False, False]
self.m_rev_mons["Month_4_Tariff_3"] = [8, FieldType.Float, ScaleType.KWH, "", 0, False, False]
self.m_rev_mons["Month_4_Tariff_4"] = [8, FieldType.Float, ScaleType.KWH, "", 0, False, False]
self.m_rev_mons["Month_5_Tot"] = [8, FieldType.Float, ScaleType.KWH, "", 0, False, False]
self.m_rev_mons["Month_5_Tariff_1"] = [8, FieldType.Float, ScaleType.KWH, "", 0, False, False]
self.m_rev_mons["Month_5_Tariff_2"] = [8, FieldType.Float, ScaleType.KWH, "", 0, False, False]
self.m_rev_mons["Month_5_Tariff_3"] = [8, FieldType.Float, ScaleType.KWH, "", 0, False, False]
self.m_rev_mons["Month_5_Tariff_4"] = [8, FieldType.Float, ScaleType.KWH, "", 0, False, False]
self.m_rev_mons["Month_6_Tot"] = [8, FieldType.Float, ScaleType.KWH, "", 0, False, False]
self.m_rev_mons["Month_6_Tariff_1"] = [8, FieldType.Float, ScaleType.KWH, "", 0, False, False]
self.m_rev_mons["Month_6_Tariff_2"] = [8, FieldType.Float, ScaleType.KWH, "", 0, False, False]
self.m_rev_mons["Month_6_Tariff_3"] = [8, FieldType.Float, ScaleType.KWH, "", 0, False, False]
self.m_rev_mons["Month_6_Tariff_4"] = [8, FieldType.Float, ScaleType.KWH, "", 0, False, False]
self.m_rev_mons["reserved_1"] = [7, FieldType.Hex, ScaleType.No, "", 0, False, False]
self.m_rev_mons["crc16"] = [2, FieldType.Hex, ScaleType.No, "", 0, False, False]
pass |
Get the months tariff SerialBlock for meter. | def getMonthsBuffer(self, direction):
""" Get the months tariff SerialBlock for meter.
Args:
direction (int): A :class:`~ekmmeters.ReadMonths` value.
Returns:
SerialBlock: Requested months tariffs buffer.
"""
if direction == ReadMonths.kWhReverse:
return self.m_rev_mons
# default direction == ReadMonths.kWh
return self.m_mons |
Serial set time with day of week calculation. | def setTime(self, yy, mm, dd, hh, minutes, ss, password="00000000"):
""" Serial set time with day of week calculation.
Args:
yy (int): Last two digits of year.
mm (int): Month 1-12.
dd (int): Day 1-31
hh (int): Hour 0 to 23.
minutes (int): Minutes 0 to 59.
ss (int): Seconds 0 to 59.
password (str): Optional password.
Returns:
bool: True on completion and ACK.
"""
result = False
self.setContext("setTime")
try:
if mm < 1 or mm > 12:
self.writeCmdMsg("Month must be between 1 and 12")
self.setContext("")
return result
if dd < 1 or dd > 31:
self.writeCmdMsg("Day must be between 1 and 31")
self.setContext("")
return result
if hh < 0 or hh > 23:
self.writeCmdMsg("Hour must be between 0 and 23, inclusive")
self.setContext("")
return result
if minutes < 0 or minutes > 59:
self.writeCmdMsg("Minutes must be between 0 and 59, inclusive")
self.setContext("")
return result
if ss < 0 or ss > 59:
self.writeCmdMsg("Seconds must be between 0 and 59, inclusive")
self.setContext("")
return result
if len(password) != 8:
self.writeCmdMsg("Invalid password length.")
self.setContext("")
return result
if not self.request(False):
self.writeCmdMsg("Bad read CRC on setting")
else:
if not self.serialCmdPwdAuth(password):
self.writeCmdMsg("Password failure")
else:
dt_buf = datetime.datetime(int(yy), int(mm), int(dd), int(hh), int(minutes), int(ss))
ekm_log("Writing Date and Time " + dt_buf.strftime("%Y-%m-%d %H:%M"))
dayofweek = dt_buf.date().isoweekday()
ekm_log("Calculated weekday " + str(dayofweek))
req_str = "015731023030363028"
req_str += binascii.hexlify(str(yy)[-2:])
req_str += binascii.hexlify(str(mm).zfill(2))
req_str += binascii.hexlify(str(dd).zfill(2))
req_str += binascii.hexlify(str(dayofweek).zfill(2))
req_str += binascii.hexlify(str(hh).zfill(2))
req_str += binascii.hexlify(str(minutes).zfill(2))
req_str += binascii.hexlify(str(ss).zfill(2))
req_str += "2903"
req_str += self.calc_crc16(req_str[2:].decode("hex"))
self.m_serial_port.write(req_str.decode("hex"))
if self.m_serial_port.getResponse(self.getContext()).encode("hex") == "06":
self.writeCmdMsg("Success(setTime): 06 returned.")
result = True
self.serialPostEnd()
except:
ekm_log(traceback.format_exc(sys.exc_info()))
self.setContext("")
return result |
Serial call to set CT ratio for attached inductive pickup. | def setCTRatio(self, new_ct, password="00000000"):
""" Serial call to set CT ratio for attached inductive pickup.
Args:
new_ct (int): A :class:`~ekmmeters.CTRatio` value, a legal amperage setting.
password (str): Optional password.
Returns:
bool: True on completion with ACK.
"""
ret = False
self.setContext("setCTRatio")
try:
self.clearCmdMsg()
if ((new_ct != CTRatio.Amps_100) and (new_ct != CTRatio.Amps_200) and
(new_ct != CTRatio.Amps_400) and (new_ct != CTRatio.Amps_600) and
(new_ct != CTRatio.Amps_800) and (new_ct != CTRatio.Amps_1000) and
(new_ct != CTRatio.Amps_1200) and (new_ct != CTRatio.Amps_1500) and
(new_ct != CTRatio.Amps_2000) and (new_ct != CTRatio.Amps_3000) and
(new_ct != CTRatio.Amps_4000) and (new_ct != CTRatio.Amps_5000)):
self.writeCmdMsg("Legal CT Ratios: 100, 200, 400, 600, " +
"800, 1000, 1200, 1500, 2000, 3000, 4000 and 5000")
self.setContext("")
return ret
if len(password) != 8:
self.writeCmdMsg("Invalid password length.")
self.setContext("")
return ret
if not self.request(False):
self.writeCmdMsg("Bad read CRC on setting")
else:
if not self.serialCmdPwdAuth(password):
self.writeCmdMsg("Password failure")
else:
req_str = "015731023030443028" + binascii.hexlify(str(new_ct).zfill(4)) + "2903"
req_str += self.calc_crc16(req_str[2:].decode("hex"))
self.m_serial_port.write(req_str.decode("hex"))
if self.m_serial_port.getResponse(self.getContext()).encode("hex") == "06":
self.writeCmdMsg("Success(setCTRatio): 06 returned.")
ret = True
self.serialPostEnd()
except:
ekm_log(traceback.format_exc(sys.exc_info()))
self.setContext("")
return ret |
Assign one schedule tariff period to meter bufffer. | def assignSchedule(self, schedule, period, hour, minute, tariff):
""" Assign one schedule tariff period to meter bufffer.
Args:
schedule (int): A :class:`~ekmmeters.Schedules` value or in range(Extents.Schedules).
tariff (int): :class:`~ekmmeters.Tariffs` value or in range(Extents.Tariffs).
hour (int): Hour from 0-23.
minute (int): Minute from 0-59.
tariff (int): Rate value.
Returns:
bool: True on completed assignment.
"""
if ((schedule not in range(Extents.Schedules)) or
(period not in range(Extents.Tariffs)) or
(hour < 0) or (hour > 23) or (minute < 0) or
(minute > 59) or (tariff < 0)):
ekm_log("Out of bounds in Schedule_" + str(schedule + 1))
return False
period += 1
idx_min = "Min_" + str(period)
idx_hour = "Hour_" + str(period)
idx_rate = "Tariff_" + str(period)
if idx_min not in self.m_schedule_params:
ekm_log("Incorrect index: " + idx_min)
return False
if idx_hour not in self.m_schedule_params:
ekm_log("Incorrect index: " + idx_hour)
return False
if idx_rate not in self.m_schedule_params:
ekm_log("Incorrect index: " + idx_rate)
return False
self.m_schedule_params[idx_rate] = tariff
self.m_schedule_params[idx_hour] = hour
self.m_schedule_params[idx_min] = minute
self.m_schedule_params['Schedule'] = schedule
return True |
Define a single season and assign a schedule | def assignSeasonSchedule(self, season, month, day, schedule):
""" Define a single season and assign a schedule
Args:
season (int): A :class:`~ekmmeters.Seasons` value or in range(Extent.Seasons).
month (int): Month 1-12.
day (int): Day 1-31.
schedule (int): A :class:`~ekmmeters.LCDItems` value or in range(Extent.Schedules).
Returns:
bool: True on completion and ACK.
"""
season += 1
schedule += 1
if ((season < 1) or (season > Extents.Seasons) or (schedule < 1) or
(schedule > Extents.Schedules) or (month > 12) or (month < 0) or
(day < 0) or (day > 31)):
ekm_log("Out of bounds: month " + str(month) + " day " + str(day) +
" schedule " + str(schedule) + " season " + str(season))
return False
idx_mon = "Season_" + str(season) + "_Start_Day"
idx_day = "Season_" + str(season) + "_Start_Month"
idx_schedule = "Season_" + str(season) + "_Schedule"
if idx_mon not in self.m_seasons_sched_params:
ekm_log("Incorrect index: " + idx_mon)
return False
if idx_day not in self.m_seasons_sched_params:
ekm_log("Incorrect index: " + idx_day)
return False
if idx_schedule not in self.m_seasons_sched_params:
ekm_log("Incorrect index: " + idx_schedule)
return False
self.m_seasons_sched_params[idx_mon] = month
self.m_seasons_sched_params[idx_day] = day
self.m_seasons_sched_params[idx_schedule] = schedule
return True |
Serial command to set seasons table. | def setSeasonSchedules(self, cmd_dict=None, password="00000000"):
""" Serial command to set seasons table.
If no dictionary is passed, the meter object buffer is used.
Args:
cmd_dict (dict): Optional dictionary of season schedules.
password (str): Optional password
Returns:
bool: True on completion and ACK.
"""
result = False
self.setContext("setSeasonSchedules")
if not cmd_dict:
cmd_dict = self.m_seasons_sched_params
try:
if not self.request(False):
self.writeCmdMsg("Bad read CRC on setting")
else:
if not self.serialCmdPwdAuth(password):
self.writeCmdMsg("Password failure")
else:
req_table = ""
req_table += binascii.hexlify(str(cmd_dict["Season_1_Start_Month"]).zfill(2))
req_table += binascii.hexlify(str(cmd_dict["Season_1_Start_Day"]).zfill(2))
req_table += binascii.hexlify(str(cmd_dict["Season_1_Schedule"]).zfill(2))
req_table += binascii.hexlify(str(cmd_dict["Season_2_Start_Month"]).zfill(2))
req_table += binascii.hexlify(str(cmd_dict["Season_2_Start_Day"]).zfill(2))
req_table += binascii.hexlify(str(cmd_dict["Season_2_Schedule"]).zfill(2))
req_table += binascii.hexlify(str(cmd_dict["Season_3_Start_Month"]).zfill(2))
req_table += binascii.hexlify(str(cmd_dict["Season_3_Start_Day"]).zfill(2))
req_table += binascii.hexlify(str(cmd_dict["Season_3_Schedule"]).zfill(2))
req_table += binascii.hexlify(str(cmd_dict["Season_4_Start_Month"]).zfill(2))
req_table += binascii.hexlify(str(cmd_dict["Season_4_Start_Day"]).zfill(2))
req_table += binascii.hexlify(str(cmd_dict["Season_4_Schedule"]).zfill(2))
req_table += binascii.hexlify(str(0).zfill(24))
req_str = "015731023030383028" + req_table + "2903"
req_str += self.calc_crc16(req_str[2:].decode("hex"))
self.m_serial_port.write(req_str.decode("hex"))
if self.m_serial_port.getResponse(self.getContext()).encode("hex") == "06":
self.writeCmdMsg("Success(setSeasonSchedules): 06 returned.")
result = True
self.serialPostEnd()
except:
ekm_log(traceback.format_exc(sys.exc_info()))
self.setContext("")
return result |
Set a singe holiday day and month in object buffer. | def assignHolidayDate(self, holiday, month, day):
""" Set a singe holiday day and month in object buffer.
There is no class style enum for holidays.
Args:
holiday (int): 0-19 or range(Extents.Holidays).
month (int): Month 1-12.
day (int): Day 1-31
Returns:
bool: True on completion.
"""
holiday += 1
if (month > 12) or (month < 0) or (day > 31) or (day < 0) or (holiday < 1) or (holiday > Extents.Holidays):
ekm_log("Out of bounds: month " + str(month) + " day " + str(day) + " holiday " + str(holiday))
return False
day_str = "Holiday_" + str(holiday) + "_Day"
mon_str = "Holiday_" + str(holiday) + "_Month"
if day_str not in self.m_holiday_date_params:
ekm_log("Incorrect index: " + day_str)
return False
if mon_str not in self.m_holiday_date_params:
ekm_log("Incorrect index: " + mon_str)
return False
self.m_holiday_date_params[day_str] = day
self.m_holiday_date_params[mon_str] = month
return True |
Serial call to set holiday list. | def setHolidayDates(self, cmd_dict=None, password="00000000"):
""" Serial call to set holiday list.
If a buffer dictionary is not supplied, the method will use
the class object buffer populated with assignHolidayDate.
Args:
cmd_dict (dict): Optional dictionary of holidays.
password (str): Optional password.
Returns:
bool: True on completion.
"""
result = False
self.setContext("setHolidayDates")
if not cmd_dict:
cmd_dict = self.m_holiday_date_params
try:
if not self.request(False):
self.writeCmdMsg("Bad read CRC on setting")
else:
if not self.serialCmdPwdAuth(password):
self.writeCmdMsg("Password failure")
else:
req_table = ""
req_table += binascii.hexlify(str(cmd_dict["Holiday_1_Month"]).zfill(2))
req_table += binascii.hexlify(str(cmd_dict["Holiday_1_Day"]).zfill(2))
req_table += binascii.hexlify(str(cmd_dict["Holiday_2_Month"]).zfill(2))
req_table += binascii.hexlify(str(cmd_dict["Holiday_2_Day"]).zfill(2))
req_table += binascii.hexlify(str(cmd_dict["Holiday_3_Month"]).zfill(2))
req_table += binascii.hexlify(str(cmd_dict["Holiday_3_Day"]).zfill(2))
req_table += binascii.hexlify(str(cmd_dict["Holiday_4_Month"]).zfill(2))
req_table += binascii.hexlify(str(cmd_dict["Holiday_4_Day"]).zfill(2))
req_table += binascii.hexlify(str(cmd_dict["Holiday_5_Month"]).zfill(2))
req_table += binascii.hexlify(str(cmd_dict["Holiday_5_Day"]).zfill(2))
req_table += binascii.hexlify(str(cmd_dict["Holiday_6_Month"]).zfill(2))
req_table += binascii.hexlify(str(cmd_dict["Holiday_6_Day"]).zfill(2))
req_table += binascii.hexlify(str(cmd_dict["Holiday_7_Month"]).zfill(2))
req_table += binascii.hexlify(str(cmd_dict["Holiday_7_Day"]).zfill(2))
req_table += binascii.hexlify(str(cmd_dict["Holiday_8_Month"]).zfill(2))
req_table += binascii.hexlify(str(cmd_dict["Holiday_8_Day"]).zfill(2))
req_table += binascii.hexlify(str(cmd_dict["Holiday_9_Month"]).zfill(2))
req_table += binascii.hexlify(str(cmd_dict["Holiday_9_Day"]).zfill(2))
req_table += binascii.hexlify(str(cmd_dict["Holiday_10_Month"]).zfill(2))
req_table += binascii.hexlify(str(cmd_dict["Holiday_10_Day"]).zfill(2))
req_table += binascii.hexlify(str(cmd_dict["Holiday_11_Month"]).zfill(2))
req_table += binascii.hexlify(str(cmd_dict["Holiday_11_Day"]).zfill(2))
req_table += binascii.hexlify(str(cmd_dict["Holiday_12_Month"]).zfill(2))
req_table += binascii.hexlify(str(cmd_dict["Holiday_12_Day"]).zfill(2))
req_table += binascii.hexlify(str(cmd_dict["Holiday_13_Month"]).zfill(2))
req_table += binascii.hexlify(str(cmd_dict["Holiday_13_Day"]).zfill(2))
req_table += binascii.hexlify(str(cmd_dict["Holiday_14_Month"]).zfill(2))
req_table += binascii.hexlify(str(cmd_dict["Holiday_14_Day"]).zfill(2))
req_table += binascii.hexlify(str(cmd_dict["Holiday_15_Month"]).zfill(2))
req_table += binascii.hexlify(str(cmd_dict["Holiday_15_Day"]).zfill(2))
req_table += binascii.hexlify(str(cmd_dict["Holiday_16_Month"]).zfill(2))
req_table += binascii.hexlify(str(cmd_dict["Holiday_16_Day"]).zfill(2))
req_table += binascii.hexlify(str(cmd_dict["Holiday_17_Month"]).zfill(2))
req_table += binascii.hexlify(str(cmd_dict["Holiday_17_Day"]).zfill(2))
req_table += binascii.hexlify(str(cmd_dict["Holiday_18_Month"]).zfill(2))
req_table += binascii.hexlify(str(cmd_dict["Holiday_18_Day"]).zfill(2))
req_table += binascii.hexlify(str(cmd_dict["Holiday_19_Month"]).zfill(2))
req_table += binascii.hexlify(str(cmd_dict["Holiday_19_Day"]).zfill(2))
req_table += binascii.hexlify(str(cmd_dict["Holiday_20_Month"]).zfill(2))
req_table += binascii.hexlify(str(cmd_dict["Holiday_20_Day"]).zfill(2))
req_str = "015731023030423028" + req_table + "2903"
req_str += self.calc_crc16(req_str[2:].decode("hex"))
self.m_serial_port.write(req_str.decode("hex"))
if self.m_serial_port.getResponse(self.getContext()).encode("hex") == "06":
self.writeCmdMsg("Success(setHolidayDates: 06 returned.")
result = True
self.serialPostEnd()
except:
ekm_log(traceback.format_exc(sys.exc_info()))
self.setContext("")
return result |
Serial call to set weekend and holiday: class: ~ekmmeters. Schedules. | def setWeekendHolidaySchedules(self, new_wknd, new_hldy, password="00000000"):
""" Serial call to set weekend and holiday :class:`~ekmmeters.Schedules`.
Args:
new_wknd (int): :class:`~ekmmeters.Schedules` value to assign.
new_hldy (int): :class:`~ekmmeters.Schedules` value to assign.
password (str): Optional password..
Returns:
bool: True on completion and ACK.
"""
result = False
self.setContext("setWeekendHolidaySchedules")
try:
if not self.request(False):
self.writeCmdMsg("Bad read CRC on setting")
else:
if not self.serialCmdPwdAuth(password):
self.writeCmdMsg("Password failure")
else:
req_wkd = binascii.hexlify(str(new_wknd).zfill(2))
req_hldy = binascii.hexlify(str(new_hldy).zfill(2))
req_str = "015731023030433028" + req_wkd + req_hldy + "2903"
req_str += self.calc_crc16(req_str[2:].decode("hex"))
self.m_serial_port.write(req_str.decode("hex"))
if self.m_serial_port.getResponse(self.getContext()).encode("hex") == "06":
self.writeCmdMsg("Success(setWeekendHolidaySchedules): 06 returned.")
result = True
self.serialPostEnd()
except:
ekm_log(traceback.format_exc(sys.exc_info()))
self.setContext("")
return result |
Serial call to read schedule tariffs buffer | def readSchedules(self, tableset):
""" Serial call to read schedule tariffs buffer
Args:
tableset (int): :class:`~ekmmeters.ReadSchedules` buffer to return.
Returns:
bool: True on completion and ACK.
"""
self.setContext("readSchedules")
try:
req_table = binascii.hexlify(str(tableset).zfill(1))
req_str = "01523102303037" + req_table + "282903"
self.request(False)
req_crc = self.calc_crc16(req_str[2:].decode("hex"))
req_str += req_crc
self.m_serial_port.write(req_str.decode("hex"))
raw_ret = self.m_serial_port.getResponse(self.getContext())
self.serialPostEnd()
return_crc = self.calc_crc16(raw_ret[1:-2])
if tableset == ReadSchedules.Schedules_1_To_4:
unpacked_read = self.unpackStruct(raw_ret, self.m_schd_1_to_4)
self.convertData(unpacked_read, self.m_schd_1_to_4, self.m_kwh_precision)
if str(return_crc) == str(self.m_schd_1_to_4["crc16"][MeterData.StringValue]):
ekm_log("Schedules 1 to 4 CRC success (06 return")
self.setContext("")
return True
elif tableset == ReadSchedules.Schedules_5_To_6:
unpacked_read = self.unpackStruct(raw_ret, self.m_schd_5_to_6)
self.convertData(unpacked_read, self.m_schd_5_to_6, self.m_kwh_precision)
if str(return_crc) == str(self.m_schd_5_to_6["crc16"][MeterData.StringValue]):
ekm_log("Schedules 5 to 8 CRC success (06 return)")
self.setContext("")
return True
except:
ekm_log(traceback.format_exc(sys.exc_info()))
self.setContext("")
return False |
Read a single schedule tariff from meter object buffer. | def extractSchedule(self, schedule, period):
""" Read a single schedule tariff from meter object buffer.
Args:
schedule (int): A :class:`~ekmmeters.Schedules` value or in range(Extent.Schedules).
tariff (int): A :class:`~ekmmeters.Tariffs` value or in range(Extent.Tariffs).
Returns:
bool: True on completion.
"""
ret = namedtuple("ret", ["Hour", "Min", "Tariff", "Period", "Schedule"])
work_table = self.m_schd_1_to_4
if Schedules.Schedule_5 <= schedule <= Schedules.Schedule_6:
work_table = self.m_schd_5_to_6
period += 1
schedule += 1
ret.Period = str(period)
ret.Schedule = str(schedule)
if (schedule < 1) or (schedule > Extents.Schedules) or (period < 0) or (period > Extents.Periods):
ekm_log("Out of bounds: tariff " + str(period) + " for schedule " + str(schedule))
ret.Hour = ret.Min = ret.Tariff = str(0)
return ret
idxhr = "Schedule_" + str(schedule) + "_Period_" + str(period) + "_Hour"
idxmin = "Schedule_" + str(schedule) + "_Period_" + str(period) + "_Min"
idxrate = "Schedule_" + str(schedule) + "_Period_" + str(period) + "_Tariff"
if idxhr not in work_table:
ekm_log("Incorrect index: " + idxhr)
ret.Hour = ret.Min = ret.Tariff = str(0)
return ret
if idxmin not in work_table:
ekm_log("Incorrect index: " + idxmin)
ret.Hour = ret.Min = ret.Tariff = str(0)
return ret
if idxrate not in work_table:
ekm_log("Incorrect index: " + idxrate)
ret.Hour = ret.Min = ret.Tariff = str(0)
return ret
ret.Hour = work_table[idxhr][MeterData.StringValue]
ret.Min = work_table[idxmin][MeterData.StringValue].zfill(2)
ret.Tariff = work_table[idxrate][MeterData.StringValue]
return ret |
Serial call to read month tariffs block into meter object buffer. | def readMonthTariffs(self, months_type):
""" Serial call to read month tariffs block into meter object buffer.
Args:
months_type (int): A :class:`~ekmmeters.ReadMonths` value.
Returns:
bool: True on completion.
"""
self.setContext("readMonthTariffs")
try:
req_type = binascii.hexlify(str(months_type).zfill(1))
req_str = "01523102303031" + req_type + "282903"
work_table = self.m_mons
if months_type == ReadMonths.kWhReverse:
work_table = self.m_rev_mons
self.request(False)
req_crc = self.calc_crc16(req_str[2:].decode("hex"))
req_str += req_crc
self.m_serial_port.write(req_str.decode("hex"))
raw_ret = self.m_serial_port.getResponse(self.getContext())
self.serialPostEnd()
unpacked_read = self.unpackStruct(raw_ret, work_table)
self.convertData(unpacked_read, work_table, self.m_kwh_precision)
return_crc = self.calc_crc16(raw_ret[1:-2])
if str(return_crc) == str(work_table["crc16"][MeterData.StringValue]):
ekm_log("Months CRC success, type = " + str(req_type))
self.setContext("")
return True
except:
ekm_log(traceback.format_exc(sys.exc_info()))
self.setContext("")
return False |
Extract the tariff for a single month from the meter object buffer. | def extractMonthTariff(self, month):
""" Extract the tariff for a single month from the meter object buffer.
Args:
month (int): A :class:`~ekmmeters.Months` value or range(Extents.Months).
Returns:
tuple: The eight tariff period totals for month. The return tuple breaks out as follows:
================= ======================================
kWh_Tariff_1 kWh for tariff period 1 over month.
kWh_Tariff_2 kWh for tariff period 2 over month
kWh_Tariff_3 kWh for tariff period 3 over month
kWh_Tariff_4 kWh for tariff period 4 over month
kWh_Tot Total kWh over requested month
Rev_kWh_Tariff_1 Rev kWh for tariff period 1 over month
Rev_kWh_Tariff_3 Rev kWh for tariff period 2 over month
Rev_kWh_Tariff_3 Rev kWh for tariff period 3 over month
Rev_kWh_Tariff_4 Rev kWh for tariff period 4 over month
Rev_kWh_Tot Total Rev kWh over requested month
================= ======================================
"""
ret = namedtuple("ret", ["Month", Field.kWh_Tariff_1, Field.kWh_Tariff_2, Field.kWh_Tariff_3,
Field.kWh_Tariff_4, Field.kWh_Tot, Field.Rev_kWh_Tariff_1,
Field.Rev_kWh_Tariff_2, Field.Rev_kWh_Tariff_3,
Field.Rev_kWh_Tariff_4, Field.Rev_kWh_Tot])
month += 1
ret.Month = str(month)
if (month < 1) or (month > Extents.Months):
ret.kWh_Tariff_1 = ret.kWh_Tariff_2 = ret.kWh_Tariff_3 = ret.kWh_Tariff_4 = str(0)
ret.Rev_kWh_Tariff_1 = ret.Rev_kWh_Tariff_2 = ret.Rev_kWh_Tariff_3 = ret.Rev_kWh_Tariff_4 = str(0)
ret.kWh_Tot = ret.Rev_kWh_Tot = str(0)
ekm_log("Out of range(Extents.Months) month = " + str(month))
return ret
base_str = "Month_" + str(month) + "_"
ret.kWh_Tariff_1 = self.m_mons[base_str + "Tariff_1"][MeterData.StringValue]
ret.kWh_Tariff_2 = self.m_mons[base_str + "Tariff_2"][MeterData.StringValue]
ret.kWh_Tariff_3 = self.m_mons[base_str + "Tariff_3"][MeterData.StringValue]
ret.kWh_Tariff_4 = self.m_mons[base_str + "Tariff_4"][MeterData.StringValue]
ret.kWh_Tot = self.m_mons[base_str + "Tot"][MeterData.StringValue]
ret.Rev_kWh_Tariff_1 = self.m_rev_mons[base_str + "Tariff_1"][MeterData.StringValue]
ret.Rev_kWh_Tariff_2 = self.m_rev_mons[base_str + "Tariff_2"][MeterData.StringValue]
ret.Rev_kWh_Tariff_3 = self.m_rev_mons[base_str + "Tariff_3"][MeterData.StringValue]
ret.Rev_kWh_Tariff_4 = self.m_rev_mons[base_str + "Tariff_4"][MeterData.StringValue]
ret.Rev_kWh_Tot = self.m_rev_mons[base_str + "Tot"][MeterData.StringValue]
return ret |
Serial call to read holiday dates into meter object buffer. | def readHolidayDates(self):
""" Serial call to read holiday dates into meter object buffer.
Returns:
bool: True on completion.
"""
self.setContext("readHolidayDates")
try:
req_str = "0152310230304230282903"
self.request(False)
req_crc = self.calc_crc16(req_str[2:].decode("hex"))
req_str += req_crc
self.m_serial_port.write(req_str.decode("hex"))
raw_ret = self.m_serial_port.getResponse(self.getContext())
self.serialPostEnd()
unpacked_read = self.unpackStruct(raw_ret, self.m_hldy)
self.convertData(unpacked_read, self.m_hldy, self.m_kwh_precision)
return_crc = self.calc_crc16(raw_ret[1:-2])
if str(return_crc) == str(self.m_hldy["crc16"][MeterData.StringValue]):
ekm_log("Holidays and Schedules CRC success")
self.setContext("")
return True
except:
ekm_log(traceback.format_exc(sys.exc_info()))
self.setContext("")
return False |
Read a single holiday date from meter buffer. | def extractHolidayDate(self, setting_holiday):
""" Read a single holiday date from meter buffer.
Args:
setting_holiday (int): Holiday from 0-19 or in range(Extents.Holidays)
Returns:
tuple: Holiday tuple, elements are strings.
=============== ======================
Holiday Holiday 0-19 as string
Day Day 1-31 as string
Month Monty 1-12 as string
=============== ======================
"""
ret = namedtuple("result", ["Holiday", "Month", "Day"])
setting_holiday += 1
ret.Holiday = str(setting_holiday)
if (setting_holiday < 1) or (setting_holiday > Extents.Holidays):
ekm_log("Out of bounds: holiday " + str(setting_holiday))
ret.Holiday = ret.Month = ret.Day = str(0)
return ret
idxday = "Holiday_" + str(setting_holiday) + "_Day"
idxmon = "Holiday_" + str(setting_holiday) + "_Mon"
if idxmon not in self.m_hldy:
ret.Holiday = ret.Month = ret.Day = str(0)
return ret
if idxday not in self.m_hldy:
ret.Holiday = ret.Month = ret.Day = str(0)
return ret
ret.Day = self.m_hldy[idxday][MeterData.StringValue]
ret.Month = self.m_hldy[idxmon][MeterData.StringValue]
return ret |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.