repository_name
stringclasses
316 values
func_path_in_repository
stringlengths
6
223
func_name
stringlengths
1
134
language
stringclasses
1 value
func_code_string
stringlengths
57
65.5k
func_documentation_string
stringlengths
1
46.3k
split_name
stringclasses
1 value
func_code_url
stringlengths
91
315
called_functions
listlengths
1
156
enclosing_scope
stringlengths
2
1.48M
agile4you/bottle-neck
example.py
ResourceHandler.get
python
def get(self, uid=None): # Return resource collection if uid is None: return self.response_factory.ok(data=resource_db) # Return resource based on UID. try: record = [r for r in resource_db if r.get('id') == uid].pop() except IndexError: return self.response_factory.not_found(errors=['Resource with UID {} does not exist.'.format(uid)]) return self.response_factory.ok(data=record)
Example retrieve API method.
train
https://github.com/agile4you/bottle-neck/blob/ebc670a4b178255473d68e9b4122ba04e38f4810/example.py#L27-L43
null
class ResourceHandler(BaseHandler): """API Handler for Data Resource. """ response_factory = WSResponse cors_enabled = True def post(self): """Example POST method. """ resource_data = self.request.json record = {'id': str(len(resource_db) + 1), 'name': resource_data.get('name')} resource_db.append(record) return self.response_factory.ok(data=record) def put(self, uid): """Example PUT method. """ resource_data = self.request.json try: record = resource_db[uid] except KeyError: return self.response_factory.not_found(errors=['Resource with UID {} does not exist!']) record['name'] = resource_data.get('name') return self.response_factory.ok(data=record) def delete(self, uid): """Example DELETE method. """ try: record = resource_db[uid].copy() except KeyError: return self.response_factory.not_found(errors=['Resource with UID {} does not exist!']) del resource_db[uid] return self.response_factory.ok(data=record)
agile4you/bottle-neck
example.py
ResourceHandler.post
python
def post(self): resource_data = self.request.json record = {'id': str(len(resource_db) + 1), 'name': resource_data.get('name')} resource_db.append(record) return self.response_factory.ok(data=record)
Example POST method.
train
https://github.com/agile4you/bottle-neck/blob/ebc670a4b178255473d68e9b4122ba04e38f4810/example.py#L45-L56
null
class ResourceHandler(BaseHandler): """API Handler for Data Resource. """ response_factory = WSResponse cors_enabled = True def get(self, uid=None): """Example retrieve API method. """ # Return resource collection if uid is None: return self.response_factory.ok(data=resource_db) # Return resource based on UID. try: record = [r for r in resource_db if r.get('id') == uid].pop() except IndexError: return self.response_factory.not_found(errors=['Resource with UID {} does not exist.'.format(uid)]) return self.response_factory.ok(data=record) def put(self, uid): """Example PUT method. """ resource_data = self.request.json try: record = resource_db[uid] except KeyError: return self.response_factory.not_found(errors=['Resource with UID {} does not exist!']) record['name'] = resource_data.get('name') return self.response_factory.ok(data=record) def delete(self, uid): """Example DELETE method. """ try: record = resource_db[uid].copy() except KeyError: return self.response_factory.not_found(errors=['Resource with UID {} does not exist!']) del resource_db[uid] return self.response_factory.ok(data=record)
agile4you/bottle-neck
example.py
ResourceHandler.put
python
def put(self, uid): resource_data = self.request.json try: record = resource_db[uid] except KeyError: return self.response_factory.not_found(errors=['Resource with UID {} does not exist!']) record['name'] = resource_data.get('name') return self.response_factory.ok(data=record)
Example PUT method.
train
https://github.com/agile4you/bottle-neck/blob/ebc670a4b178255473d68e9b4122ba04e38f4810/example.py#L58-L72
null
class ResourceHandler(BaseHandler): """API Handler for Data Resource. """ response_factory = WSResponse cors_enabled = True def get(self, uid=None): """Example retrieve API method. """ # Return resource collection if uid is None: return self.response_factory.ok(data=resource_db) # Return resource based on UID. try: record = [r for r in resource_db if r.get('id') == uid].pop() except IndexError: return self.response_factory.not_found(errors=['Resource with UID {} does not exist.'.format(uid)]) return self.response_factory.ok(data=record) def post(self): """Example POST method. """ resource_data = self.request.json record = {'id': str(len(resource_db) + 1), 'name': resource_data.get('name')} resource_db.append(record) return self.response_factory.ok(data=record) def delete(self, uid): """Example DELETE method. """ try: record = resource_db[uid].copy() except KeyError: return self.response_factory.not_found(errors=['Resource with UID {} does not exist!']) del resource_db[uid] return self.response_factory.ok(data=record)
agile4you/bottle-neck
example.py
ResourceHandler.delete
python
def delete(self, uid): try: record = resource_db[uid].copy() except KeyError: return self.response_factory.not_found(errors=['Resource with UID {} does not exist!']) del resource_db[uid] return self.response_factory.ok(data=record)
Example DELETE method.
train
https://github.com/agile4you/bottle-neck/blob/ebc670a4b178255473d68e9b4122ba04e38f4810/example.py#L74-L85
null
class ResourceHandler(BaseHandler): """API Handler for Data Resource. """ response_factory = WSResponse cors_enabled = True def get(self, uid=None): """Example retrieve API method. """ # Return resource collection if uid is None: return self.response_factory.ok(data=resource_db) # Return resource based on UID. try: record = [r for r in resource_db if r.get('id') == uid].pop() except IndexError: return self.response_factory.not_found(errors=['Resource with UID {} does not exist.'.format(uid)]) return self.response_factory.ok(data=record) def post(self): """Example POST method. """ resource_data = self.request.json record = {'id': str(len(resource_db) + 1), 'name': resource_data.get('name')} resource_db.append(record) return self.response_factory.ok(data=record) def put(self, uid): """Example PUT method. """ resource_data = self.request.json try: record = resource_db[uid] except KeyError: return self.response_factory.not_found(errors=['Resource with UID {} does not exist!']) record['name'] = resource_data.get('name') return self.response_factory.ok(data=record)
earlzo/hfut
hfut/util.py
get_point
python
def get_point(grade_str): try: grade = float(grade_str) assert 0 <= grade <= 100 if 95 <= grade <= 100: return 4.3 elif 90 <= grade < 95: return 4.0 elif 85 <= grade < 90: return 3.7 elif 82 <= grade < 85: return 3.3 elif 78 <= grade < 82: return 3.0 elif 75 <= grade < 78: return 2.7 elif 72 <= grade < 75: return 2.3 elif 68 <= grade < 72: return 2.0 elif 66 <= grade < 68: return 1.7 elif 64 <= grade < 66: return 1.3 elif 60 <= grade < 64: return 1.0 else: return 0.0 except ValueError: if grade_str == '优': return 3.9 elif grade_str == '良': return 3.0 elif grade_str == '中': return 2.0 elif grade_str == '及格': return 1.2 elif grade_str in ('不及格', '免修', '未考'): return 0.0 else: raise ValueError('{:s} 不是有效的成绩'.format(grade_str))
根据成绩判断绩点 :param grade_str: 一个字符串,因为可能是百分制成绩或等级制成绩 :return: 成绩绩点 :rtype: float
train
https://github.com/earlzo/hfut/blob/09270a9647fba79f26fd1a8a3c53c0678b5257a1/hfut/util.py#L21-L68
null
# -*- coding:utf-8 -*- """ 一些能够帮你提升效率的辅助函数 """ from __future__ import unicode_literals, division from copy import deepcopy from datetime import timedelta from threading import Thread import requests import requests.exceptions from six.moves import urllib from .log import logger from .value import ENV __all__ = ['get_point', 'cal_gpa', 'cal_term_code', 'term_str2code', 'sort_hosts', 'filter_curriculum'] def cal_gpa(grades): """ 根据成绩数组计算课程平均绩点和 gpa, 算法不一定与学校一致, 结果仅供参考 :param grades: :meth:`models.StudentSession.get_my_achievements` 返回的成绩数组 :return: 包含了课程平均绩点和 gpa 的元组 """ # 课程总数 courses_sum = len(grades) # 课程绩点和 points_sum = 0 # 学分和 credit_sum = 0 # 课程学分 x 课程绩点之和 gpa_points_sum = 0 for grade in grades: point = get_point(grade.get('补考成绩') or grade['成绩']) credit = float(grade['学分']) points_sum += point credit_sum += credit gpa_points_sum += credit * point ave_point = points_sum / courses_sum gpa = gpa_points_sum / credit_sum return round(ave_point, 5), round(gpa, 5) def cal_term_code(year, is_first_term=True): """ 计算对应的学期代码 :param year: 学年开始年份,例如 "2012-2013学年第二学期" 就是 2012 :param is_first_term: 是否为第一学期 :type is_first_term: bool :return: 形如 "022" 的学期代码 """ if year <= 2001: msg = '出现了超出范围年份: {}'.format(year) raise ValueError(msg) term_code = (year - 2001) * 2 if is_first_term: term_code -= 1 return '%03d' % term_code def term_str2code(term_str): """ 将学期字符串转换为对应的学期代码串 :param term_str: 形如 "2012-2013学年第二学期" 的学期字符串 :return: 形如 "022" 的学期代码 """ result = ENV['TERM_PATTERN'].match(term_str).groups() year = int(result[0]) return cal_term_code(year, result[1] == '一') def sort_hosts(hosts, method='GET', path='/', timeout=(5, 10), **kwargs): """ 测试各个地址的速度并返回排名, 当出现错误时消耗时间为 INFINITY = 10000000 :param method: 请求方法 :param path: 默认的访问路径 :param hosts: 进行的主机地址列表, 如 `['http://222.195.8.201/']` :param timeout: 超时时间, 可以是一个浮点数或 形如 ``(连接超时, 读取超时)`` 的元祖 :param kwargs: 其他传递到 ``requests.request`` 的参数 :return: 形如 ``[(访问耗时, 地址)]`` 的排名数据 """ ranks = [] class HostCheckerThread(Thread): def __init__(self, host): super(HostCheckerThread, self).__init__() self.host = host def run(self): INFINITY = 10000000 try: url = urllib.parse.urljoin(self.host, path) res = requests.request(method, url, timeout=timeout, **kwargs) res.raise_for_status() cost = res.elapsed.total_seconds() * 1000 except Exception as e: logger.warning('访问出错: %s', e) cost = INFINITY # http://stackoverflow.com/questions/6319207/are-lists-thread-safe ranks.append((cost, self.host)) threads = [HostCheckerThread(u) for u in hosts] for t in threads: t.start() for t in threads: t.join() ranks.sort() return ranks def filter_curriculum(curriculum, week, weekday=None): """ 筛选出指定星期[和指定星期几]的课程 :param curriculum: 课程表数据 :param week: 需要筛选的周数, 是一个代表周数的正整数 :param weekday: 星期几, 是一个代表星期的整数, 1-7 对应周一到周日 :return: 如果 weekday 参数没给出, 返回的格式与原课表一致, 但只包括了在指定周数的课程, 否则返回指定周数和星期几的当天课程 """ if weekday: c = [deepcopy(curriculum[weekday - 1])] else: c = deepcopy(curriculum) for d in c: l = len(d) for t_idx in range(l): t = d[t_idx] if t is None: continue # 一般同一时间课程不会重复,重复时给出警告 t = list(filter(lambda k: week in k['上课周数'], t)) or None if t is not None and len(t) > 1: logger.warning('第 %d 周周 %d 第 %d 节课有冲突: %s', week, weekday or c.index(d) + 1, t_idx + 1, t) d[t_idx] = t return c[0] if weekday else c def curriculum2schedule(curriculum, first_day, compress=False, time_table=None): """ 将课程表转换为上课时间表, 如果 compress=False 结果是未排序的, 否则为压缩并排序后的上课时间表 :param curriculum: 课表 :param first_day: 第一周周一, 如 datetime.datetime(2016, 8, 29) :param compress: 压缩连续的课时为一个 :param time_table: 每天上课的时间表, 形如 ``((start timedelta, end timedelta), ...)`` 的 11 × 2 的矩阵 :return: [(datetime.datetime, str) ...] """ schedule = [] time_table = time_table or ( (timedelta(hours=8), timedelta(hours=8, minutes=50)), (timedelta(hours=9), timedelta(hours=9, minutes=50)), (timedelta(hours=10, minutes=10), timedelta(hours=11)), (timedelta(hours=11, minutes=10), timedelta(hours=12)), (timedelta(hours=14), timedelta(hours=14, minutes=50)), (timedelta(hours=15), timedelta(hours=15, minutes=50)), (timedelta(hours=16), timedelta(hours=16, minutes=50)), (timedelta(hours=17), timedelta(hours=17, minutes=50)), (timedelta(hours=19), timedelta(hours=19, minutes=50)), (timedelta(hours=19, minutes=50), timedelta(hours=20, minutes=40)), (timedelta(hours=20, minutes=40), timedelta(hours=21, minutes=30)) ) for i, d in enumerate(curriculum): for j, cs in enumerate(d): for c in cs or []: course = '{name}[{place}]'.format(name=c['课程名称'], place=c['课程地点']) for week in c['上课周数']: day = first_day + timedelta(weeks=week - 1, days=i) start, end = time_table[j] item = (week, day + start, day + end, course) schedule.append(item) schedule.sort() if compress: new_schedule = [schedule[0]] for i in range(1, len(schedule)): sch = schedule[i] # 同一天的连续课程 if new_schedule[-1][1].date() == sch[1].date() and new_schedule[-1][3] == sch[3]: # 更新结束时间 old_item = new_schedule.pop() # week, start, end, course new_item = (old_item[0], old_item[1], sch[2], old_item[3]) else: new_item = sch new_schedule.append(new_item) return new_schedule return schedule
earlzo/hfut
hfut/util.py
cal_gpa
python
def cal_gpa(grades): # 课程总数 courses_sum = len(grades) # 课程绩点和 points_sum = 0 # 学分和 credit_sum = 0 # 课程学分 x 课程绩点之和 gpa_points_sum = 0 for grade in grades: point = get_point(grade.get('补考成绩') or grade['成绩']) credit = float(grade['学分']) points_sum += point credit_sum += credit gpa_points_sum += credit * point ave_point = points_sum / courses_sum gpa = gpa_points_sum / credit_sum return round(ave_point, 5), round(gpa, 5)
根据成绩数组计算课程平均绩点和 gpa, 算法不一定与学校一致, 结果仅供参考 :param grades: :meth:`models.StudentSession.get_my_achievements` 返回的成绩数组 :return: 包含了课程平均绩点和 gpa 的元组
train
https://github.com/earlzo/hfut/blob/09270a9647fba79f26fd1a8a3c53c0678b5257a1/hfut/util.py#L71-L95
[ "def get_point(grade_str):\n \"\"\"\n 根据成绩判断绩点\n\n :param grade_str: 一个字符串,因为可能是百分制成绩或等级制成绩\n :return: 成绩绩点\n :rtype: float\n \"\"\"\n try:\n grade = float(grade_str)\n assert 0 <= grade <= 100\n if 95 <= grade <= 100:\n return 4.3\n elif 90 <= grade < 95:...
# -*- coding:utf-8 -*- """ 一些能够帮你提升效率的辅助函数 """ from __future__ import unicode_literals, division from copy import deepcopy from datetime import timedelta from threading import Thread import requests import requests.exceptions from six.moves import urllib from .log import logger from .value import ENV __all__ = ['get_point', 'cal_gpa', 'cal_term_code', 'term_str2code', 'sort_hosts', 'filter_curriculum'] def get_point(grade_str): """ 根据成绩判断绩点 :param grade_str: 一个字符串,因为可能是百分制成绩或等级制成绩 :return: 成绩绩点 :rtype: float """ try: grade = float(grade_str) assert 0 <= grade <= 100 if 95 <= grade <= 100: return 4.3 elif 90 <= grade < 95: return 4.0 elif 85 <= grade < 90: return 3.7 elif 82 <= grade < 85: return 3.3 elif 78 <= grade < 82: return 3.0 elif 75 <= grade < 78: return 2.7 elif 72 <= grade < 75: return 2.3 elif 68 <= grade < 72: return 2.0 elif 66 <= grade < 68: return 1.7 elif 64 <= grade < 66: return 1.3 elif 60 <= grade < 64: return 1.0 else: return 0.0 except ValueError: if grade_str == '优': return 3.9 elif grade_str == '良': return 3.0 elif grade_str == '中': return 2.0 elif grade_str == '及格': return 1.2 elif grade_str in ('不及格', '免修', '未考'): return 0.0 else: raise ValueError('{:s} 不是有效的成绩'.format(grade_str)) def cal_term_code(year, is_first_term=True): """ 计算对应的学期代码 :param year: 学年开始年份,例如 "2012-2013学年第二学期" 就是 2012 :param is_first_term: 是否为第一学期 :type is_first_term: bool :return: 形如 "022" 的学期代码 """ if year <= 2001: msg = '出现了超出范围年份: {}'.format(year) raise ValueError(msg) term_code = (year - 2001) * 2 if is_first_term: term_code -= 1 return '%03d' % term_code def term_str2code(term_str): """ 将学期字符串转换为对应的学期代码串 :param term_str: 形如 "2012-2013学年第二学期" 的学期字符串 :return: 形如 "022" 的学期代码 """ result = ENV['TERM_PATTERN'].match(term_str).groups() year = int(result[0]) return cal_term_code(year, result[1] == '一') def sort_hosts(hosts, method='GET', path='/', timeout=(5, 10), **kwargs): """ 测试各个地址的速度并返回排名, 当出现错误时消耗时间为 INFINITY = 10000000 :param method: 请求方法 :param path: 默认的访问路径 :param hosts: 进行的主机地址列表, 如 `['http://222.195.8.201/']` :param timeout: 超时时间, 可以是一个浮点数或 形如 ``(连接超时, 读取超时)`` 的元祖 :param kwargs: 其他传递到 ``requests.request`` 的参数 :return: 形如 ``[(访问耗时, 地址)]`` 的排名数据 """ ranks = [] class HostCheckerThread(Thread): def __init__(self, host): super(HostCheckerThread, self).__init__() self.host = host def run(self): INFINITY = 10000000 try: url = urllib.parse.urljoin(self.host, path) res = requests.request(method, url, timeout=timeout, **kwargs) res.raise_for_status() cost = res.elapsed.total_seconds() * 1000 except Exception as e: logger.warning('访问出错: %s', e) cost = INFINITY # http://stackoverflow.com/questions/6319207/are-lists-thread-safe ranks.append((cost, self.host)) threads = [HostCheckerThread(u) for u in hosts] for t in threads: t.start() for t in threads: t.join() ranks.sort() return ranks def filter_curriculum(curriculum, week, weekday=None): """ 筛选出指定星期[和指定星期几]的课程 :param curriculum: 课程表数据 :param week: 需要筛选的周数, 是一个代表周数的正整数 :param weekday: 星期几, 是一个代表星期的整数, 1-7 对应周一到周日 :return: 如果 weekday 参数没给出, 返回的格式与原课表一致, 但只包括了在指定周数的课程, 否则返回指定周数和星期几的当天课程 """ if weekday: c = [deepcopy(curriculum[weekday - 1])] else: c = deepcopy(curriculum) for d in c: l = len(d) for t_idx in range(l): t = d[t_idx] if t is None: continue # 一般同一时间课程不会重复,重复时给出警告 t = list(filter(lambda k: week in k['上课周数'], t)) or None if t is not None and len(t) > 1: logger.warning('第 %d 周周 %d 第 %d 节课有冲突: %s', week, weekday or c.index(d) + 1, t_idx + 1, t) d[t_idx] = t return c[0] if weekday else c def curriculum2schedule(curriculum, first_day, compress=False, time_table=None): """ 将课程表转换为上课时间表, 如果 compress=False 结果是未排序的, 否则为压缩并排序后的上课时间表 :param curriculum: 课表 :param first_day: 第一周周一, 如 datetime.datetime(2016, 8, 29) :param compress: 压缩连续的课时为一个 :param time_table: 每天上课的时间表, 形如 ``((start timedelta, end timedelta), ...)`` 的 11 × 2 的矩阵 :return: [(datetime.datetime, str) ...] """ schedule = [] time_table = time_table or ( (timedelta(hours=8), timedelta(hours=8, minutes=50)), (timedelta(hours=9), timedelta(hours=9, minutes=50)), (timedelta(hours=10, minutes=10), timedelta(hours=11)), (timedelta(hours=11, minutes=10), timedelta(hours=12)), (timedelta(hours=14), timedelta(hours=14, minutes=50)), (timedelta(hours=15), timedelta(hours=15, minutes=50)), (timedelta(hours=16), timedelta(hours=16, minutes=50)), (timedelta(hours=17), timedelta(hours=17, minutes=50)), (timedelta(hours=19), timedelta(hours=19, minutes=50)), (timedelta(hours=19, minutes=50), timedelta(hours=20, minutes=40)), (timedelta(hours=20, minutes=40), timedelta(hours=21, minutes=30)) ) for i, d in enumerate(curriculum): for j, cs in enumerate(d): for c in cs or []: course = '{name}[{place}]'.format(name=c['课程名称'], place=c['课程地点']) for week in c['上课周数']: day = first_day + timedelta(weeks=week - 1, days=i) start, end = time_table[j] item = (week, day + start, day + end, course) schedule.append(item) schedule.sort() if compress: new_schedule = [schedule[0]] for i in range(1, len(schedule)): sch = schedule[i] # 同一天的连续课程 if new_schedule[-1][1].date() == sch[1].date() and new_schedule[-1][3] == sch[3]: # 更新结束时间 old_item = new_schedule.pop() # week, start, end, course new_item = (old_item[0], old_item[1], sch[2], old_item[3]) else: new_item = sch new_schedule.append(new_item) return new_schedule return schedule
earlzo/hfut
hfut/util.py
cal_term_code
python
def cal_term_code(year, is_first_term=True): if year <= 2001: msg = '出现了超出范围年份: {}'.format(year) raise ValueError(msg) term_code = (year - 2001) * 2 if is_first_term: term_code -= 1 return '%03d' % term_code
计算对应的学期代码 :param year: 学年开始年份,例如 "2012-2013学年第二学期" 就是 2012 :param is_first_term: 是否为第一学期 :type is_first_term: bool :return: 形如 "022" 的学期代码
train
https://github.com/earlzo/hfut/blob/09270a9647fba79f26fd1a8a3c53c0678b5257a1/hfut/util.py#L98-L113
null
# -*- coding:utf-8 -*- """ 一些能够帮你提升效率的辅助函数 """ from __future__ import unicode_literals, division from copy import deepcopy from datetime import timedelta from threading import Thread import requests import requests.exceptions from six.moves import urllib from .log import logger from .value import ENV __all__ = ['get_point', 'cal_gpa', 'cal_term_code', 'term_str2code', 'sort_hosts', 'filter_curriculum'] def get_point(grade_str): """ 根据成绩判断绩点 :param grade_str: 一个字符串,因为可能是百分制成绩或等级制成绩 :return: 成绩绩点 :rtype: float """ try: grade = float(grade_str) assert 0 <= grade <= 100 if 95 <= grade <= 100: return 4.3 elif 90 <= grade < 95: return 4.0 elif 85 <= grade < 90: return 3.7 elif 82 <= grade < 85: return 3.3 elif 78 <= grade < 82: return 3.0 elif 75 <= grade < 78: return 2.7 elif 72 <= grade < 75: return 2.3 elif 68 <= grade < 72: return 2.0 elif 66 <= grade < 68: return 1.7 elif 64 <= grade < 66: return 1.3 elif 60 <= grade < 64: return 1.0 else: return 0.0 except ValueError: if grade_str == '优': return 3.9 elif grade_str == '良': return 3.0 elif grade_str == '中': return 2.0 elif grade_str == '及格': return 1.2 elif grade_str in ('不及格', '免修', '未考'): return 0.0 else: raise ValueError('{:s} 不是有效的成绩'.format(grade_str)) def cal_gpa(grades): """ 根据成绩数组计算课程平均绩点和 gpa, 算法不一定与学校一致, 结果仅供参考 :param grades: :meth:`models.StudentSession.get_my_achievements` 返回的成绩数组 :return: 包含了课程平均绩点和 gpa 的元组 """ # 课程总数 courses_sum = len(grades) # 课程绩点和 points_sum = 0 # 学分和 credit_sum = 0 # 课程学分 x 课程绩点之和 gpa_points_sum = 0 for grade in grades: point = get_point(grade.get('补考成绩') or grade['成绩']) credit = float(grade['学分']) points_sum += point credit_sum += credit gpa_points_sum += credit * point ave_point = points_sum / courses_sum gpa = gpa_points_sum / credit_sum return round(ave_point, 5), round(gpa, 5) def term_str2code(term_str): """ 将学期字符串转换为对应的学期代码串 :param term_str: 形如 "2012-2013学年第二学期" 的学期字符串 :return: 形如 "022" 的学期代码 """ result = ENV['TERM_PATTERN'].match(term_str).groups() year = int(result[0]) return cal_term_code(year, result[1] == '一') def sort_hosts(hosts, method='GET', path='/', timeout=(5, 10), **kwargs): """ 测试各个地址的速度并返回排名, 当出现错误时消耗时间为 INFINITY = 10000000 :param method: 请求方法 :param path: 默认的访问路径 :param hosts: 进行的主机地址列表, 如 `['http://222.195.8.201/']` :param timeout: 超时时间, 可以是一个浮点数或 形如 ``(连接超时, 读取超时)`` 的元祖 :param kwargs: 其他传递到 ``requests.request`` 的参数 :return: 形如 ``[(访问耗时, 地址)]`` 的排名数据 """ ranks = [] class HostCheckerThread(Thread): def __init__(self, host): super(HostCheckerThread, self).__init__() self.host = host def run(self): INFINITY = 10000000 try: url = urllib.parse.urljoin(self.host, path) res = requests.request(method, url, timeout=timeout, **kwargs) res.raise_for_status() cost = res.elapsed.total_seconds() * 1000 except Exception as e: logger.warning('访问出错: %s', e) cost = INFINITY # http://stackoverflow.com/questions/6319207/are-lists-thread-safe ranks.append((cost, self.host)) threads = [HostCheckerThread(u) for u in hosts] for t in threads: t.start() for t in threads: t.join() ranks.sort() return ranks def filter_curriculum(curriculum, week, weekday=None): """ 筛选出指定星期[和指定星期几]的课程 :param curriculum: 课程表数据 :param week: 需要筛选的周数, 是一个代表周数的正整数 :param weekday: 星期几, 是一个代表星期的整数, 1-7 对应周一到周日 :return: 如果 weekday 参数没给出, 返回的格式与原课表一致, 但只包括了在指定周数的课程, 否则返回指定周数和星期几的当天课程 """ if weekday: c = [deepcopy(curriculum[weekday - 1])] else: c = deepcopy(curriculum) for d in c: l = len(d) for t_idx in range(l): t = d[t_idx] if t is None: continue # 一般同一时间课程不会重复,重复时给出警告 t = list(filter(lambda k: week in k['上课周数'], t)) or None if t is not None and len(t) > 1: logger.warning('第 %d 周周 %d 第 %d 节课有冲突: %s', week, weekday or c.index(d) + 1, t_idx + 1, t) d[t_idx] = t return c[0] if weekday else c def curriculum2schedule(curriculum, first_day, compress=False, time_table=None): """ 将课程表转换为上课时间表, 如果 compress=False 结果是未排序的, 否则为压缩并排序后的上课时间表 :param curriculum: 课表 :param first_day: 第一周周一, 如 datetime.datetime(2016, 8, 29) :param compress: 压缩连续的课时为一个 :param time_table: 每天上课的时间表, 形如 ``((start timedelta, end timedelta), ...)`` 的 11 × 2 的矩阵 :return: [(datetime.datetime, str) ...] """ schedule = [] time_table = time_table or ( (timedelta(hours=8), timedelta(hours=8, minutes=50)), (timedelta(hours=9), timedelta(hours=9, minutes=50)), (timedelta(hours=10, minutes=10), timedelta(hours=11)), (timedelta(hours=11, minutes=10), timedelta(hours=12)), (timedelta(hours=14), timedelta(hours=14, minutes=50)), (timedelta(hours=15), timedelta(hours=15, minutes=50)), (timedelta(hours=16), timedelta(hours=16, minutes=50)), (timedelta(hours=17), timedelta(hours=17, minutes=50)), (timedelta(hours=19), timedelta(hours=19, minutes=50)), (timedelta(hours=19, minutes=50), timedelta(hours=20, minutes=40)), (timedelta(hours=20, minutes=40), timedelta(hours=21, minutes=30)) ) for i, d in enumerate(curriculum): for j, cs in enumerate(d): for c in cs or []: course = '{name}[{place}]'.format(name=c['课程名称'], place=c['课程地点']) for week in c['上课周数']: day = first_day + timedelta(weeks=week - 1, days=i) start, end = time_table[j] item = (week, day + start, day + end, course) schedule.append(item) schedule.sort() if compress: new_schedule = [schedule[0]] for i in range(1, len(schedule)): sch = schedule[i] # 同一天的连续课程 if new_schedule[-1][1].date() == sch[1].date() and new_schedule[-1][3] == sch[3]: # 更新结束时间 old_item = new_schedule.pop() # week, start, end, course new_item = (old_item[0], old_item[1], sch[2], old_item[3]) else: new_item = sch new_schedule.append(new_item) return new_schedule return schedule
earlzo/hfut
hfut/util.py
term_str2code
python
def term_str2code(term_str): result = ENV['TERM_PATTERN'].match(term_str).groups() year = int(result[0]) return cal_term_code(year, result[1] == '一')
将学期字符串转换为对应的学期代码串 :param term_str: 形如 "2012-2013学年第二学期" 的学期字符串 :return: 形如 "022" 的学期代码
train
https://github.com/earlzo/hfut/blob/09270a9647fba79f26fd1a8a3c53c0678b5257a1/hfut/util.py#L116-L125
[ "def cal_term_code(year, is_first_term=True):\n \"\"\"\n 计算对应的学期代码\n\n :param year: 学年开始年份,例如 \"2012-2013学年第二学期\" 就是 2012\n :param is_first_term: 是否为第一学期\n :type is_first_term: bool\n :return: 形如 \"022\" 的学期代码\n \"\"\"\n if year <= 2001:\n msg = '出现了超出范围年份: {}'.format(year)\n r...
# -*- coding:utf-8 -*- """ 一些能够帮你提升效率的辅助函数 """ from __future__ import unicode_literals, division from copy import deepcopy from datetime import timedelta from threading import Thread import requests import requests.exceptions from six.moves import urllib from .log import logger from .value import ENV __all__ = ['get_point', 'cal_gpa', 'cal_term_code', 'term_str2code', 'sort_hosts', 'filter_curriculum'] def get_point(grade_str): """ 根据成绩判断绩点 :param grade_str: 一个字符串,因为可能是百分制成绩或等级制成绩 :return: 成绩绩点 :rtype: float """ try: grade = float(grade_str) assert 0 <= grade <= 100 if 95 <= grade <= 100: return 4.3 elif 90 <= grade < 95: return 4.0 elif 85 <= grade < 90: return 3.7 elif 82 <= grade < 85: return 3.3 elif 78 <= grade < 82: return 3.0 elif 75 <= grade < 78: return 2.7 elif 72 <= grade < 75: return 2.3 elif 68 <= grade < 72: return 2.0 elif 66 <= grade < 68: return 1.7 elif 64 <= grade < 66: return 1.3 elif 60 <= grade < 64: return 1.0 else: return 0.0 except ValueError: if grade_str == '优': return 3.9 elif grade_str == '良': return 3.0 elif grade_str == '中': return 2.0 elif grade_str == '及格': return 1.2 elif grade_str in ('不及格', '免修', '未考'): return 0.0 else: raise ValueError('{:s} 不是有效的成绩'.format(grade_str)) def cal_gpa(grades): """ 根据成绩数组计算课程平均绩点和 gpa, 算法不一定与学校一致, 结果仅供参考 :param grades: :meth:`models.StudentSession.get_my_achievements` 返回的成绩数组 :return: 包含了课程平均绩点和 gpa 的元组 """ # 课程总数 courses_sum = len(grades) # 课程绩点和 points_sum = 0 # 学分和 credit_sum = 0 # 课程学分 x 课程绩点之和 gpa_points_sum = 0 for grade in grades: point = get_point(grade.get('补考成绩') or grade['成绩']) credit = float(grade['学分']) points_sum += point credit_sum += credit gpa_points_sum += credit * point ave_point = points_sum / courses_sum gpa = gpa_points_sum / credit_sum return round(ave_point, 5), round(gpa, 5) def cal_term_code(year, is_first_term=True): """ 计算对应的学期代码 :param year: 学年开始年份,例如 "2012-2013学年第二学期" 就是 2012 :param is_first_term: 是否为第一学期 :type is_first_term: bool :return: 形如 "022" 的学期代码 """ if year <= 2001: msg = '出现了超出范围年份: {}'.format(year) raise ValueError(msg) term_code = (year - 2001) * 2 if is_first_term: term_code -= 1 return '%03d' % term_code def sort_hosts(hosts, method='GET', path='/', timeout=(5, 10), **kwargs): """ 测试各个地址的速度并返回排名, 当出现错误时消耗时间为 INFINITY = 10000000 :param method: 请求方法 :param path: 默认的访问路径 :param hosts: 进行的主机地址列表, 如 `['http://222.195.8.201/']` :param timeout: 超时时间, 可以是一个浮点数或 形如 ``(连接超时, 读取超时)`` 的元祖 :param kwargs: 其他传递到 ``requests.request`` 的参数 :return: 形如 ``[(访问耗时, 地址)]`` 的排名数据 """ ranks = [] class HostCheckerThread(Thread): def __init__(self, host): super(HostCheckerThread, self).__init__() self.host = host def run(self): INFINITY = 10000000 try: url = urllib.parse.urljoin(self.host, path) res = requests.request(method, url, timeout=timeout, **kwargs) res.raise_for_status() cost = res.elapsed.total_seconds() * 1000 except Exception as e: logger.warning('访问出错: %s', e) cost = INFINITY # http://stackoverflow.com/questions/6319207/are-lists-thread-safe ranks.append((cost, self.host)) threads = [HostCheckerThread(u) for u in hosts] for t in threads: t.start() for t in threads: t.join() ranks.sort() return ranks def filter_curriculum(curriculum, week, weekday=None): """ 筛选出指定星期[和指定星期几]的课程 :param curriculum: 课程表数据 :param week: 需要筛选的周数, 是一个代表周数的正整数 :param weekday: 星期几, 是一个代表星期的整数, 1-7 对应周一到周日 :return: 如果 weekday 参数没给出, 返回的格式与原课表一致, 但只包括了在指定周数的课程, 否则返回指定周数和星期几的当天课程 """ if weekday: c = [deepcopy(curriculum[weekday - 1])] else: c = deepcopy(curriculum) for d in c: l = len(d) for t_idx in range(l): t = d[t_idx] if t is None: continue # 一般同一时间课程不会重复,重复时给出警告 t = list(filter(lambda k: week in k['上课周数'], t)) or None if t is not None and len(t) > 1: logger.warning('第 %d 周周 %d 第 %d 节课有冲突: %s', week, weekday or c.index(d) + 1, t_idx + 1, t) d[t_idx] = t return c[0] if weekday else c def curriculum2schedule(curriculum, first_day, compress=False, time_table=None): """ 将课程表转换为上课时间表, 如果 compress=False 结果是未排序的, 否则为压缩并排序后的上课时间表 :param curriculum: 课表 :param first_day: 第一周周一, 如 datetime.datetime(2016, 8, 29) :param compress: 压缩连续的课时为一个 :param time_table: 每天上课的时间表, 形如 ``((start timedelta, end timedelta), ...)`` 的 11 × 2 的矩阵 :return: [(datetime.datetime, str) ...] """ schedule = [] time_table = time_table or ( (timedelta(hours=8), timedelta(hours=8, minutes=50)), (timedelta(hours=9), timedelta(hours=9, minutes=50)), (timedelta(hours=10, minutes=10), timedelta(hours=11)), (timedelta(hours=11, minutes=10), timedelta(hours=12)), (timedelta(hours=14), timedelta(hours=14, minutes=50)), (timedelta(hours=15), timedelta(hours=15, minutes=50)), (timedelta(hours=16), timedelta(hours=16, minutes=50)), (timedelta(hours=17), timedelta(hours=17, minutes=50)), (timedelta(hours=19), timedelta(hours=19, minutes=50)), (timedelta(hours=19, minutes=50), timedelta(hours=20, minutes=40)), (timedelta(hours=20, minutes=40), timedelta(hours=21, minutes=30)) ) for i, d in enumerate(curriculum): for j, cs in enumerate(d): for c in cs or []: course = '{name}[{place}]'.format(name=c['课程名称'], place=c['课程地点']) for week in c['上课周数']: day = first_day + timedelta(weeks=week - 1, days=i) start, end = time_table[j] item = (week, day + start, day + end, course) schedule.append(item) schedule.sort() if compress: new_schedule = [schedule[0]] for i in range(1, len(schedule)): sch = schedule[i] # 同一天的连续课程 if new_schedule[-1][1].date() == sch[1].date() and new_schedule[-1][3] == sch[3]: # 更新结束时间 old_item = new_schedule.pop() # week, start, end, course new_item = (old_item[0], old_item[1], sch[2], old_item[3]) else: new_item = sch new_schedule.append(new_item) return new_schedule return schedule
earlzo/hfut
hfut/util.py
sort_hosts
python
def sort_hosts(hosts, method='GET', path='/', timeout=(5, 10), **kwargs): ranks = [] class HostCheckerThread(Thread): def __init__(self, host): super(HostCheckerThread, self).__init__() self.host = host def run(self): INFINITY = 10000000 try: url = urllib.parse.urljoin(self.host, path) res = requests.request(method, url, timeout=timeout, **kwargs) res.raise_for_status() cost = res.elapsed.total_seconds() * 1000 except Exception as e: logger.warning('访问出错: %s', e) cost = INFINITY # http://stackoverflow.com/questions/6319207/are-lists-thread-safe ranks.append((cost, self.host)) threads = [HostCheckerThread(u) for u in hosts] for t in threads: t.start() for t in threads: t.join() ranks.sort() return ranks
测试各个地址的速度并返回排名, 当出现错误时消耗时间为 INFINITY = 10000000 :param method: 请求方法 :param path: 默认的访问路径 :param hosts: 进行的主机地址列表, 如 `['http://222.195.8.201/']` :param timeout: 超时时间, 可以是一个浮点数或 形如 ``(连接超时, 读取超时)`` 的元祖 :param kwargs: 其他传递到 ``requests.request`` 的参数 :return: 形如 ``[(访问耗时, 地址)]`` 的排名数据
train
https://github.com/earlzo/hfut/blob/09270a9647fba79f26fd1a8a3c53c0678b5257a1/hfut/util.py#L128-L168
null
# -*- coding:utf-8 -*- """ 一些能够帮你提升效率的辅助函数 """ from __future__ import unicode_literals, division from copy import deepcopy from datetime import timedelta from threading import Thread import requests import requests.exceptions from six.moves import urllib from .log import logger from .value import ENV __all__ = ['get_point', 'cal_gpa', 'cal_term_code', 'term_str2code', 'sort_hosts', 'filter_curriculum'] def get_point(grade_str): """ 根据成绩判断绩点 :param grade_str: 一个字符串,因为可能是百分制成绩或等级制成绩 :return: 成绩绩点 :rtype: float """ try: grade = float(grade_str) assert 0 <= grade <= 100 if 95 <= grade <= 100: return 4.3 elif 90 <= grade < 95: return 4.0 elif 85 <= grade < 90: return 3.7 elif 82 <= grade < 85: return 3.3 elif 78 <= grade < 82: return 3.0 elif 75 <= grade < 78: return 2.7 elif 72 <= grade < 75: return 2.3 elif 68 <= grade < 72: return 2.0 elif 66 <= grade < 68: return 1.7 elif 64 <= grade < 66: return 1.3 elif 60 <= grade < 64: return 1.0 else: return 0.0 except ValueError: if grade_str == '优': return 3.9 elif grade_str == '良': return 3.0 elif grade_str == '中': return 2.0 elif grade_str == '及格': return 1.2 elif grade_str in ('不及格', '免修', '未考'): return 0.0 else: raise ValueError('{:s} 不是有效的成绩'.format(grade_str)) def cal_gpa(grades): """ 根据成绩数组计算课程平均绩点和 gpa, 算法不一定与学校一致, 结果仅供参考 :param grades: :meth:`models.StudentSession.get_my_achievements` 返回的成绩数组 :return: 包含了课程平均绩点和 gpa 的元组 """ # 课程总数 courses_sum = len(grades) # 课程绩点和 points_sum = 0 # 学分和 credit_sum = 0 # 课程学分 x 课程绩点之和 gpa_points_sum = 0 for grade in grades: point = get_point(grade.get('补考成绩') or grade['成绩']) credit = float(grade['学分']) points_sum += point credit_sum += credit gpa_points_sum += credit * point ave_point = points_sum / courses_sum gpa = gpa_points_sum / credit_sum return round(ave_point, 5), round(gpa, 5) def cal_term_code(year, is_first_term=True): """ 计算对应的学期代码 :param year: 学年开始年份,例如 "2012-2013学年第二学期" 就是 2012 :param is_first_term: 是否为第一学期 :type is_first_term: bool :return: 形如 "022" 的学期代码 """ if year <= 2001: msg = '出现了超出范围年份: {}'.format(year) raise ValueError(msg) term_code = (year - 2001) * 2 if is_first_term: term_code -= 1 return '%03d' % term_code def term_str2code(term_str): """ 将学期字符串转换为对应的学期代码串 :param term_str: 形如 "2012-2013学年第二学期" 的学期字符串 :return: 形如 "022" 的学期代码 """ result = ENV['TERM_PATTERN'].match(term_str).groups() year = int(result[0]) return cal_term_code(year, result[1] == '一') def filter_curriculum(curriculum, week, weekday=None): """ 筛选出指定星期[和指定星期几]的课程 :param curriculum: 课程表数据 :param week: 需要筛选的周数, 是一个代表周数的正整数 :param weekday: 星期几, 是一个代表星期的整数, 1-7 对应周一到周日 :return: 如果 weekday 参数没给出, 返回的格式与原课表一致, 但只包括了在指定周数的课程, 否则返回指定周数和星期几的当天课程 """ if weekday: c = [deepcopy(curriculum[weekday - 1])] else: c = deepcopy(curriculum) for d in c: l = len(d) for t_idx in range(l): t = d[t_idx] if t is None: continue # 一般同一时间课程不会重复,重复时给出警告 t = list(filter(lambda k: week in k['上课周数'], t)) or None if t is not None and len(t) > 1: logger.warning('第 %d 周周 %d 第 %d 节课有冲突: %s', week, weekday or c.index(d) + 1, t_idx + 1, t) d[t_idx] = t return c[0] if weekday else c def curriculum2schedule(curriculum, first_day, compress=False, time_table=None): """ 将课程表转换为上课时间表, 如果 compress=False 结果是未排序的, 否则为压缩并排序后的上课时间表 :param curriculum: 课表 :param first_day: 第一周周一, 如 datetime.datetime(2016, 8, 29) :param compress: 压缩连续的课时为一个 :param time_table: 每天上课的时间表, 形如 ``((start timedelta, end timedelta), ...)`` 的 11 × 2 的矩阵 :return: [(datetime.datetime, str) ...] """ schedule = [] time_table = time_table or ( (timedelta(hours=8), timedelta(hours=8, minutes=50)), (timedelta(hours=9), timedelta(hours=9, minutes=50)), (timedelta(hours=10, minutes=10), timedelta(hours=11)), (timedelta(hours=11, minutes=10), timedelta(hours=12)), (timedelta(hours=14), timedelta(hours=14, minutes=50)), (timedelta(hours=15), timedelta(hours=15, minutes=50)), (timedelta(hours=16), timedelta(hours=16, minutes=50)), (timedelta(hours=17), timedelta(hours=17, minutes=50)), (timedelta(hours=19), timedelta(hours=19, minutes=50)), (timedelta(hours=19, minutes=50), timedelta(hours=20, minutes=40)), (timedelta(hours=20, minutes=40), timedelta(hours=21, minutes=30)) ) for i, d in enumerate(curriculum): for j, cs in enumerate(d): for c in cs or []: course = '{name}[{place}]'.format(name=c['课程名称'], place=c['课程地点']) for week in c['上课周数']: day = first_day + timedelta(weeks=week - 1, days=i) start, end = time_table[j] item = (week, day + start, day + end, course) schedule.append(item) schedule.sort() if compress: new_schedule = [schedule[0]] for i in range(1, len(schedule)): sch = schedule[i] # 同一天的连续课程 if new_schedule[-1][1].date() == sch[1].date() and new_schedule[-1][3] == sch[3]: # 更新结束时间 old_item = new_schedule.pop() # week, start, end, course new_item = (old_item[0], old_item[1], sch[2], old_item[3]) else: new_item = sch new_schedule.append(new_item) return new_schedule return schedule
earlzo/hfut
hfut/util.py
filter_curriculum
python
def filter_curriculum(curriculum, week, weekday=None): if weekday: c = [deepcopy(curriculum[weekday - 1])] else: c = deepcopy(curriculum) for d in c: l = len(d) for t_idx in range(l): t = d[t_idx] if t is None: continue # 一般同一时间课程不会重复,重复时给出警告 t = list(filter(lambda k: week in k['上课周数'], t)) or None if t is not None and len(t) > 1: logger.warning('第 %d 周周 %d 第 %d 节课有冲突: %s', week, weekday or c.index(d) + 1, t_idx + 1, t) d[t_idx] = t return c[0] if weekday else c
筛选出指定星期[和指定星期几]的课程 :param curriculum: 课程表数据 :param week: 需要筛选的周数, 是一个代表周数的正整数 :param weekday: 星期几, 是一个代表星期的整数, 1-7 对应周一到周日 :return: 如果 weekday 参数没给出, 返回的格式与原课表一致, 但只包括了在指定周数的课程, 否则返回指定周数和星期几的当天课程
train
https://github.com/earlzo/hfut/blob/09270a9647fba79f26fd1a8a3c53c0678b5257a1/hfut/util.py#L171-L195
null
# -*- coding:utf-8 -*- """ 一些能够帮你提升效率的辅助函数 """ from __future__ import unicode_literals, division from copy import deepcopy from datetime import timedelta from threading import Thread import requests import requests.exceptions from six.moves import urllib from .log import logger from .value import ENV __all__ = ['get_point', 'cal_gpa', 'cal_term_code', 'term_str2code', 'sort_hosts', 'filter_curriculum'] def get_point(grade_str): """ 根据成绩判断绩点 :param grade_str: 一个字符串,因为可能是百分制成绩或等级制成绩 :return: 成绩绩点 :rtype: float """ try: grade = float(grade_str) assert 0 <= grade <= 100 if 95 <= grade <= 100: return 4.3 elif 90 <= grade < 95: return 4.0 elif 85 <= grade < 90: return 3.7 elif 82 <= grade < 85: return 3.3 elif 78 <= grade < 82: return 3.0 elif 75 <= grade < 78: return 2.7 elif 72 <= grade < 75: return 2.3 elif 68 <= grade < 72: return 2.0 elif 66 <= grade < 68: return 1.7 elif 64 <= grade < 66: return 1.3 elif 60 <= grade < 64: return 1.0 else: return 0.0 except ValueError: if grade_str == '优': return 3.9 elif grade_str == '良': return 3.0 elif grade_str == '中': return 2.0 elif grade_str == '及格': return 1.2 elif grade_str in ('不及格', '免修', '未考'): return 0.0 else: raise ValueError('{:s} 不是有效的成绩'.format(grade_str)) def cal_gpa(grades): """ 根据成绩数组计算课程平均绩点和 gpa, 算法不一定与学校一致, 结果仅供参考 :param grades: :meth:`models.StudentSession.get_my_achievements` 返回的成绩数组 :return: 包含了课程平均绩点和 gpa 的元组 """ # 课程总数 courses_sum = len(grades) # 课程绩点和 points_sum = 0 # 学分和 credit_sum = 0 # 课程学分 x 课程绩点之和 gpa_points_sum = 0 for grade in grades: point = get_point(grade.get('补考成绩') or grade['成绩']) credit = float(grade['学分']) points_sum += point credit_sum += credit gpa_points_sum += credit * point ave_point = points_sum / courses_sum gpa = gpa_points_sum / credit_sum return round(ave_point, 5), round(gpa, 5) def cal_term_code(year, is_first_term=True): """ 计算对应的学期代码 :param year: 学年开始年份,例如 "2012-2013学年第二学期" 就是 2012 :param is_first_term: 是否为第一学期 :type is_first_term: bool :return: 形如 "022" 的学期代码 """ if year <= 2001: msg = '出现了超出范围年份: {}'.format(year) raise ValueError(msg) term_code = (year - 2001) * 2 if is_first_term: term_code -= 1 return '%03d' % term_code def term_str2code(term_str): """ 将学期字符串转换为对应的学期代码串 :param term_str: 形如 "2012-2013学年第二学期" 的学期字符串 :return: 形如 "022" 的学期代码 """ result = ENV['TERM_PATTERN'].match(term_str).groups() year = int(result[0]) return cal_term_code(year, result[1] == '一') def sort_hosts(hosts, method='GET', path='/', timeout=(5, 10), **kwargs): """ 测试各个地址的速度并返回排名, 当出现错误时消耗时间为 INFINITY = 10000000 :param method: 请求方法 :param path: 默认的访问路径 :param hosts: 进行的主机地址列表, 如 `['http://222.195.8.201/']` :param timeout: 超时时间, 可以是一个浮点数或 形如 ``(连接超时, 读取超时)`` 的元祖 :param kwargs: 其他传递到 ``requests.request`` 的参数 :return: 形如 ``[(访问耗时, 地址)]`` 的排名数据 """ ranks = [] class HostCheckerThread(Thread): def __init__(self, host): super(HostCheckerThread, self).__init__() self.host = host def run(self): INFINITY = 10000000 try: url = urllib.parse.urljoin(self.host, path) res = requests.request(method, url, timeout=timeout, **kwargs) res.raise_for_status() cost = res.elapsed.total_seconds() * 1000 except Exception as e: logger.warning('访问出错: %s', e) cost = INFINITY # http://stackoverflow.com/questions/6319207/are-lists-thread-safe ranks.append((cost, self.host)) threads = [HostCheckerThread(u) for u in hosts] for t in threads: t.start() for t in threads: t.join() ranks.sort() return ranks def curriculum2schedule(curriculum, first_day, compress=False, time_table=None): """ 将课程表转换为上课时间表, 如果 compress=False 结果是未排序的, 否则为压缩并排序后的上课时间表 :param curriculum: 课表 :param first_day: 第一周周一, 如 datetime.datetime(2016, 8, 29) :param compress: 压缩连续的课时为一个 :param time_table: 每天上课的时间表, 形如 ``((start timedelta, end timedelta), ...)`` 的 11 × 2 的矩阵 :return: [(datetime.datetime, str) ...] """ schedule = [] time_table = time_table or ( (timedelta(hours=8), timedelta(hours=8, minutes=50)), (timedelta(hours=9), timedelta(hours=9, minutes=50)), (timedelta(hours=10, minutes=10), timedelta(hours=11)), (timedelta(hours=11, minutes=10), timedelta(hours=12)), (timedelta(hours=14), timedelta(hours=14, minutes=50)), (timedelta(hours=15), timedelta(hours=15, minutes=50)), (timedelta(hours=16), timedelta(hours=16, minutes=50)), (timedelta(hours=17), timedelta(hours=17, minutes=50)), (timedelta(hours=19), timedelta(hours=19, minutes=50)), (timedelta(hours=19, minutes=50), timedelta(hours=20, minutes=40)), (timedelta(hours=20, minutes=40), timedelta(hours=21, minutes=30)) ) for i, d in enumerate(curriculum): for j, cs in enumerate(d): for c in cs or []: course = '{name}[{place}]'.format(name=c['课程名称'], place=c['课程地点']) for week in c['上课周数']: day = first_day + timedelta(weeks=week - 1, days=i) start, end = time_table[j] item = (week, day + start, day + end, course) schedule.append(item) schedule.sort() if compress: new_schedule = [schedule[0]] for i in range(1, len(schedule)): sch = schedule[i] # 同一天的连续课程 if new_schedule[-1][1].date() == sch[1].date() and new_schedule[-1][3] == sch[3]: # 更新结束时间 old_item = new_schedule.pop() # week, start, end, course new_item = (old_item[0], old_item[1], sch[2], old_item[3]) else: new_item = sch new_schedule.append(new_item) return new_schedule return schedule
earlzo/hfut
hfut/util.py
curriculum2schedule
python
def curriculum2schedule(curriculum, first_day, compress=False, time_table=None): schedule = [] time_table = time_table or ( (timedelta(hours=8), timedelta(hours=8, minutes=50)), (timedelta(hours=9), timedelta(hours=9, minutes=50)), (timedelta(hours=10, minutes=10), timedelta(hours=11)), (timedelta(hours=11, minutes=10), timedelta(hours=12)), (timedelta(hours=14), timedelta(hours=14, minutes=50)), (timedelta(hours=15), timedelta(hours=15, minutes=50)), (timedelta(hours=16), timedelta(hours=16, minutes=50)), (timedelta(hours=17), timedelta(hours=17, minutes=50)), (timedelta(hours=19), timedelta(hours=19, minutes=50)), (timedelta(hours=19, minutes=50), timedelta(hours=20, minutes=40)), (timedelta(hours=20, minutes=40), timedelta(hours=21, minutes=30)) ) for i, d in enumerate(curriculum): for j, cs in enumerate(d): for c in cs or []: course = '{name}[{place}]'.format(name=c['课程名称'], place=c['课程地点']) for week in c['上课周数']: day = first_day + timedelta(weeks=week - 1, days=i) start, end = time_table[j] item = (week, day + start, day + end, course) schedule.append(item) schedule.sort() if compress: new_schedule = [schedule[0]] for i in range(1, len(schedule)): sch = schedule[i] # 同一天的连续课程 if new_schedule[-1][1].date() == sch[1].date() and new_schedule[-1][3] == sch[3]: # 更新结束时间 old_item = new_schedule.pop() # week, start, end, course new_item = (old_item[0], old_item[1], sch[2], old_item[3]) else: new_item = sch new_schedule.append(new_item) return new_schedule return schedule
将课程表转换为上课时间表, 如果 compress=False 结果是未排序的, 否则为压缩并排序后的上课时间表 :param curriculum: 课表 :param first_day: 第一周周一, 如 datetime.datetime(2016, 8, 29) :param compress: 压缩连续的课时为一个 :param time_table: 每天上课的时间表, 形如 ``((start timedelta, end timedelta), ...)`` 的 11 × 2 的矩阵 :return: [(datetime.datetime, str) ...]
train
https://github.com/earlzo/hfut/blob/09270a9647fba79f26fd1a8a3c53c0678b5257a1/hfut/util.py#L198-L248
null
# -*- coding:utf-8 -*- """ 一些能够帮你提升效率的辅助函数 """ from __future__ import unicode_literals, division from copy import deepcopy from datetime import timedelta from threading import Thread import requests import requests.exceptions from six.moves import urllib from .log import logger from .value import ENV __all__ = ['get_point', 'cal_gpa', 'cal_term_code', 'term_str2code', 'sort_hosts', 'filter_curriculum'] def get_point(grade_str): """ 根据成绩判断绩点 :param grade_str: 一个字符串,因为可能是百分制成绩或等级制成绩 :return: 成绩绩点 :rtype: float """ try: grade = float(grade_str) assert 0 <= grade <= 100 if 95 <= grade <= 100: return 4.3 elif 90 <= grade < 95: return 4.0 elif 85 <= grade < 90: return 3.7 elif 82 <= grade < 85: return 3.3 elif 78 <= grade < 82: return 3.0 elif 75 <= grade < 78: return 2.7 elif 72 <= grade < 75: return 2.3 elif 68 <= grade < 72: return 2.0 elif 66 <= grade < 68: return 1.7 elif 64 <= grade < 66: return 1.3 elif 60 <= grade < 64: return 1.0 else: return 0.0 except ValueError: if grade_str == '优': return 3.9 elif grade_str == '良': return 3.0 elif grade_str == '中': return 2.0 elif grade_str == '及格': return 1.2 elif grade_str in ('不及格', '免修', '未考'): return 0.0 else: raise ValueError('{:s} 不是有效的成绩'.format(grade_str)) def cal_gpa(grades): """ 根据成绩数组计算课程平均绩点和 gpa, 算法不一定与学校一致, 结果仅供参考 :param grades: :meth:`models.StudentSession.get_my_achievements` 返回的成绩数组 :return: 包含了课程平均绩点和 gpa 的元组 """ # 课程总数 courses_sum = len(grades) # 课程绩点和 points_sum = 0 # 学分和 credit_sum = 0 # 课程学分 x 课程绩点之和 gpa_points_sum = 0 for grade in grades: point = get_point(grade.get('补考成绩') or grade['成绩']) credit = float(grade['学分']) points_sum += point credit_sum += credit gpa_points_sum += credit * point ave_point = points_sum / courses_sum gpa = gpa_points_sum / credit_sum return round(ave_point, 5), round(gpa, 5) def cal_term_code(year, is_first_term=True): """ 计算对应的学期代码 :param year: 学年开始年份,例如 "2012-2013学年第二学期" 就是 2012 :param is_first_term: 是否为第一学期 :type is_first_term: bool :return: 形如 "022" 的学期代码 """ if year <= 2001: msg = '出现了超出范围年份: {}'.format(year) raise ValueError(msg) term_code = (year - 2001) * 2 if is_first_term: term_code -= 1 return '%03d' % term_code def term_str2code(term_str): """ 将学期字符串转换为对应的学期代码串 :param term_str: 形如 "2012-2013学年第二学期" 的学期字符串 :return: 形如 "022" 的学期代码 """ result = ENV['TERM_PATTERN'].match(term_str).groups() year = int(result[0]) return cal_term_code(year, result[1] == '一') def sort_hosts(hosts, method='GET', path='/', timeout=(5, 10), **kwargs): """ 测试各个地址的速度并返回排名, 当出现错误时消耗时间为 INFINITY = 10000000 :param method: 请求方法 :param path: 默认的访问路径 :param hosts: 进行的主机地址列表, 如 `['http://222.195.8.201/']` :param timeout: 超时时间, 可以是一个浮点数或 形如 ``(连接超时, 读取超时)`` 的元祖 :param kwargs: 其他传递到 ``requests.request`` 的参数 :return: 形如 ``[(访问耗时, 地址)]`` 的排名数据 """ ranks = [] class HostCheckerThread(Thread): def __init__(self, host): super(HostCheckerThread, self).__init__() self.host = host def run(self): INFINITY = 10000000 try: url = urllib.parse.urljoin(self.host, path) res = requests.request(method, url, timeout=timeout, **kwargs) res.raise_for_status() cost = res.elapsed.total_seconds() * 1000 except Exception as e: logger.warning('访问出错: %s', e) cost = INFINITY # http://stackoverflow.com/questions/6319207/are-lists-thread-safe ranks.append((cost, self.host)) threads = [HostCheckerThread(u) for u in hosts] for t in threads: t.start() for t in threads: t.join() ranks.sort() return ranks def filter_curriculum(curriculum, week, weekday=None): """ 筛选出指定星期[和指定星期几]的课程 :param curriculum: 课程表数据 :param week: 需要筛选的周数, 是一个代表周数的正整数 :param weekday: 星期几, 是一个代表星期的整数, 1-7 对应周一到周日 :return: 如果 weekday 参数没给出, 返回的格式与原课表一致, 但只包括了在指定周数的课程, 否则返回指定周数和星期几的当天课程 """ if weekday: c = [deepcopy(curriculum[weekday - 1])] else: c = deepcopy(curriculum) for d in c: l = len(d) for t_idx in range(l): t = d[t_idx] if t is None: continue # 一般同一时间课程不会重复,重复时给出警告 t = list(filter(lambda k: week in k['上课周数'], t)) or None if t is not None and len(t) > 1: logger.warning('第 %d 周周 %d 第 %d 节课有冲突: %s', week, weekday or c.index(d) + 1, t_idx + 1, t) d[t_idx] = t return c[0] if weekday else c
earlzo/hfut
examples/curriculum_calendar.py
schedule2calendar
python
def schedule2calendar(schedule, name='课表', using_todo=True): # https://zh.wikipedia.org/wiki/ICalendar # http://icalendar.readthedocs.io/en/latest # https://tools.ietf.org/html/rfc5545 cal = icalendar.Calendar() cal.add('X-WR-TIMEZONE', 'Asia/Shanghai') cal.add('X-WR-CALNAME', name) cls = icalendar.Todo if using_todo else icalendar.Event for week, start, end, data in schedule: # "事件"组件更具通用性, Google 日历不支持"待办"组件 item = cls( SUMMARY='第{:02d}周-{}'.format(week, data), DTSTART=icalendar.vDatetime(start), DTEND=icalendar.vDatetime(end), DESCRIPTION='起始于 {}, 结束于 {}'.format(start.strftime('%H:%M'), end.strftime('%H:%M')) ) now = datetime.now() # 这个状态"事件"组件是没有的, 对于待办列表类应用有作用 # https://tools.ietf.org/html/rfc5545#section-3.2.12 if using_todo: if start < now < end: item.add('STATUS', 'IN-PROCESS') elif now > end: item.add('STATUS', 'COMPLETED') cal.add_component(item) return cal
将上课时间表转换为 icalendar :param schedule: 上课时间表 :param name: 日历名称 :param using_todo: 使用 ``icalendar.Todo`` 而不是 ``icalendar.Event`` 作为活动类 :return: icalendar.Calendar()
train
https://github.com/earlzo/hfut/blob/09270a9647fba79f26fd1a8a3c53c0678b5257a1/examples/curriculum_calendar.py#L14-L47
null
# -*- coding:utf-8 -*- """ 将课表导出为日历文件 """ from __future__ import unicode_literals from datetime import datetime import icalendar import hfut if __name__ == '__main__': session = hfut.Student('你的学号', '密码', '校区') curriculum = session.get_my_curriculum() first_day = datetime(2016, 8, 29) schedule = hfut.util.curriculum2schedule(curriculum['课表'], first_day, compress=True) print(len(hfut.util.curriculum2schedule(curriculum['课表'], first_day)), len(schedule)) cal = schedule2calendar(schedule) with open('curriculum.ics', 'wb') as fp: fp.write(cal.to_ical())
earlzo/hfut
hfut/parser.py
parse_tr_strs
python
def parse_tr_strs(trs): tr_strs = [] for tr in trs: strs = [] for td in tr.find_all('td'): text = td.get_text(strip=True) strs.append(text or None) tr_strs.append(strs) logger.debug('从行中解析出以下数据\n%s', pformat(tr_strs)) return tr_strs
将没有值但有必须要的单元格的值设置为 None 将 <tr> 标签数组内的单元格文字解析出来并返回一个二维列表 :param trs: <tr> 标签或标签数组, 为 :class:`bs4.element.Tag` 对象 :return: 二维列表
train
https://github.com/earlzo/hfut/blob/09270a9647fba79f26fd1a8a3c53c0678b5257a1/hfut/parser.py#L54-L70
null
# -*- coding:utf-8 -*- """ 页面解析相关的函数,如果你想自己编写接口可能用得到 """ from __future__ import unicode_literals import re from pprint import pformat import six from bs4 import BeautifulSoup from .log import logger from .value import ENV __all__ = [ 'GlobalFeaturedSoup', 'safe_zip', 'parse_tr_strs', 'flatten_list', 'dict_list_2_tuple_set', 'dict_list_2_matrix', 'parse_course' ] class GlobalFeaturedSoup(BeautifulSoup): def __init__(self, markup="", parse_only=None, from_encoding=None, exclude_encodings=None, **kwargs): logger.debug('Using SOUP_FEATURES: %s', ENV['SOUP_FEATURES']) super(GlobalFeaturedSoup, self).__init__( markup=markup, features=ENV['SOUP_FEATURES'], # https://www.crummy.com/software/BeautifulSoup/bs4/doc.zh/#id9 parse_only=parse_only, from_encoding=from_encoding, exclude_encodings=exclude_encodings, **kwargs ) def safe_zip(iter1, iter2, iter1_len=None, iter2_len=None): iter1 = tuple(iter1) iter2 = tuple(iter2) logger.debug('%s 与 %s 将要被 zip', iter1, iter2) if iter1_len and iter2_len: assert len(iter1) == iter1_len assert len(iter2) == iter2_len else: equal_len = iter1_len or iter2_len or len(iter1) assert len(iter1) == equal_len assert len(iter2) == equal_len return zip(iter1, iter2) def flatten_list(multiply_list): """ 碾平 list:: >>> a = [1, 2, [3, 4], [[5, 6], [7, 8]]] >>> flatten_list(a) [1, 2, 3, 4, 5, 6, 7, 8] :param multiply_list: 混淆的多层列表 :return: 单层的 list """ if isinstance(multiply_list, list): return [rv for l in multiply_list for rv in flatten_list(l)] else: return [multiply_list] def dict_list_2_tuple_set(dict_list_or_tuple_set, reverse=False): """ >>> dict_list_2_tuple_set([{'a': 1, 'b': 2}, {'c': 3, 'd': 4}]) {(('c', 3), ('d', 4)), (('a', 1), ('b', 2))} >>> dict_list_2_tuple_set({(('c', 3), ('d', 4)), (('a', 1), ('b', 2))}, reverse=True) [{'a': 1, 'b': 2}, {'c': 3, 'd': 4}] :param dict_list_or_tuple_set: 如果 ``reverse=False`` 为字典列表, 否则为元组集合 :param reverse: 是否反向转换 """ if reverse: return [dict(l) for l in dict_list_or_tuple_set] return {tuple(six.iteritems(d)) for d in dict_list_or_tuple_set} def dict_list_2_matrix(dict_list, columns): """ >>> dict_list_2_matrix([{'a': 1, 'b': 2}, {'a': 3, 'b': 4}], ('a', 'b')) [[1, 2], [3, 4]] :param dict_list: 字典列表 :param columns: 字典的键 """ k = len(columns) n = len(dict_list) result = [[None] * k for i in range(n)] for i in range(n): row = dict_list[i] for j in range(k): col = columns[j] if col in row: result[i][j] = row[col] else: result[i][j] = None return result def parse_course(course_str): """ 解析课程表里的课程 :param course_str: 形如 `单片机原理及应用[新安学堂434 (9-15周)]/数字图像处理及应用[新安学堂434 (1-7周)]/` 的课程表数据 """ # 解析课程单元格 # 所有情况 # 机械原理[一教416 (1-14周)]/ # 程序与算法综合设计[不占用教室 (18周)]/ # 财务管理[一教323 (11-17单周)]/ # 财务管理[一教323 (10-16双周)]/ # 形势与政策(4)[一教220 (2,4,6-7周)]/ p = re.compile(r'(.+?)\[(.+?)\s+\(([\d,-单双]+?)周\)\]/') courses = p.findall(course_str) results = [] for course in courses: d = {'课程名称': course[0], '课程地点': course[1]} # 解析上课周数 week_str = course[2] l = week_str.split(',') weeks = [] for v in l: m = re.match(r'(\d+)$', v) or re.match(r'(\d+)-(\d+)$', v) or re.match(r'(\d+)-(\d+)(单|双)$', v) g = m.groups() gl = len(g) if gl == 1: weeks.append(int(g[0])) elif gl == 2: weeks.extend([i for i in range(int(g[0]), int(g[1]) + 1)]) else: weeks.extend([i for i in range(int(g[0]), int(g[1]) + 1, 2)]) d['上课周数'] = weeks results.append(d) return results
earlzo/hfut
hfut/parser.py
flatten_list
python
def flatten_list(multiply_list): if isinstance(multiply_list, list): return [rv for l in multiply_list for rv in flatten_list(l)] else: return [multiply_list]
碾平 list:: >>> a = [1, 2, [3, 4], [[5, 6], [7, 8]]] >>> flatten_list(a) [1, 2, 3, 4, 5, 6, 7, 8] :param multiply_list: 混淆的多层列表 :return: 单层的 list
train
https://github.com/earlzo/hfut/blob/09270a9647fba79f26fd1a8a3c53c0678b5257a1/hfut/parser.py#L73-L87
null
# -*- coding:utf-8 -*- """ 页面解析相关的函数,如果你想自己编写接口可能用得到 """ from __future__ import unicode_literals import re from pprint import pformat import six from bs4 import BeautifulSoup from .log import logger from .value import ENV __all__ = [ 'GlobalFeaturedSoup', 'safe_zip', 'parse_tr_strs', 'flatten_list', 'dict_list_2_tuple_set', 'dict_list_2_matrix', 'parse_course' ] class GlobalFeaturedSoup(BeautifulSoup): def __init__(self, markup="", parse_only=None, from_encoding=None, exclude_encodings=None, **kwargs): logger.debug('Using SOUP_FEATURES: %s', ENV['SOUP_FEATURES']) super(GlobalFeaturedSoup, self).__init__( markup=markup, features=ENV['SOUP_FEATURES'], # https://www.crummy.com/software/BeautifulSoup/bs4/doc.zh/#id9 parse_only=parse_only, from_encoding=from_encoding, exclude_encodings=exclude_encodings, **kwargs ) def safe_zip(iter1, iter2, iter1_len=None, iter2_len=None): iter1 = tuple(iter1) iter2 = tuple(iter2) logger.debug('%s 与 %s 将要被 zip', iter1, iter2) if iter1_len and iter2_len: assert len(iter1) == iter1_len assert len(iter2) == iter2_len else: equal_len = iter1_len or iter2_len or len(iter1) assert len(iter1) == equal_len assert len(iter2) == equal_len return zip(iter1, iter2) def parse_tr_strs(trs): """ 将没有值但有必须要的单元格的值设置为 None 将 <tr> 标签数组内的单元格文字解析出来并返回一个二维列表 :param trs: <tr> 标签或标签数组, 为 :class:`bs4.element.Tag` 对象 :return: 二维列表 """ tr_strs = [] for tr in trs: strs = [] for td in tr.find_all('td'): text = td.get_text(strip=True) strs.append(text or None) tr_strs.append(strs) logger.debug('从行中解析出以下数据\n%s', pformat(tr_strs)) return tr_strs def dict_list_2_tuple_set(dict_list_or_tuple_set, reverse=False): """ >>> dict_list_2_tuple_set([{'a': 1, 'b': 2}, {'c': 3, 'd': 4}]) {(('c', 3), ('d', 4)), (('a', 1), ('b', 2))} >>> dict_list_2_tuple_set({(('c', 3), ('d', 4)), (('a', 1), ('b', 2))}, reverse=True) [{'a': 1, 'b': 2}, {'c': 3, 'd': 4}] :param dict_list_or_tuple_set: 如果 ``reverse=False`` 为字典列表, 否则为元组集合 :param reverse: 是否反向转换 """ if reverse: return [dict(l) for l in dict_list_or_tuple_set] return {tuple(six.iteritems(d)) for d in dict_list_or_tuple_set} def dict_list_2_matrix(dict_list, columns): """ >>> dict_list_2_matrix([{'a': 1, 'b': 2}, {'a': 3, 'b': 4}], ('a', 'b')) [[1, 2], [3, 4]] :param dict_list: 字典列表 :param columns: 字典的键 """ k = len(columns) n = len(dict_list) result = [[None] * k for i in range(n)] for i in range(n): row = dict_list[i] for j in range(k): col = columns[j] if col in row: result[i][j] = row[col] else: result[i][j] = None return result def parse_course(course_str): """ 解析课程表里的课程 :param course_str: 形如 `单片机原理及应用[新安学堂434 (9-15周)]/数字图像处理及应用[新安学堂434 (1-7周)]/` 的课程表数据 """ # 解析课程单元格 # 所有情况 # 机械原理[一教416 (1-14周)]/ # 程序与算法综合设计[不占用教室 (18周)]/ # 财务管理[一教323 (11-17单周)]/ # 财务管理[一教323 (10-16双周)]/ # 形势与政策(4)[一教220 (2,4,6-7周)]/ p = re.compile(r'(.+?)\[(.+?)\s+\(([\d,-单双]+?)周\)\]/') courses = p.findall(course_str) results = [] for course in courses: d = {'课程名称': course[0], '课程地点': course[1]} # 解析上课周数 week_str = course[2] l = week_str.split(',') weeks = [] for v in l: m = re.match(r'(\d+)$', v) or re.match(r'(\d+)-(\d+)$', v) or re.match(r'(\d+)-(\d+)(单|双)$', v) g = m.groups() gl = len(g) if gl == 1: weeks.append(int(g[0])) elif gl == 2: weeks.extend([i for i in range(int(g[0]), int(g[1]) + 1)]) else: weeks.extend([i for i in range(int(g[0]), int(g[1]) + 1, 2)]) d['上课周数'] = weeks results.append(d) return results
earlzo/hfut
hfut/parser.py
dict_list_2_matrix
python
def dict_list_2_matrix(dict_list, columns): k = len(columns) n = len(dict_list) result = [[None] * k for i in range(n)] for i in range(n): row = dict_list[i] for j in range(k): col = columns[j] if col in row: result[i][j] = row[col] else: result[i][j] = None return result
>>> dict_list_2_matrix([{'a': 1, 'b': 2}, {'a': 3, 'b': 4}], ('a', 'b')) [[1, 2], [3, 4]] :param dict_list: 字典列表 :param columns: 字典的键
train
https://github.com/earlzo/hfut/blob/09270a9647fba79f26fd1a8a3c53c0678b5257a1/hfut/parser.py#L106-L126
null
# -*- coding:utf-8 -*- """ 页面解析相关的函数,如果你想自己编写接口可能用得到 """ from __future__ import unicode_literals import re from pprint import pformat import six from bs4 import BeautifulSoup from .log import logger from .value import ENV __all__ = [ 'GlobalFeaturedSoup', 'safe_zip', 'parse_tr_strs', 'flatten_list', 'dict_list_2_tuple_set', 'dict_list_2_matrix', 'parse_course' ] class GlobalFeaturedSoup(BeautifulSoup): def __init__(self, markup="", parse_only=None, from_encoding=None, exclude_encodings=None, **kwargs): logger.debug('Using SOUP_FEATURES: %s', ENV['SOUP_FEATURES']) super(GlobalFeaturedSoup, self).__init__( markup=markup, features=ENV['SOUP_FEATURES'], # https://www.crummy.com/software/BeautifulSoup/bs4/doc.zh/#id9 parse_only=parse_only, from_encoding=from_encoding, exclude_encodings=exclude_encodings, **kwargs ) def safe_zip(iter1, iter2, iter1_len=None, iter2_len=None): iter1 = tuple(iter1) iter2 = tuple(iter2) logger.debug('%s 与 %s 将要被 zip', iter1, iter2) if iter1_len and iter2_len: assert len(iter1) == iter1_len assert len(iter2) == iter2_len else: equal_len = iter1_len or iter2_len or len(iter1) assert len(iter1) == equal_len assert len(iter2) == equal_len return zip(iter1, iter2) def parse_tr_strs(trs): """ 将没有值但有必须要的单元格的值设置为 None 将 <tr> 标签数组内的单元格文字解析出来并返回一个二维列表 :param trs: <tr> 标签或标签数组, 为 :class:`bs4.element.Tag` 对象 :return: 二维列表 """ tr_strs = [] for tr in trs: strs = [] for td in tr.find_all('td'): text = td.get_text(strip=True) strs.append(text or None) tr_strs.append(strs) logger.debug('从行中解析出以下数据\n%s', pformat(tr_strs)) return tr_strs def flatten_list(multiply_list): """ 碾平 list:: >>> a = [1, 2, [3, 4], [[5, 6], [7, 8]]] >>> flatten_list(a) [1, 2, 3, 4, 5, 6, 7, 8] :param multiply_list: 混淆的多层列表 :return: 单层的 list """ if isinstance(multiply_list, list): return [rv for l in multiply_list for rv in flatten_list(l)] else: return [multiply_list] def dict_list_2_tuple_set(dict_list_or_tuple_set, reverse=False): """ >>> dict_list_2_tuple_set([{'a': 1, 'b': 2}, {'c': 3, 'd': 4}]) {(('c', 3), ('d', 4)), (('a', 1), ('b', 2))} >>> dict_list_2_tuple_set({(('c', 3), ('d', 4)), (('a', 1), ('b', 2))}, reverse=True) [{'a': 1, 'b': 2}, {'c': 3, 'd': 4}] :param dict_list_or_tuple_set: 如果 ``reverse=False`` 为字典列表, 否则为元组集合 :param reverse: 是否反向转换 """ if reverse: return [dict(l) for l in dict_list_or_tuple_set] return {tuple(six.iteritems(d)) for d in dict_list_or_tuple_set} def parse_course(course_str): """ 解析课程表里的课程 :param course_str: 形如 `单片机原理及应用[新安学堂434 (9-15周)]/数字图像处理及应用[新安学堂434 (1-7周)]/` 的课程表数据 """ # 解析课程单元格 # 所有情况 # 机械原理[一教416 (1-14周)]/ # 程序与算法综合设计[不占用教室 (18周)]/ # 财务管理[一教323 (11-17单周)]/ # 财务管理[一教323 (10-16双周)]/ # 形势与政策(4)[一教220 (2,4,6-7周)]/ p = re.compile(r'(.+?)\[(.+?)\s+\(([\d,-单双]+?)周\)\]/') courses = p.findall(course_str) results = [] for course in courses: d = {'课程名称': course[0], '课程地点': course[1]} # 解析上课周数 week_str = course[2] l = week_str.split(',') weeks = [] for v in l: m = re.match(r'(\d+)$', v) or re.match(r'(\d+)-(\d+)$', v) or re.match(r'(\d+)-(\d+)(单|双)$', v) g = m.groups() gl = len(g) if gl == 1: weeks.append(int(g[0])) elif gl == 2: weeks.extend([i for i in range(int(g[0]), int(g[1]) + 1)]) else: weeks.extend([i for i in range(int(g[0]), int(g[1]) + 1, 2)]) d['上课周数'] = weeks results.append(d) return results
earlzo/hfut
hfut/parser.py
parse_course
python
def parse_course(course_str): # 解析课程单元格 # 所有情况 # 机械原理[一教416 (1-14周)]/ # 程序与算法综合设计[不占用教室 (18周)]/ # 财务管理[一教323 (11-17单周)]/ # 财务管理[一教323 (10-16双周)]/ # 形势与政策(4)[一教220 (2,4,6-7周)]/ p = re.compile(r'(.+?)\[(.+?)\s+\(([\d,-单双]+?)周\)\]/') courses = p.findall(course_str) results = [] for course in courses: d = {'课程名称': course[0], '课程地点': course[1]} # 解析上课周数 week_str = course[2] l = week_str.split(',') weeks = [] for v in l: m = re.match(r'(\d+)$', v) or re.match(r'(\d+)-(\d+)$', v) or re.match(r'(\d+)-(\d+)(单|双)$', v) g = m.groups() gl = len(g) if gl == 1: weeks.append(int(g[0])) elif gl == 2: weeks.extend([i for i in range(int(g[0]), int(g[1]) + 1)]) else: weeks.extend([i for i in range(int(g[0]), int(g[1]) + 1, 2)]) d['上课周数'] = weeks results.append(d) return results
解析课程表里的课程 :param course_str: 形如 `单片机原理及应用[新安学堂434 (9-15周)]/数字图像处理及应用[新安学堂434 (1-7周)]/` 的课程表数据
train
https://github.com/earlzo/hfut/blob/09270a9647fba79f26fd1a8a3c53c0678b5257a1/hfut/parser.py#L129-L163
null
# -*- coding:utf-8 -*- """ 页面解析相关的函数,如果你想自己编写接口可能用得到 """ from __future__ import unicode_literals import re from pprint import pformat import six from bs4 import BeautifulSoup from .log import logger from .value import ENV __all__ = [ 'GlobalFeaturedSoup', 'safe_zip', 'parse_tr_strs', 'flatten_list', 'dict_list_2_tuple_set', 'dict_list_2_matrix', 'parse_course' ] class GlobalFeaturedSoup(BeautifulSoup): def __init__(self, markup="", parse_only=None, from_encoding=None, exclude_encodings=None, **kwargs): logger.debug('Using SOUP_FEATURES: %s', ENV['SOUP_FEATURES']) super(GlobalFeaturedSoup, self).__init__( markup=markup, features=ENV['SOUP_FEATURES'], # https://www.crummy.com/software/BeautifulSoup/bs4/doc.zh/#id9 parse_only=parse_only, from_encoding=from_encoding, exclude_encodings=exclude_encodings, **kwargs ) def safe_zip(iter1, iter2, iter1_len=None, iter2_len=None): iter1 = tuple(iter1) iter2 = tuple(iter2) logger.debug('%s 与 %s 将要被 zip', iter1, iter2) if iter1_len and iter2_len: assert len(iter1) == iter1_len assert len(iter2) == iter2_len else: equal_len = iter1_len or iter2_len or len(iter1) assert len(iter1) == equal_len assert len(iter2) == equal_len return zip(iter1, iter2) def parse_tr_strs(trs): """ 将没有值但有必须要的单元格的值设置为 None 将 <tr> 标签数组内的单元格文字解析出来并返回一个二维列表 :param trs: <tr> 标签或标签数组, 为 :class:`bs4.element.Tag` 对象 :return: 二维列表 """ tr_strs = [] for tr in trs: strs = [] for td in tr.find_all('td'): text = td.get_text(strip=True) strs.append(text or None) tr_strs.append(strs) logger.debug('从行中解析出以下数据\n%s', pformat(tr_strs)) return tr_strs def flatten_list(multiply_list): """ 碾平 list:: >>> a = [1, 2, [3, 4], [[5, 6], [7, 8]]] >>> flatten_list(a) [1, 2, 3, 4, 5, 6, 7, 8] :param multiply_list: 混淆的多层列表 :return: 单层的 list """ if isinstance(multiply_list, list): return [rv for l in multiply_list for rv in flatten_list(l)] else: return [multiply_list] def dict_list_2_tuple_set(dict_list_or_tuple_set, reverse=False): """ >>> dict_list_2_tuple_set([{'a': 1, 'b': 2}, {'c': 3, 'd': 4}]) {(('c', 3), ('d', 4)), (('a', 1), ('b', 2))} >>> dict_list_2_tuple_set({(('c', 3), ('d', 4)), (('a', 1), ('b', 2))}, reverse=True) [{'a': 1, 'b': 2}, {'c': 3, 'd': 4}] :param dict_list_or_tuple_set: 如果 ``reverse=False`` 为字典列表, 否则为元组集合 :param reverse: 是否反向转换 """ if reverse: return [dict(l) for l in dict_list_or_tuple_set] return {tuple(six.iteritems(d)) for d in dict_list_or_tuple_set} def dict_list_2_matrix(dict_list, columns): """ >>> dict_list_2_matrix([{'a': 1, 'b': 2}, {'a': 3, 'b': 4}], ('a', 'b')) [[1, 2], [3, 4]] :param dict_list: 字典列表 :param columns: 字典的键 """ k = len(columns) n = len(dict_list) result = [[None] * k for i in range(n)] for i in range(n): row = dict_list[i] for j in range(k): col = columns[j] if col in row: result[i][j] = row[col] else: result[i][j] = None return result
earlzo/hfut
hfut/shortcut.py
Guest.get_class_students
python
def get_class_students(self, xqdm, kcdm, jxbh): return self.query(GetClassStudents(xqdm, kcdm, jxbh))
教学班查询, 查询指定教学班的所有学生 @structure {'学期': str, '班级名称': str, '学生': [{'姓名': str, '学号': int}]} :param xqdm: 学期代码 :param kcdm: 课程代码 :param jxbh: 教学班号
train
https://github.com/earlzo/hfut/blob/09270a9647fba79f26fd1a8a3c53c0678b5257a1/hfut/shortcut.py#L47-L57
[ "def query(self, interface):\n response = self.request(interface)\n return interface.parse(response)\n" ]
class Guest(BaseShortcuts): def __init__(self, *args, **kwargs): self.session = GuestSession(*args, **kwargs) def get_system_status(self): """ 获取教务系统当前状态信息, 包括当前学期以及选课计划 @structure {'当前学期': str, '选课计划': [(float, float)], '当前轮数': int or None} """ return self.query(GetSystemStatus()) def get_class_info(self, xqdm, kcdm, jxbh): """ 获取教学班详情, 包括上课时间地点, 考查方式, 老师, 选中人数, 课程容量等等信息 @structure {'校区': str,'开课单位': str,'考核类型': str,'课程类型': str,'课程名称': str,'教学班号': str,'起止周': str, '时间地点': str,'学分': float,'性别限制': str,'优选范围': str,'禁选范围': str,'选中人数': int,'备注': str} :param xqdm: 学期代码 :param kcdm: 课程代码 :param jxbh: 教学班号 """ return self.query(GetClassInfo(xqdm, kcdm, jxbh)) def search_course(self, xqdm, kcdm=None, kcmc=None): """ 课程查询 @structure [{'任课教师': str, '课程名称': str, '教学班号': str, '课程代码': str, '班级容量': int}] :param xqdm: 学期代码 :param kcdm: 课程代码 :param kcmc: 课程名称 """ return self.query(SearchCourse(xqdm, kcdm, kcmc)) def get_teaching_plan(self, xqdm, kclx='b', zydm=''): """ 专业教学计划查询, 可以查询全校公选课, 此时可以不填 `zydm` @structure [{'开课单位': str, '学时': int, '课程名称': str, '课程代码': str, '学分': float}] :param xqdm: 学期代码 :param kclx: 课程类型参数,只有两个值 b:专业必修课, x:全校公选课 :param zydm: 专业代码, 可以从 :meth:`models.StudentSession.get_code` 获得 """ return self.query(GetTeachingPlan(xqdm, kclx, zydm)) def get_teacher_info(self, jsh): """ 教师信息查询 @structure {'教研室': str, '教学课程': str, '学历': str, '教龄': str, '教师寄语': str, '简 历': str, '照片': str, '科研方向': str, '出生': str, '姓名': str, '联系电话': [str], '职称': str, '电子邮件': str, '性别': str, '学位': str, '院系': str] :param jsh: 8位教师号, 例如 '05000162' """ return self.query(GetTeacherInfo(jsh)) def get_course_classes(self, kcdm): """ 获取选课系统中课程的可选教学班级(不可选的班级即使人数未满也不能选) @structure {'可选班级': [{'起止周': str, '考核类型': str, '教学班附加信息': str, '课程容量': int, '选中人数': int, '教学班号': str, '禁选专业': str, '教师': [str], '校区': str, '优选范围': [str], '开课时间,开课地点': [str]}], '课程代码': str, '课程名称': str} :param kcdm: 课程代码 """ return self.query(GetCourseClasses(kcdm)) def get_entire_curriculum(self, xqdm=None): """ 获取全校的学期课程表, 当没有提供学期代码时默认返回本学期课程表 @structure {'课表': [[[{'上课周数': [int], '课程名称': str, '课程地点': str}]]], '起始周': int, '结束周': int} :param xqdm: 学期代码 """ return self.query(GetEntireCurriculum(xqdm))
earlzo/hfut
hfut/shortcut.py
Guest.get_class_info
python
def get_class_info(self, xqdm, kcdm, jxbh): return self.query(GetClassInfo(xqdm, kcdm, jxbh))
获取教学班详情, 包括上课时间地点, 考查方式, 老师, 选中人数, 课程容量等等信息 @structure {'校区': str,'开课单位': str,'考核类型': str,'课程类型': str,'课程名称': str,'教学班号': str,'起止周': str, '时间地点': str,'学分': float,'性别限制': str,'优选范围': str,'禁选范围': str,'选中人数': int,'备注': str} :param xqdm: 学期代码 :param kcdm: 课程代码 :param jxbh: 教学班号
train
https://github.com/earlzo/hfut/blob/09270a9647fba79f26fd1a8a3c53c0678b5257a1/hfut/shortcut.py#L59-L70
[ "def query(self, interface):\n response = self.request(interface)\n return interface.parse(response)\n" ]
class Guest(BaseShortcuts): def __init__(self, *args, **kwargs): self.session = GuestSession(*args, **kwargs) def get_system_status(self): """ 获取教务系统当前状态信息, 包括当前学期以及选课计划 @structure {'当前学期': str, '选课计划': [(float, float)], '当前轮数': int or None} """ return self.query(GetSystemStatus()) def get_class_students(self, xqdm, kcdm, jxbh): """ 教学班查询, 查询指定教学班的所有学生 @structure {'学期': str, '班级名称': str, '学生': [{'姓名': str, '学号': int}]} :param xqdm: 学期代码 :param kcdm: 课程代码 :param jxbh: 教学班号 """ return self.query(GetClassStudents(xqdm, kcdm, jxbh)) def search_course(self, xqdm, kcdm=None, kcmc=None): """ 课程查询 @structure [{'任课教师': str, '课程名称': str, '教学班号': str, '课程代码': str, '班级容量': int}] :param xqdm: 学期代码 :param kcdm: 课程代码 :param kcmc: 课程名称 """ return self.query(SearchCourse(xqdm, kcdm, kcmc)) def get_teaching_plan(self, xqdm, kclx='b', zydm=''): """ 专业教学计划查询, 可以查询全校公选课, 此时可以不填 `zydm` @structure [{'开课单位': str, '学时': int, '课程名称': str, '课程代码': str, '学分': float}] :param xqdm: 学期代码 :param kclx: 课程类型参数,只有两个值 b:专业必修课, x:全校公选课 :param zydm: 专业代码, 可以从 :meth:`models.StudentSession.get_code` 获得 """ return self.query(GetTeachingPlan(xqdm, kclx, zydm)) def get_teacher_info(self, jsh): """ 教师信息查询 @structure {'教研室': str, '教学课程': str, '学历': str, '教龄': str, '教师寄语': str, '简 历': str, '照片': str, '科研方向': str, '出生': str, '姓名': str, '联系电话': [str], '职称': str, '电子邮件': str, '性别': str, '学位': str, '院系': str] :param jsh: 8位教师号, 例如 '05000162' """ return self.query(GetTeacherInfo(jsh)) def get_course_classes(self, kcdm): """ 获取选课系统中课程的可选教学班级(不可选的班级即使人数未满也不能选) @structure {'可选班级': [{'起止周': str, '考核类型': str, '教学班附加信息': str, '课程容量': int, '选中人数': int, '教学班号': str, '禁选专业': str, '教师': [str], '校区': str, '优选范围': [str], '开课时间,开课地点': [str]}], '课程代码': str, '课程名称': str} :param kcdm: 课程代码 """ return self.query(GetCourseClasses(kcdm)) def get_entire_curriculum(self, xqdm=None): """ 获取全校的学期课程表, 当没有提供学期代码时默认返回本学期课程表 @structure {'课表': [[[{'上课周数': [int], '课程名称': str, '课程地点': str}]]], '起始周': int, '结束周': int} :param xqdm: 学期代码 """ return self.query(GetEntireCurriculum(xqdm))
earlzo/hfut
hfut/shortcut.py
Guest.search_course
python
def search_course(self, xqdm, kcdm=None, kcmc=None): return self.query(SearchCourse(xqdm, kcdm, kcmc))
课程查询 @structure [{'任课教师': str, '课程名称': str, '教学班号': str, '课程代码': str, '班级容量': int}] :param xqdm: 学期代码 :param kcdm: 课程代码 :param kcmc: 课程名称
train
https://github.com/earlzo/hfut/blob/09270a9647fba79f26fd1a8a3c53c0678b5257a1/hfut/shortcut.py#L72-L82
[ "def query(self, interface):\n response = self.request(interface)\n return interface.parse(response)\n" ]
class Guest(BaseShortcuts): def __init__(self, *args, **kwargs): self.session = GuestSession(*args, **kwargs) def get_system_status(self): """ 获取教务系统当前状态信息, 包括当前学期以及选课计划 @structure {'当前学期': str, '选课计划': [(float, float)], '当前轮数': int or None} """ return self.query(GetSystemStatus()) def get_class_students(self, xqdm, kcdm, jxbh): """ 教学班查询, 查询指定教学班的所有学生 @structure {'学期': str, '班级名称': str, '学生': [{'姓名': str, '学号': int}]} :param xqdm: 学期代码 :param kcdm: 课程代码 :param jxbh: 教学班号 """ return self.query(GetClassStudents(xqdm, kcdm, jxbh)) def get_class_info(self, xqdm, kcdm, jxbh): """ 获取教学班详情, 包括上课时间地点, 考查方式, 老师, 选中人数, 课程容量等等信息 @structure {'校区': str,'开课单位': str,'考核类型': str,'课程类型': str,'课程名称': str,'教学班号': str,'起止周': str, '时间地点': str,'学分': float,'性别限制': str,'优选范围': str,'禁选范围': str,'选中人数': int,'备注': str} :param xqdm: 学期代码 :param kcdm: 课程代码 :param jxbh: 教学班号 """ return self.query(GetClassInfo(xqdm, kcdm, jxbh)) def get_teaching_plan(self, xqdm, kclx='b', zydm=''): """ 专业教学计划查询, 可以查询全校公选课, 此时可以不填 `zydm` @structure [{'开课单位': str, '学时': int, '课程名称': str, '课程代码': str, '学分': float}] :param xqdm: 学期代码 :param kclx: 课程类型参数,只有两个值 b:专业必修课, x:全校公选课 :param zydm: 专业代码, 可以从 :meth:`models.StudentSession.get_code` 获得 """ return self.query(GetTeachingPlan(xqdm, kclx, zydm)) def get_teacher_info(self, jsh): """ 教师信息查询 @structure {'教研室': str, '教学课程': str, '学历': str, '教龄': str, '教师寄语': str, '简 历': str, '照片': str, '科研方向': str, '出生': str, '姓名': str, '联系电话': [str], '职称': str, '电子邮件': str, '性别': str, '学位': str, '院系': str] :param jsh: 8位教师号, 例如 '05000162' """ return self.query(GetTeacherInfo(jsh)) def get_course_classes(self, kcdm): """ 获取选课系统中课程的可选教学班级(不可选的班级即使人数未满也不能选) @structure {'可选班级': [{'起止周': str, '考核类型': str, '教学班附加信息': str, '课程容量': int, '选中人数': int, '教学班号': str, '禁选专业': str, '教师': [str], '校区': str, '优选范围': [str], '开课时间,开课地点': [str]}], '课程代码': str, '课程名称': str} :param kcdm: 课程代码 """ return self.query(GetCourseClasses(kcdm)) def get_entire_curriculum(self, xqdm=None): """ 获取全校的学期课程表, 当没有提供学期代码时默认返回本学期课程表 @structure {'课表': [[[{'上课周数': [int], '课程名称': str, '课程地点': str}]]], '起始周': int, '结束周': int} :param xqdm: 学期代码 """ return self.query(GetEntireCurriculum(xqdm))
earlzo/hfut
hfut/shortcut.py
Guest.get_teaching_plan
python
def get_teaching_plan(self, xqdm, kclx='b', zydm=''): return self.query(GetTeachingPlan(xqdm, kclx, zydm))
专业教学计划查询, 可以查询全校公选课, 此时可以不填 `zydm` @structure [{'开课单位': str, '学时': int, '课程名称': str, '课程代码': str, '学分': float}] :param xqdm: 学期代码 :param kclx: 课程类型参数,只有两个值 b:专业必修课, x:全校公选课 :param zydm: 专业代码, 可以从 :meth:`models.StudentSession.get_code` 获得
train
https://github.com/earlzo/hfut/blob/09270a9647fba79f26fd1a8a3c53c0678b5257a1/hfut/shortcut.py#L84-L94
[ "def query(self, interface):\n response = self.request(interface)\n return interface.parse(response)\n" ]
class Guest(BaseShortcuts): def __init__(self, *args, **kwargs): self.session = GuestSession(*args, **kwargs) def get_system_status(self): """ 获取教务系统当前状态信息, 包括当前学期以及选课计划 @structure {'当前学期': str, '选课计划': [(float, float)], '当前轮数': int or None} """ return self.query(GetSystemStatus()) def get_class_students(self, xqdm, kcdm, jxbh): """ 教学班查询, 查询指定教学班的所有学生 @structure {'学期': str, '班级名称': str, '学生': [{'姓名': str, '学号': int}]} :param xqdm: 学期代码 :param kcdm: 课程代码 :param jxbh: 教学班号 """ return self.query(GetClassStudents(xqdm, kcdm, jxbh)) def get_class_info(self, xqdm, kcdm, jxbh): """ 获取教学班详情, 包括上课时间地点, 考查方式, 老师, 选中人数, 课程容量等等信息 @structure {'校区': str,'开课单位': str,'考核类型': str,'课程类型': str,'课程名称': str,'教学班号': str,'起止周': str, '时间地点': str,'学分': float,'性别限制': str,'优选范围': str,'禁选范围': str,'选中人数': int,'备注': str} :param xqdm: 学期代码 :param kcdm: 课程代码 :param jxbh: 教学班号 """ return self.query(GetClassInfo(xqdm, kcdm, jxbh)) def search_course(self, xqdm, kcdm=None, kcmc=None): """ 课程查询 @structure [{'任课教师': str, '课程名称': str, '教学班号': str, '课程代码': str, '班级容量': int}] :param xqdm: 学期代码 :param kcdm: 课程代码 :param kcmc: 课程名称 """ return self.query(SearchCourse(xqdm, kcdm, kcmc)) def get_teacher_info(self, jsh): """ 教师信息查询 @structure {'教研室': str, '教学课程': str, '学历': str, '教龄': str, '教师寄语': str, '简 历': str, '照片': str, '科研方向': str, '出生': str, '姓名': str, '联系电话': [str], '职称': str, '电子邮件': str, '性别': str, '学位': str, '院系': str] :param jsh: 8位教师号, 例如 '05000162' """ return self.query(GetTeacherInfo(jsh)) def get_course_classes(self, kcdm): """ 获取选课系统中课程的可选教学班级(不可选的班级即使人数未满也不能选) @structure {'可选班级': [{'起止周': str, '考核类型': str, '教学班附加信息': str, '课程容量': int, '选中人数': int, '教学班号': str, '禁选专业': str, '教师': [str], '校区': str, '优选范围': [str], '开课时间,开课地点': [str]}], '课程代码': str, '课程名称': str} :param kcdm: 课程代码 """ return self.query(GetCourseClasses(kcdm)) def get_entire_curriculum(self, xqdm=None): """ 获取全校的学期课程表, 当没有提供学期代码时默认返回本学期课程表 @structure {'课表': [[[{'上课周数': [int], '课程名称': str, '课程地点': str}]]], '起始周': int, '结束周': int} :param xqdm: 学期代码 """ return self.query(GetEntireCurriculum(xqdm))
earlzo/hfut
hfut/shortcut.py
Student.change_password
python
def change_password(self, new_password): if self.session.campus == HF: raise ValueError('合肥校区使用信息中心账号登录, 修改教务密码没有作用') # 若新密码与原密码相同, 直接返回 True if new_password == self.session.password: raise ValueError('原密码与新密码相同') result = self.query(ChangePassword(self.session.password, new_password)) if result: self.session.password = new_password return result
修改教务密码, **注意** 合肥校区使用信息中心账号登录, 与教务密码不一致, 即使修改了也没有作用, 因此合肥校区帐号调用此接口会直接报错 @structure bool :param new_password: 新密码
train
https://github.com/earlzo/hfut/blob/09270a9647fba79f26fd1a8a3c53c0678b5257a1/hfut/shortcut.py#L179-L197
[ "def query(self, interface):\n response = self.request(interface)\n return interface.parse(response)\n" ]
class Student(Guest): def __init__(self, *args, **kwargs): self.session = StudentSession(*args, **kwargs) def get_code(self): """ 获取当前所有的学期, 学期以及对应的学期代码, 注意如果你只是需要获取某个学期的代码的话请使用 :func:`util.cal_term_code` @structure {'专业': [{'专业代码': str, '专业名称': str}], '学期': [{'学期代码': str, '学期名称': str}]} """ return self.query(GetCode()) def get_my_info(self): """ 获取个人信息 @structure {'婚姻状况': str, '毕业高中': str, '专业简称': str, '家庭地址': str, '能否选课': str, '政治面貌': str, '性别': str, '学院简称': str, '外语语种': str, '入学方式': str, '照片': str, '联系电话': str, '姓名': str, '入学时间': str, '籍贯': str, '民族': str, '学号': int, '家庭电话': str, '生源地': str, '出生日期': str, '学籍状态': str, '身份证号': str, '考生号': int, '班级简称': str, '注册状态': str} """ return self.query(GetMyInfo()) def get_my_achievements(self): """ 获取个人成绩 @structure [{'教学班号': str, '课程名称': str, '学期': str, '补考成绩': str, '课程代码': str, '学分': float, '成绩': str}] """ return self.query(GetMyAchievements()) def get_my_curriculum(self): """ 获取个人课表 @structure {'课表': [[[{'上课周数': [int], '课程名称': str, '课程地点': str}]]], '起始周': int, '结束周': int} """ return self.query(GetMyCurriculum()) def get_my_fees(self): """ 收费查询 @structure [{'教学班号': str, '课程名称': str, '学期': str, '收费(元): float', '课程代码': str, '学分': float}] """ return self.query(GetMyFees()) def set_telephone(self, tel): """ 更新电话 @structure bool :param tel: 电话号码, 需要满足手机和普通电话的格式, 例如 `18112345678` 或者 '0791-1234567' """ return type(tel)(self.query(SetTelephone(tel))) == tel # ========== 选课功能相关 ========== def get_optional_courses(self, kclx='x'): """ 获取可选课程, 并不判断是否选满 @structure [{'学分': float, '开课院系': str, '课程代码': str, '课程名称': str, '课程类型': str}] :param kclx: 课程类型参数,只有三个值,{x:全校公选课, b:全校必修课, jh:本专业计划},默认为'x' """ return self.query(GetOptionalCourses(kclx)) def get_selected_courses(self): """ 获取所有已选的课程 @structure [{'费用': float, '教学班号': str, '课程名称': str, '课程代码': str, '学分': float, '课程类型': str}] """ return self.query(GetSelectedCourses()) def get_unfinished_evaluation(self): """ 获取未完成的课程评价 @structure [{'教学班号': str, '课程名称': str, '课程代码': str}] """ return self.query(GetUnfinishedEvaluation()) def evaluate_course(self, kcdm, jxbh, r101=1, r102=1, r103=1, r104=1, r105=1, r106=1, r107=1, r108=1, r109=1, r201=3, r202=3, advice=''): """ 课程评价, 数值为 1-5, r1 类选项 1 为最好, 5 为最差, r2 类选项程度由深到浅, 3 为最好. 默认都是最好的选项 :param kcdm: 课程代码 :param jxbh: 教学班号 :param r101: 教学态度认真,课前准备充分 :param r102: 教授内容充实,要点重点突出 :param r103: 理论联系实际,反映最新成果 :param r104: 教学方法灵活,师生互动得当 :param r105: 运用现代技术,教学手段多样 :param r106: 注重因材施教,加强能力培养 :param r107: 严格要求管理,关心爱护学生 :param r108: 处处为人师表,注重教书育人 :param r109: 教学综合效果 :param r201: 课程内容 :param r202: 课程负担 :param advice: 其他建议,不能超过120字且不能使用分号,单引号,都好 :return: """ return self.query(EvaluateCourse( kcdm, jxbh, r101, r102, r103, r104, r105, r106, r107, r108, r109, r201, r202, advice )) def change_course(self, select_courses=None, delete_courses=None): """ 修改个人的课程 @structure [{'费用': float, '教学班号': str, '课程名称': str, '课程代码': str, '学分': float, '课程类型': str}] :param select_courses: 形如 ``[{'kcdm': '9900039X', 'jxbhs': {'0001', '0002'}}]`` 的课程代码与教学班号列表, jxbhs 可以为空代表选择所有可选班级 :param delete_courses: 需要删除的课程代码集合, 如 ``{'0200011B'}`` :return: 选课结果, 返回选中的课程教学班列表, 结构与 ``get_selected_courses`` 一致 """ # 框架重构后调整接口的调用 t = self.get_system_status() if t['当前轮数'] is None: raise ValueError('当前为 %s,选课系统尚未开启', t['当前学期']) if not (select_courses or delete_courses): raise ValueError('select_courses, delete_courses 参数不能都为空!') # 参数处理 select_courses = select_courses or [] delete_courses = {l.upper() for l in (delete_courses or [])} selected_courses = self.get_selected_courses() selected_kcdms = {course['课程代码'] for course in selected_courses} # 尝试删除没有被选中的课程会出错 unselected = delete_courses.difference(selected_kcdms) if unselected: msg = '无法删除没有被选的课程 {}'.format(unselected) logger.warning(msg) # 要提交的 kcdm 数据 kcdms_data = [] # 要提交的 jxbh 数据 jxbhs_data = [] # 必须添加已选课程, 同时去掉要删除的课程 for course in selected_courses: if course['课程代码'] not in delete_courses: kcdms_data.append(course['课程代码']) jxbhs_data.append(course['教学班号']) # 选课 for kv in select_courses: kcdm = kv['kcdm'].upper() jxbhs = set(kv['jxbhs']) if kv.get('jxbhs') else set() teaching_classes = self.get_course_classes(kcdm) if not teaching_classes: logger.warning('课程[%s]没有可选班级', kcdm) continue # 反正是统一提交, 不需要判断是否已满 optional_jxbhs = {c['教学班号'] for c in teaching_classes['可选班级']} if jxbhs: wrong_jxbhs = jxbhs.difference(optional_jxbhs) if wrong_jxbhs: msg = '课程[{}]{}没有教学班号{}'.format(kcdm, teaching_classes['课程名称'], wrong_jxbhs) logger.warning(msg) jxbhs = jxbhs.intersection(optional_jxbhs) else: jxbhs = optional_jxbhs for jxbh in jxbhs: kcdms_data.append(kcdm) jxbhs_data.append(jxbh) return self.query(ChangeCourse(self.session.account, select_courses, delete_courses)) # ---------- 不需要专门的请求 ---------- def check_courses(self, kcdms): """ 检查课程是否被选 @structure [bool] :param kcdms: 课程代码列表 :return: 与课程代码列表长度一致的布尔值列表, 已为True,未选为False """ selected_courses = self.get_selected_courses() selected_kcdms = {course['课程代码'] for course in selected_courses} result = [True if kcdm in selected_kcdms else False for kcdm in kcdms] return result def get_selectable_courses(self, kcdms=None, pool_size=5, dump_result=True, filename='可选课程.json', encoding='utf-8'): """ 获取所有能够选上的课程的课程班级, 注意这个方法遍历所给出的课程和它们的可选班级, 当选中人数大于等于课程容量时表示不可选. 由于请求非常耗时且一般情况下用不到, 因此默认推荐在第一轮选课结束后到第三轮选课结束之前的时间段使用, 如果你仍然坚持使用, 你将会得到一个警告. @structure [{'可选班级': [{'起止周': str, '考核类型': str, '教学班附加信息': str, '课程容量': int, '选中人数': int, '教学班号': str, '禁选专业': str, '教师': [str], '校区': str, '优选范围': [str], '开课时间,开课地点': [str]}], '课程代码': str, '课程名称': str}] :param kcdms: 课程代码列表, 默认为所有可选课程的课程代码 :param dump_result: 是否保存结果到本地 :param filename: 保存的文件路径 :param encoding: 文件编码 """ now = time.time() t = self.get_system_status() if not (t['选课计划'][0][1] < now < t['选课计划'][2][1]): logger.warning('只推荐在第一轮选课结束到第三轮选课结束之间的时间段使用本接口!') def iter_kcdms(): for l in self.get_optional_courses(): yield l['课程代码'] kcdms = kcdms or iter_kcdms() def target(kcdm): course_classes = self.get_course_classes(kcdm) if not course_classes: return course_classes['可选班级'] = [c for c in course_classes['可选班级'] if c['课程容量'] > c['选中人数']] if len(course_classes['可选班级']) > 0: return course_classes # Python 2.7 不支持 with 语法 pool = Pool(pool_size) result = list(filter(None, pool.map(target, kcdms))) pool.close() pool.join() if dump_result: json_str = json.dumps(result, ensure_ascii=False, indent=4, sort_keys=True) with open(filename, 'wb') as fp: fp.write(json_str.encode(encoding)) logger.info('可选课程结果导出到了:%s', filename) return result
earlzo/hfut
hfut/shortcut.py
Student.set_telephone
python
def set_telephone(self, tel): return type(tel)(self.query(SetTelephone(tel))) == tel
更新电话 @structure bool :param tel: 电话号码, 需要满足手机和普通电话的格式, 例如 `18112345678` 或者 '0791-1234567'
train
https://github.com/earlzo/hfut/blob/09270a9647fba79f26fd1a8a3c53c0678b5257a1/hfut/shortcut.py#L199-L208
[ "def query(self, interface):\n response = self.request(interface)\n return interface.parse(response)\n" ]
class Student(Guest): def __init__(self, *args, **kwargs): self.session = StudentSession(*args, **kwargs) def get_code(self): """ 获取当前所有的学期, 学期以及对应的学期代码, 注意如果你只是需要获取某个学期的代码的话请使用 :func:`util.cal_term_code` @structure {'专业': [{'专业代码': str, '专业名称': str}], '学期': [{'学期代码': str, '学期名称': str}]} """ return self.query(GetCode()) def get_my_info(self): """ 获取个人信息 @structure {'婚姻状况': str, '毕业高中': str, '专业简称': str, '家庭地址': str, '能否选课': str, '政治面貌': str, '性别': str, '学院简称': str, '外语语种': str, '入学方式': str, '照片': str, '联系电话': str, '姓名': str, '入学时间': str, '籍贯': str, '民族': str, '学号': int, '家庭电话': str, '生源地': str, '出生日期': str, '学籍状态': str, '身份证号': str, '考生号': int, '班级简称': str, '注册状态': str} """ return self.query(GetMyInfo()) def get_my_achievements(self): """ 获取个人成绩 @structure [{'教学班号': str, '课程名称': str, '学期': str, '补考成绩': str, '课程代码': str, '学分': float, '成绩': str}] """ return self.query(GetMyAchievements()) def get_my_curriculum(self): """ 获取个人课表 @structure {'课表': [[[{'上课周数': [int], '课程名称': str, '课程地点': str}]]], '起始周': int, '结束周': int} """ return self.query(GetMyCurriculum()) def get_my_fees(self): """ 收费查询 @structure [{'教学班号': str, '课程名称': str, '学期': str, '收费(元): float', '课程代码': str, '学分': float}] """ return self.query(GetMyFees()) def change_password(self, new_password): """ 修改教务密码, **注意** 合肥校区使用信息中心账号登录, 与教务密码不一致, 即使修改了也没有作用, 因此合肥校区帐号调用此接口会直接报错 @structure bool :param new_password: 新密码 """ if self.session.campus == HF: raise ValueError('合肥校区使用信息中心账号登录, 修改教务密码没有作用') # 若新密码与原密码相同, 直接返回 True if new_password == self.session.password: raise ValueError('原密码与新密码相同') result = self.query(ChangePassword(self.session.password, new_password)) if result: self.session.password = new_password return result # ========== 选课功能相关 ========== def get_optional_courses(self, kclx='x'): """ 获取可选课程, 并不判断是否选满 @structure [{'学分': float, '开课院系': str, '课程代码': str, '课程名称': str, '课程类型': str}] :param kclx: 课程类型参数,只有三个值,{x:全校公选课, b:全校必修课, jh:本专业计划},默认为'x' """ return self.query(GetOptionalCourses(kclx)) def get_selected_courses(self): """ 获取所有已选的课程 @structure [{'费用': float, '教学班号': str, '课程名称': str, '课程代码': str, '学分': float, '课程类型': str}] """ return self.query(GetSelectedCourses()) def get_unfinished_evaluation(self): """ 获取未完成的课程评价 @structure [{'教学班号': str, '课程名称': str, '课程代码': str}] """ return self.query(GetUnfinishedEvaluation()) def evaluate_course(self, kcdm, jxbh, r101=1, r102=1, r103=1, r104=1, r105=1, r106=1, r107=1, r108=1, r109=1, r201=3, r202=3, advice=''): """ 课程评价, 数值为 1-5, r1 类选项 1 为最好, 5 为最差, r2 类选项程度由深到浅, 3 为最好. 默认都是最好的选项 :param kcdm: 课程代码 :param jxbh: 教学班号 :param r101: 教学态度认真,课前准备充分 :param r102: 教授内容充实,要点重点突出 :param r103: 理论联系实际,反映最新成果 :param r104: 教学方法灵活,师生互动得当 :param r105: 运用现代技术,教学手段多样 :param r106: 注重因材施教,加强能力培养 :param r107: 严格要求管理,关心爱护学生 :param r108: 处处为人师表,注重教书育人 :param r109: 教学综合效果 :param r201: 课程内容 :param r202: 课程负担 :param advice: 其他建议,不能超过120字且不能使用分号,单引号,都好 :return: """ return self.query(EvaluateCourse( kcdm, jxbh, r101, r102, r103, r104, r105, r106, r107, r108, r109, r201, r202, advice )) def change_course(self, select_courses=None, delete_courses=None): """ 修改个人的课程 @structure [{'费用': float, '教学班号': str, '课程名称': str, '课程代码': str, '学分': float, '课程类型': str}] :param select_courses: 形如 ``[{'kcdm': '9900039X', 'jxbhs': {'0001', '0002'}}]`` 的课程代码与教学班号列表, jxbhs 可以为空代表选择所有可选班级 :param delete_courses: 需要删除的课程代码集合, 如 ``{'0200011B'}`` :return: 选课结果, 返回选中的课程教学班列表, 结构与 ``get_selected_courses`` 一致 """ # 框架重构后调整接口的调用 t = self.get_system_status() if t['当前轮数'] is None: raise ValueError('当前为 %s,选课系统尚未开启', t['当前学期']) if not (select_courses or delete_courses): raise ValueError('select_courses, delete_courses 参数不能都为空!') # 参数处理 select_courses = select_courses or [] delete_courses = {l.upper() for l in (delete_courses or [])} selected_courses = self.get_selected_courses() selected_kcdms = {course['课程代码'] for course in selected_courses} # 尝试删除没有被选中的课程会出错 unselected = delete_courses.difference(selected_kcdms) if unselected: msg = '无法删除没有被选的课程 {}'.format(unselected) logger.warning(msg) # 要提交的 kcdm 数据 kcdms_data = [] # 要提交的 jxbh 数据 jxbhs_data = [] # 必须添加已选课程, 同时去掉要删除的课程 for course in selected_courses: if course['课程代码'] not in delete_courses: kcdms_data.append(course['课程代码']) jxbhs_data.append(course['教学班号']) # 选课 for kv in select_courses: kcdm = kv['kcdm'].upper() jxbhs = set(kv['jxbhs']) if kv.get('jxbhs') else set() teaching_classes = self.get_course_classes(kcdm) if not teaching_classes: logger.warning('课程[%s]没有可选班级', kcdm) continue # 反正是统一提交, 不需要判断是否已满 optional_jxbhs = {c['教学班号'] for c in teaching_classes['可选班级']} if jxbhs: wrong_jxbhs = jxbhs.difference(optional_jxbhs) if wrong_jxbhs: msg = '课程[{}]{}没有教学班号{}'.format(kcdm, teaching_classes['课程名称'], wrong_jxbhs) logger.warning(msg) jxbhs = jxbhs.intersection(optional_jxbhs) else: jxbhs = optional_jxbhs for jxbh in jxbhs: kcdms_data.append(kcdm) jxbhs_data.append(jxbh) return self.query(ChangeCourse(self.session.account, select_courses, delete_courses)) # ---------- 不需要专门的请求 ---------- def check_courses(self, kcdms): """ 检查课程是否被选 @structure [bool] :param kcdms: 课程代码列表 :return: 与课程代码列表长度一致的布尔值列表, 已为True,未选为False """ selected_courses = self.get_selected_courses() selected_kcdms = {course['课程代码'] for course in selected_courses} result = [True if kcdm in selected_kcdms else False for kcdm in kcdms] return result def get_selectable_courses(self, kcdms=None, pool_size=5, dump_result=True, filename='可选课程.json', encoding='utf-8'): """ 获取所有能够选上的课程的课程班级, 注意这个方法遍历所给出的课程和它们的可选班级, 当选中人数大于等于课程容量时表示不可选. 由于请求非常耗时且一般情况下用不到, 因此默认推荐在第一轮选课结束后到第三轮选课结束之前的时间段使用, 如果你仍然坚持使用, 你将会得到一个警告. @structure [{'可选班级': [{'起止周': str, '考核类型': str, '教学班附加信息': str, '课程容量': int, '选中人数': int, '教学班号': str, '禁选专业': str, '教师': [str], '校区': str, '优选范围': [str], '开课时间,开课地点': [str]}], '课程代码': str, '课程名称': str}] :param kcdms: 课程代码列表, 默认为所有可选课程的课程代码 :param dump_result: 是否保存结果到本地 :param filename: 保存的文件路径 :param encoding: 文件编码 """ now = time.time() t = self.get_system_status() if not (t['选课计划'][0][1] < now < t['选课计划'][2][1]): logger.warning('只推荐在第一轮选课结束到第三轮选课结束之间的时间段使用本接口!') def iter_kcdms(): for l in self.get_optional_courses(): yield l['课程代码'] kcdms = kcdms or iter_kcdms() def target(kcdm): course_classes = self.get_course_classes(kcdm) if not course_classes: return course_classes['可选班级'] = [c for c in course_classes['可选班级'] if c['课程容量'] > c['选中人数']] if len(course_classes['可选班级']) > 0: return course_classes # Python 2.7 不支持 with 语法 pool = Pool(pool_size) result = list(filter(None, pool.map(target, kcdms))) pool.close() pool.join() if dump_result: json_str = json.dumps(result, ensure_ascii=False, indent=4, sort_keys=True) with open(filename, 'wb') as fp: fp.write(json_str.encode(encoding)) logger.info('可选课程结果导出到了:%s', filename) return result
earlzo/hfut
hfut/shortcut.py
Student.evaluate_course
python
def evaluate_course(self, kcdm, jxbh, r101=1, r102=1, r103=1, r104=1, r105=1, r106=1, r107=1, r108=1, r109=1, r201=3, r202=3, advice=''): return self.query(EvaluateCourse( kcdm, jxbh, r101, r102, r103, r104, r105, r106, r107, r108, r109, r201, r202, advice ))
课程评价, 数值为 1-5, r1 类选项 1 为最好, 5 为最差, r2 类选项程度由深到浅, 3 为最好. 默认都是最好的选项 :param kcdm: 课程代码 :param jxbh: 教学班号 :param r101: 教学态度认真,课前准备充分 :param r102: 教授内容充实,要点重点突出 :param r103: 理论联系实际,反映最新成果 :param r104: 教学方法灵活,师生互动得当 :param r105: 运用现代技术,教学手段多样 :param r106: 注重因材施教,加强能力培养 :param r107: 严格要求管理,关心爱护学生 :param r108: 处处为人师表,注重教书育人 :param r109: 教学综合效果 :param r201: 课程内容 :param r202: 课程负担 :param advice: 其他建议,不能超过120字且不能使用分号,单引号,都好 :return:
train
https://github.com/earlzo/hfut/blob/09270a9647fba79f26fd1a8a3c53c0678b5257a1/hfut/shortcut.py#L237-L265
[ "def query(self, interface):\n response = self.request(interface)\n return interface.parse(response)\n" ]
class Student(Guest): def __init__(self, *args, **kwargs): self.session = StudentSession(*args, **kwargs) def get_code(self): """ 获取当前所有的学期, 学期以及对应的学期代码, 注意如果你只是需要获取某个学期的代码的话请使用 :func:`util.cal_term_code` @structure {'专业': [{'专业代码': str, '专业名称': str}], '学期': [{'学期代码': str, '学期名称': str}]} """ return self.query(GetCode()) def get_my_info(self): """ 获取个人信息 @structure {'婚姻状况': str, '毕业高中': str, '专业简称': str, '家庭地址': str, '能否选课': str, '政治面貌': str, '性别': str, '学院简称': str, '外语语种': str, '入学方式': str, '照片': str, '联系电话': str, '姓名': str, '入学时间': str, '籍贯': str, '民族': str, '学号': int, '家庭电话': str, '生源地': str, '出生日期': str, '学籍状态': str, '身份证号': str, '考生号': int, '班级简称': str, '注册状态': str} """ return self.query(GetMyInfo()) def get_my_achievements(self): """ 获取个人成绩 @structure [{'教学班号': str, '课程名称': str, '学期': str, '补考成绩': str, '课程代码': str, '学分': float, '成绩': str}] """ return self.query(GetMyAchievements()) def get_my_curriculum(self): """ 获取个人课表 @structure {'课表': [[[{'上课周数': [int], '课程名称': str, '课程地点': str}]]], '起始周': int, '结束周': int} """ return self.query(GetMyCurriculum()) def get_my_fees(self): """ 收费查询 @structure [{'教学班号': str, '课程名称': str, '学期': str, '收费(元): float', '课程代码': str, '学分': float}] """ return self.query(GetMyFees()) def change_password(self, new_password): """ 修改教务密码, **注意** 合肥校区使用信息中心账号登录, 与教务密码不一致, 即使修改了也没有作用, 因此合肥校区帐号调用此接口会直接报错 @structure bool :param new_password: 新密码 """ if self.session.campus == HF: raise ValueError('合肥校区使用信息中心账号登录, 修改教务密码没有作用') # 若新密码与原密码相同, 直接返回 True if new_password == self.session.password: raise ValueError('原密码与新密码相同') result = self.query(ChangePassword(self.session.password, new_password)) if result: self.session.password = new_password return result def set_telephone(self, tel): """ 更新电话 @structure bool :param tel: 电话号码, 需要满足手机和普通电话的格式, 例如 `18112345678` 或者 '0791-1234567' """ return type(tel)(self.query(SetTelephone(tel))) == tel # ========== 选课功能相关 ========== def get_optional_courses(self, kclx='x'): """ 获取可选课程, 并不判断是否选满 @structure [{'学分': float, '开课院系': str, '课程代码': str, '课程名称': str, '课程类型': str}] :param kclx: 课程类型参数,只有三个值,{x:全校公选课, b:全校必修课, jh:本专业计划},默认为'x' """ return self.query(GetOptionalCourses(kclx)) def get_selected_courses(self): """ 获取所有已选的课程 @structure [{'费用': float, '教学班号': str, '课程名称': str, '课程代码': str, '学分': float, '课程类型': str}] """ return self.query(GetSelectedCourses()) def get_unfinished_evaluation(self): """ 获取未完成的课程评价 @structure [{'教学班号': str, '课程名称': str, '课程代码': str}] """ return self.query(GetUnfinishedEvaluation()) def change_course(self, select_courses=None, delete_courses=None): """ 修改个人的课程 @structure [{'费用': float, '教学班号': str, '课程名称': str, '课程代码': str, '学分': float, '课程类型': str}] :param select_courses: 形如 ``[{'kcdm': '9900039X', 'jxbhs': {'0001', '0002'}}]`` 的课程代码与教学班号列表, jxbhs 可以为空代表选择所有可选班级 :param delete_courses: 需要删除的课程代码集合, 如 ``{'0200011B'}`` :return: 选课结果, 返回选中的课程教学班列表, 结构与 ``get_selected_courses`` 一致 """ # 框架重构后调整接口的调用 t = self.get_system_status() if t['当前轮数'] is None: raise ValueError('当前为 %s,选课系统尚未开启', t['当前学期']) if not (select_courses or delete_courses): raise ValueError('select_courses, delete_courses 参数不能都为空!') # 参数处理 select_courses = select_courses or [] delete_courses = {l.upper() for l in (delete_courses or [])} selected_courses = self.get_selected_courses() selected_kcdms = {course['课程代码'] for course in selected_courses} # 尝试删除没有被选中的课程会出错 unselected = delete_courses.difference(selected_kcdms) if unselected: msg = '无法删除没有被选的课程 {}'.format(unselected) logger.warning(msg) # 要提交的 kcdm 数据 kcdms_data = [] # 要提交的 jxbh 数据 jxbhs_data = [] # 必须添加已选课程, 同时去掉要删除的课程 for course in selected_courses: if course['课程代码'] not in delete_courses: kcdms_data.append(course['课程代码']) jxbhs_data.append(course['教学班号']) # 选课 for kv in select_courses: kcdm = kv['kcdm'].upper() jxbhs = set(kv['jxbhs']) if kv.get('jxbhs') else set() teaching_classes = self.get_course_classes(kcdm) if not teaching_classes: logger.warning('课程[%s]没有可选班级', kcdm) continue # 反正是统一提交, 不需要判断是否已满 optional_jxbhs = {c['教学班号'] for c in teaching_classes['可选班级']} if jxbhs: wrong_jxbhs = jxbhs.difference(optional_jxbhs) if wrong_jxbhs: msg = '课程[{}]{}没有教学班号{}'.format(kcdm, teaching_classes['课程名称'], wrong_jxbhs) logger.warning(msg) jxbhs = jxbhs.intersection(optional_jxbhs) else: jxbhs = optional_jxbhs for jxbh in jxbhs: kcdms_data.append(kcdm) jxbhs_data.append(jxbh) return self.query(ChangeCourse(self.session.account, select_courses, delete_courses)) # ---------- 不需要专门的请求 ---------- def check_courses(self, kcdms): """ 检查课程是否被选 @structure [bool] :param kcdms: 课程代码列表 :return: 与课程代码列表长度一致的布尔值列表, 已为True,未选为False """ selected_courses = self.get_selected_courses() selected_kcdms = {course['课程代码'] for course in selected_courses} result = [True if kcdm in selected_kcdms else False for kcdm in kcdms] return result def get_selectable_courses(self, kcdms=None, pool_size=5, dump_result=True, filename='可选课程.json', encoding='utf-8'): """ 获取所有能够选上的课程的课程班级, 注意这个方法遍历所给出的课程和它们的可选班级, 当选中人数大于等于课程容量时表示不可选. 由于请求非常耗时且一般情况下用不到, 因此默认推荐在第一轮选课结束后到第三轮选课结束之前的时间段使用, 如果你仍然坚持使用, 你将会得到一个警告. @structure [{'可选班级': [{'起止周': str, '考核类型': str, '教学班附加信息': str, '课程容量': int, '选中人数': int, '教学班号': str, '禁选专业': str, '教师': [str], '校区': str, '优选范围': [str], '开课时间,开课地点': [str]}], '课程代码': str, '课程名称': str}] :param kcdms: 课程代码列表, 默认为所有可选课程的课程代码 :param dump_result: 是否保存结果到本地 :param filename: 保存的文件路径 :param encoding: 文件编码 """ now = time.time() t = self.get_system_status() if not (t['选课计划'][0][1] < now < t['选课计划'][2][1]): logger.warning('只推荐在第一轮选课结束到第三轮选课结束之间的时间段使用本接口!') def iter_kcdms(): for l in self.get_optional_courses(): yield l['课程代码'] kcdms = kcdms or iter_kcdms() def target(kcdm): course_classes = self.get_course_classes(kcdm) if not course_classes: return course_classes['可选班级'] = [c for c in course_classes['可选班级'] if c['课程容量'] > c['选中人数']] if len(course_classes['可选班级']) > 0: return course_classes # Python 2.7 不支持 with 语法 pool = Pool(pool_size) result = list(filter(None, pool.map(target, kcdms))) pool.close() pool.join() if dump_result: json_str = json.dumps(result, ensure_ascii=False, indent=4, sort_keys=True) with open(filename, 'wb') as fp: fp.write(json_str.encode(encoding)) logger.info('可选课程结果导出到了:%s', filename) return result
earlzo/hfut
hfut/shortcut.py
Student.change_course
python
def change_course(self, select_courses=None, delete_courses=None): # 框架重构后调整接口的调用 t = self.get_system_status() if t['当前轮数'] is None: raise ValueError('当前为 %s,选课系统尚未开启', t['当前学期']) if not (select_courses or delete_courses): raise ValueError('select_courses, delete_courses 参数不能都为空!') # 参数处理 select_courses = select_courses or [] delete_courses = {l.upper() for l in (delete_courses or [])} selected_courses = self.get_selected_courses() selected_kcdms = {course['课程代码'] for course in selected_courses} # 尝试删除没有被选中的课程会出错 unselected = delete_courses.difference(selected_kcdms) if unselected: msg = '无法删除没有被选的课程 {}'.format(unselected) logger.warning(msg) # 要提交的 kcdm 数据 kcdms_data = [] # 要提交的 jxbh 数据 jxbhs_data = [] # 必须添加已选课程, 同时去掉要删除的课程 for course in selected_courses: if course['课程代码'] not in delete_courses: kcdms_data.append(course['课程代码']) jxbhs_data.append(course['教学班号']) # 选课 for kv in select_courses: kcdm = kv['kcdm'].upper() jxbhs = set(kv['jxbhs']) if kv.get('jxbhs') else set() teaching_classes = self.get_course_classes(kcdm) if not teaching_classes: logger.warning('课程[%s]没有可选班级', kcdm) continue # 反正是统一提交, 不需要判断是否已满 optional_jxbhs = {c['教学班号'] for c in teaching_classes['可选班级']} if jxbhs: wrong_jxbhs = jxbhs.difference(optional_jxbhs) if wrong_jxbhs: msg = '课程[{}]{}没有教学班号{}'.format(kcdm, teaching_classes['课程名称'], wrong_jxbhs) logger.warning(msg) jxbhs = jxbhs.intersection(optional_jxbhs) else: jxbhs = optional_jxbhs for jxbh in jxbhs: kcdms_data.append(kcdm) jxbhs_data.append(jxbh) return self.query(ChangeCourse(self.session.account, select_courses, delete_courses))
修改个人的课程 @structure [{'费用': float, '教学班号': str, '课程名称': str, '课程代码': str, '学分': float, '课程类型': str}] :param select_courses: 形如 ``[{'kcdm': '9900039X', 'jxbhs': {'0001', '0002'}}]`` 的课程代码与教学班号列表, jxbhs 可以为空代表选择所有可选班级 :param delete_courses: 需要删除的课程代码集合, 如 ``{'0200011B'}`` :return: 选课结果, 返回选中的课程教学班列表, 结构与 ``get_selected_courses`` 一致
train
https://github.com/earlzo/hfut/blob/09270a9647fba79f26fd1a8a3c53c0678b5257a1/hfut/shortcut.py#L267-L333
[ "def query(self, interface):\n response = self.request(interface)\n return interface.parse(response)\n", "def get_system_status(self):\n \"\"\"\n 获取教务系统当前状态信息, 包括当前学期以及选课计划\n\n @structure {'当前学期': str, '选课计划': [(float, float)], '当前轮数': int or None}\n \"\"\"\n return self.query(GetSystemStatus...
class Student(Guest): def __init__(self, *args, **kwargs): self.session = StudentSession(*args, **kwargs) def get_code(self): """ 获取当前所有的学期, 学期以及对应的学期代码, 注意如果你只是需要获取某个学期的代码的话请使用 :func:`util.cal_term_code` @structure {'专业': [{'专业代码': str, '专业名称': str}], '学期': [{'学期代码': str, '学期名称': str}]} """ return self.query(GetCode()) def get_my_info(self): """ 获取个人信息 @structure {'婚姻状况': str, '毕业高中': str, '专业简称': str, '家庭地址': str, '能否选课': str, '政治面貌': str, '性别': str, '学院简称': str, '外语语种': str, '入学方式': str, '照片': str, '联系电话': str, '姓名': str, '入学时间': str, '籍贯': str, '民族': str, '学号': int, '家庭电话': str, '生源地': str, '出生日期': str, '学籍状态': str, '身份证号': str, '考生号': int, '班级简称': str, '注册状态': str} """ return self.query(GetMyInfo()) def get_my_achievements(self): """ 获取个人成绩 @structure [{'教学班号': str, '课程名称': str, '学期': str, '补考成绩': str, '课程代码': str, '学分': float, '成绩': str}] """ return self.query(GetMyAchievements()) def get_my_curriculum(self): """ 获取个人课表 @structure {'课表': [[[{'上课周数': [int], '课程名称': str, '课程地点': str}]]], '起始周': int, '结束周': int} """ return self.query(GetMyCurriculum()) def get_my_fees(self): """ 收费查询 @structure [{'教学班号': str, '课程名称': str, '学期': str, '收费(元): float', '课程代码': str, '学分': float}] """ return self.query(GetMyFees()) def change_password(self, new_password): """ 修改教务密码, **注意** 合肥校区使用信息中心账号登录, 与教务密码不一致, 即使修改了也没有作用, 因此合肥校区帐号调用此接口会直接报错 @structure bool :param new_password: 新密码 """ if self.session.campus == HF: raise ValueError('合肥校区使用信息中心账号登录, 修改教务密码没有作用') # 若新密码与原密码相同, 直接返回 True if new_password == self.session.password: raise ValueError('原密码与新密码相同') result = self.query(ChangePassword(self.session.password, new_password)) if result: self.session.password = new_password return result def set_telephone(self, tel): """ 更新电话 @structure bool :param tel: 电话号码, 需要满足手机和普通电话的格式, 例如 `18112345678` 或者 '0791-1234567' """ return type(tel)(self.query(SetTelephone(tel))) == tel # ========== 选课功能相关 ========== def get_optional_courses(self, kclx='x'): """ 获取可选课程, 并不判断是否选满 @structure [{'学分': float, '开课院系': str, '课程代码': str, '课程名称': str, '课程类型': str}] :param kclx: 课程类型参数,只有三个值,{x:全校公选课, b:全校必修课, jh:本专业计划},默认为'x' """ return self.query(GetOptionalCourses(kclx)) def get_selected_courses(self): """ 获取所有已选的课程 @structure [{'费用': float, '教学班号': str, '课程名称': str, '课程代码': str, '学分': float, '课程类型': str}] """ return self.query(GetSelectedCourses()) def get_unfinished_evaluation(self): """ 获取未完成的课程评价 @structure [{'教学班号': str, '课程名称': str, '课程代码': str}] """ return self.query(GetUnfinishedEvaluation()) def evaluate_course(self, kcdm, jxbh, r101=1, r102=1, r103=1, r104=1, r105=1, r106=1, r107=1, r108=1, r109=1, r201=3, r202=3, advice=''): """ 课程评价, 数值为 1-5, r1 类选项 1 为最好, 5 为最差, r2 类选项程度由深到浅, 3 为最好. 默认都是最好的选项 :param kcdm: 课程代码 :param jxbh: 教学班号 :param r101: 教学态度认真,课前准备充分 :param r102: 教授内容充实,要点重点突出 :param r103: 理论联系实际,反映最新成果 :param r104: 教学方法灵活,师生互动得当 :param r105: 运用现代技术,教学手段多样 :param r106: 注重因材施教,加强能力培养 :param r107: 严格要求管理,关心爱护学生 :param r108: 处处为人师表,注重教书育人 :param r109: 教学综合效果 :param r201: 课程内容 :param r202: 课程负担 :param advice: 其他建议,不能超过120字且不能使用分号,单引号,都好 :return: """ return self.query(EvaluateCourse( kcdm, jxbh, r101, r102, r103, r104, r105, r106, r107, r108, r109, r201, r202, advice )) # ---------- 不需要专门的请求 ---------- def check_courses(self, kcdms): """ 检查课程是否被选 @structure [bool] :param kcdms: 课程代码列表 :return: 与课程代码列表长度一致的布尔值列表, 已为True,未选为False """ selected_courses = self.get_selected_courses() selected_kcdms = {course['课程代码'] for course in selected_courses} result = [True if kcdm in selected_kcdms else False for kcdm in kcdms] return result def get_selectable_courses(self, kcdms=None, pool_size=5, dump_result=True, filename='可选课程.json', encoding='utf-8'): """ 获取所有能够选上的课程的课程班级, 注意这个方法遍历所给出的课程和它们的可选班级, 当选中人数大于等于课程容量时表示不可选. 由于请求非常耗时且一般情况下用不到, 因此默认推荐在第一轮选课结束后到第三轮选课结束之前的时间段使用, 如果你仍然坚持使用, 你将会得到一个警告. @structure [{'可选班级': [{'起止周': str, '考核类型': str, '教学班附加信息': str, '课程容量': int, '选中人数': int, '教学班号': str, '禁选专业': str, '教师': [str], '校区': str, '优选范围': [str], '开课时间,开课地点': [str]}], '课程代码': str, '课程名称': str}] :param kcdms: 课程代码列表, 默认为所有可选课程的课程代码 :param dump_result: 是否保存结果到本地 :param filename: 保存的文件路径 :param encoding: 文件编码 """ now = time.time() t = self.get_system_status() if not (t['选课计划'][0][1] < now < t['选课计划'][2][1]): logger.warning('只推荐在第一轮选课结束到第三轮选课结束之间的时间段使用本接口!') def iter_kcdms(): for l in self.get_optional_courses(): yield l['课程代码'] kcdms = kcdms or iter_kcdms() def target(kcdm): course_classes = self.get_course_classes(kcdm) if not course_classes: return course_classes['可选班级'] = [c for c in course_classes['可选班级'] if c['课程容量'] > c['选中人数']] if len(course_classes['可选班级']) > 0: return course_classes # Python 2.7 不支持 with 语法 pool = Pool(pool_size) result = list(filter(None, pool.map(target, kcdms))) pool.close() pool.join() if dump_result: json_str = json.dumps(result, ensure_ascii=False, indent=4, sort_keys=True) with open(filename, 'wb') as fp: fp.write(json_str.encode(encoding)) logger.info('可选课程结果导出到了:%s', filename) return result
earlzo/hfut
hfut/shortcut.py
Student.check_courses
python
def check_courses(self, kcdms): selected_courses = self.get_selected_courses() selected_kcdms = {course['课程代码'] for course in selected_courses} result = [True if kcdm in selected_kcdms else False for kcdm in kcdms] return result
检查课程是否被选 @structure [bool] :param kcdms: 课程代码列表 :return: 与课程代码列表长度一致的布尔值列表, 已为True,未选为False
train
https://github.com/earlzo/hfut/blob/09270a9647fba79f26fd1a8a3c53c0678b5257a1/hfut/shortcut.py#L336-L348
[ "def get_selected_courses(self):\n \"\"\"\n 获取所有已选的课程\n\n @structure [{'费用': float, '教学班号': str, '课程名称': str, '课程代码': str, '学分': float, '课程类型': str}]\n \"\"\"\n return self.query(GetSelectedCourses())\n" ]
class Student(Guest): def __init__(self, *args, **kwargs): self.session = StudentSession(*args, **kwargs) def get_code(self): """ 获取当前所有的学期, 学期以及对应的学期代码, 注意如果你只是需要获取某个学期的代码的话请使用 :func:`util.cal_term_code` @structure {'专业': [{'专业代码': str, '专业名称': str}], '学期': [{'学期代码': str, '学期名称': str}]} """ return self.query(GetCode()) def get_my_info(self): """ 获取个人信息 @structure {'婚姻状况': str, '毕业高中': str, '专业简称': str, '家庭地址': str, '能否选课': str, '政治面貌': str, '性别': str, '学院简称': str, '外语语种': str, '入学方式': str, '照片': str, '联系电话': str, '姓名': str, '入学时间': str, '籍贯': str, '民族': str, '学号': int, '家庭电话': str, '生源地': str, '出生日期': str, '学籍状态': str, '身份证号': str, '考生号': int, '班级简称': str, '注册状态': str} """ return self.query(GetMyInfo()) def get_my_achievements(self): """ 获取个人成绩 @structure [{'教学班号': str, '课程名称': str, '学期': str, '补考成绩': str, '课程代码': str, '学分': float, '成绩': str}] """ return self.query(GetMyAchievements()) def get_my_curriculum(self): """ 获取个人课表 @structure {'课表': [[[{'上课周数': [int], '课程名称': str, '课程地点': str}]]], '起始周': int, '结束周': int} """ return self.query(GetMyCurriculum()) def get_my_fees(self): """ 收费查询 @structure [{'教学班号': str, '课程名称': str, '学期': str, '收费(元): float', '课程代码': str, '学分': float}] """ return self.query(GetMyFees()) def change_password(self, new_password): """ 修改教务密码, **注意** 合肥校区使用信息中心账号登录, 与教务密码不一致, 即使修改了也没有作用, 因此合肥校区帐号调用此接口会直接报错 @structure bool :param new_password: 新密码 """ if self.session.campus == HF: raise ValueError('合肥校区使用信息中心账号登录, 修改教务密码没有作用') # 若新密码与原密码相同, 直接返回 True if new_password == self.session.password: raise ValueError('原密码与新密码相同') result = self.query(ChangePassword(self.session.password, new_password)) if result: self.session.password = new_password return result def set_telephone(self, tel): """ 更新电话 @structure bool :param tel: 电话号码, 需要满足手机和普通电话的格式, 例如 `18112345678` 或者 '0791-1234567' """ return type(tel)(self.query(SetTelephone(tel))) == tel # ========== 选课功能相关 ========== def get_optional_courses(self, kclx='x'): """ 获取可选课程, 并不判断是否选满 @structure [{'学分': float, '开课院系': str, '课程代码': str, '课程名称': str, '课程类型': str}] :param kclx: 课程类型参数,只有三个值,{x:全校公选课, b:全校必修课, jh:本专业计划},默认为'x' """ return self.query(GetOptionalCourses(kclx)) def get_selected_courses(self): """ 获取所有已选的课程 @structure [{'费用': float, '教学班号': str, '课程名称': str, '课程代码': str, '学分': float, '课程类型': str}] """ return self.query(GetSelectedCourses()) def get_unfinished_evaluation(self): """ 获取未完成的课程评价 @structure [{'教学班号': str, '课程名称': str, '课程代码': str}] """ return self.query(GetUnfinishedEvaluation()) def evaluate_course(self, kcdm, jxbh, r101=1, r102=1, r103=1, r104=1, r105=1, r106=1, r107=1, r108=1, r109=1, r201=3, r202=3, advice=''): """ 课程评价, 数值为 1-5, r1 类选项 1 为最好, 5 为最差, r2 类选项程度由深到浅, 3 为最好. 默认都是最好的选项 :param kcdm: 课程代码 :param jxbh: 教学班号 :param r101: 教学态度认真,课前准备充分 :param r102: 教授内容充实,要点重点突出 :param r103: 理论联系实际,反映最新成果 :param r104: 教学方法灵活,师生互动得当 :param r105: 运用现代技术,教学手段多样 :param r106: 注重因材施教,加强能力培养 :param r107: 严格要求管理,关心爱护学生 :param r108: 处处为人师表,注重教书育人 :param r109: 教学综合效果 :param r201: 课程内容 :param r202: 课程负担 :param advice: 其他建议,不能超过120字且不能使用分号,单引号,都好 :return: """ return self.query(EvaluateCourse( kcdm, jxbh, r101, r102, r103, r104, r105, r106, r107, r108, r109, r201, r202, advice )) def change_course(self, select_courses=None, delete_courses=None): """ 修改个人的课程 @structure [{'费用': float, '教学班号': str, '课程名称': str, '课程代码': str, '学分': float, '课程类型': str}] :param select_courses: 形如 ``[{'kcdm': '9900039X', 'jxbhs': {'0001', '0002'}}]`` 的课程代码与教学班号列表, jxbhs 可以为空代表选择所有可选班级 :param delete_courses: 需要删除的课程代码集合, 如 ``{'0200011B'}`` :return: 选课结果, 返回选中的课程教学班列表, 结构与 ``get_selected_courses`` 一致 """ # 框架重构后调整接口的调用 t = self.get_system_status() if t['当前轮数'] is None: raise ValueError('当前为 %s,选课系统尚未开启', t['当前学期']) if not (select_courses or delete_courses): raise ValueError('select_courses, delete_courses 参数不能都为空!') # 参数处理 select_courses = select_courses or [] delete_courses = {l.upper() for l in (delete_courses or [])} selected_courses = self.get_selected_courses() selected_kcdms = {course['课程代码'] for course in selected_courses} # 尝试删除没有被选中的课程会出错 unselected = delete_courses.difference(selected_kcdms) if unselected: msg = '无法删除没有被选的课程 {}'.format(unselected) logger.warning(msg) # 要提交的 kcdm 数据 kcdms_data = [] # 要提交的 jxbh 数据 jxbhs_data = [] # 必须添加已选课程, 同时去掉要删除的课程 for course in selected_courses: if course['课程代码'] not in delete_courses: kcdms_data.append(course['课程代码']) jxbhs_data.append(course['教学班号']) # 选课 for kv in select_courses: kcdm = kv['kcdm'].upper() jxbhs = set(kv['jxbhs']) if kv.get('jxbhs') else set() teaching_classes = self.get_course_classes(kcdm) if not teaching_classes: logger.warning('课程[%s]没有可选班级', kcdm) continue # 反正是统一提交, 不需要判断是否已满 optional_jxbhs = {c['教学班号'] for c in teaching_classes['可选班级']} if jxbhs: wrong_jxbhs = jxbhs.difference(optional_jxbhs) if wrong_jxbhs: msg = '课程[{}]{}没有教学班号{}'.format(kcdm, teaching_classes['课程名称'], wrong_jxbhs) logger.warning(msg) jxbhs = jxbhs.intersection(optional_jxbhs) else: jxbhs = optional_jxbhs for jxbh in jxbhs: kcdms_data.append(kcdm) jxbhs_data.append(jxbh) return self.query(ChangeCourse(self.session.account, select_courses, delete_courses)) # ---------- 不需要专门的请求 ---------- def get_selectable_courses(self, kcdms=None, pool_size=5, dump_result=True, filename='可选课程.json', encoding='utf-8'): """ 获取所有能够选上的课程的课程班级, 注意这个方法遍历所给出的课程和它们的可选班级, 当选中人数大于等于课程容量时表示不可选. 由于请求非常耗时且一般情况下用不到, 因此默认推荐在第一轮选课结束后到第三轮选课结束之前的时间段使用, 如果你仍然坚持使用, 你将会得到一个警告. @structure [{'可选班级': [{'起止周': str, '考核类型': str, '教学班附加信息': str, '课程容量': int, '选中人数': int, '教学班号': str, '禁选专业': str, '教师': [str], '校区': str, '优选范围': [str], '开课时间,开课地点': [str]}], '课程代码': str, '课程名称': str}] :param kcdms: 课程代码列表, 默认为所有可选课程的课程代码 :param dump_result: 是否保存结果到本地 :param filename: 保存的文件路径 :param encoding: 文件编码 """ now = time.time() t = self.get_system_status() if not (t['选课计划'][0][1] < now < t['选课计划'][2][1]): logger.warning('只推荐在第一轮选课结束到第三轮选课结束之间的时间段使用本接口!') def iter_kcdms(): for l in self.get_optional_courses(): yield l['课程代码'] kcdms = kcdms or iter_kcdms() def target(kcdm): course_classes = self.get_course_classes(kcdm) if not course_classes: return course_classes['可选班级'] = [c for c in course_classes['可选班级'] if c['课程容量'] > c['选中人数']] if len(course_classes['可选班级']) > 0: return course_classes # Python 2.7 不支持 with 语法 pool = Pool(pool_size) result = list(filter(None, pool.map(target, kcdms))) pool.close() pool.join() if dump_result: json_str = json.dumps(result, ensure_ascii=False, indent=4, sort_keys=True) with open(filename, 'wb') as fp: fp.write(json_str.encode(encoding)) logger.info('可选课程结果导出到了:%s', filename) return result
earlzo/hfut
hfut/shortcut.py
Student.get_selectable_courses
python
def get_selectable_courses(self, kcdms=None, pool_size=5, dump_result=True, filename='可选课程.json', encoding='utf-8'): now = time.time() t = self.get_system_status() if not (t['选课计划'][0][1] < now < t['选课计划'][2][1]): logger.warning('只推荐在第一轮选课结束到第三轮选课结束之间的时间段使用本接口!') def iter_kcdms(): for l in self.get_optional_courses(): yield l['课程代码'] kcdms = kcdms or iter_kcdms() def target(kcdm): course_classes = self.get_course_classes(kcdm) if not course_classes: return course_classes['可选班级'] = [c for c in course_classes['可选班级'] if c['课程容量'] > c['选中人数']] if len(course_classes['可选班级']) > 0: return course_classes # Python 2.7 不支持 with 语法 pool = Pool(pool_size) result = list(filter(None, pool.map(target, kcdms))) pool.close() pool.join() if dump_result: json_str = json.dumps(result, ensure_ascii=False, indent=4, sort_keys=True) with open(filename, 'wb') as fp: fp.write(json_str.encode(encoding)) logger.info('可选课程结果导出到了:%s', filename) return result
获取所有能够选上的课程的课程班级, 注意这个方法遍历所给出的课程和它们的可选班级, 当选中人数大于等于课程容量时表示不可选. 由于请求非常耗时且一般情况下用不到, 因此默认推荐在第一轮选课结束后到第三轮选课结束之前的时间段使用, 如果你仍然坚持使用, 你将会得到一个警告. @structure [{'可选班级': [{'起止周': str, '考核类型': str, '教学班附加信息': str, '课程容量': int, '选中人数': int, '教学班号': str, '禁选专业': str, '教师': [str], '校区': str, '优选范围': [str], '开课时间,开课地点': [str]}], '课程代码': str, '课程名称': str}] :param kcdms: 课程代码列表, 默认为所有可选课程的课程代码 :param dump_result: 是否保存结果到本地 :param filename: 保存的文件路径 :param encoding: 文件编码
train
https://github.com/earlzo/hfut/blob/09270a9647fba79f26fd1a8a3c53c0678b5257a1/hfut/shortcut.py#L350-L395
[ "def get_system_status(self):\n \"\"\"\n 获取教务系统当前状态信息, 包括当前学期以及选课计划\n\n @structure {'当前学期': str, '选课计划': [(float, float)], '当前轮数': int or None}\n \"\"\"\n return self.query(GetSystemStatus())\n", "def iter_kcdms():\n for l in self.get_optional_courses():\n yield l['课程代码']\n" ]
class Student(Guest): def __init__(self, *args, **kwargs): self.session = StudentSession(*args, **kwargs) def get_code(self): """ 获取当前所有的学期, 学期以及对应的学期代码, 注意如果你只是需要获取某个学期的代码的话请使用 :func:`util.cal_term_code` @structure {'专业': [{'专业代码': str, '专业名称': str}], '学期': [{'学期代码': str, '学期名称': str}]} """ return self.query(GetCode()) def get_my_info(self): """ 获取个人信息 @structure {'婚姻状况': str, '毕业高中': str, '专业简称': str, '家庭地址': str, '能否选课': str, '政治面貌': str, '性别': str, '学院简称': str, '外语语种': str, '入学方式': str, '照片': str, '联系电话': str, '姓名': str, '入学时间': str, '籍贯': str, '民族': str, '学号': int, '家庭电话': str, '生源地': str, '出生日期': str, '学籍状态': str, '身份证号': str, '考生号': int, '班级简称': str, '注册状态': str} """ return self.query(GetMyInfo()) def get_my_achievements(self): """ 获取个人成绩 @structure [{'教学班号': str, '课程名称': str, '学期': str, '补考成绩': str, '课程代码': str, '学分': float, '成绩': str}] """ return self.query(GetMyAchievements()) def get_my_curriculum(self): """ 获取个人课表 @structure {'课表': [[[{'上课周数': [int], '课程名称': str, '课程地点': str}]]], '起始周': int, '结束周': int} """ return self.query(GetMyCurriculum()) def get_my_fees(self): """ 收费查询 @structure [{'教学班号': str, '课程名称': str, '学期': str, '收费(元): float', '课程代码': str, '学分': float}] """ return self.query(GetMyFees()) def change_password(self, new_password): """ 修改教务密码, **注意** 合肥校区使用信息中心账号登录, 与教务密码不一致, 即使修改了也没有作用, 因此合肥校区帐号调用此接口会直接报错 @structure bool :param new_password: 新密码 """ if self.session.campus == HF: raise ValueError('合肥校区使用信息中心账号登录, 修改教务密码没有作用') # 若新密码与原密码相同, 直接返回 True if new_password == self.session.password: raise ValueError('原密码与新密码相同') result = self.query(ChangePassword(self.session.password, new_password)) if result: self.session.password = new_password return result def set_telephone(self, tel): """ 更新电话 @structure bool :param tel: 电话号码, 需要满足手机和普通电话的格式, 例如 `18112345678` 或者 '0791-1234567' """ return type(tel)(self.query(SetTelephone(tel))) == tel # ========== 选课功能相关 ========== def get_optional_courses(self, kclx='x'): """ 获取可选课程, 并不判断是否选满 @structure [{'学分': float, '开课院系': str, '课程代码': str, '课程名称': str, '课程类型': str}] :param kclx: 课程类型参数,只有三个值,{x:全校公选课, b:全校必修课, jh:本专业计划},默认为'x' """ return self.query(GetOptionalCourses(kclx)) def get_selected_courses(self): """ 获取所有已选的课程 @structure [{'费用': float, '教学班号': str, '课程名称': str, '课程代码': str, '学分': float, '课程类型': str}] """ return self.query(GetSelectedCourses()) def get_unfinished_evaluation(self): """ 获取未完成的课程评价 @structure [{'教学班号': str, '课程名称': str, '课程代码': str}] """ return self.query(GetUnfinishedEvaluation()) def evaluate_course(self, kcdm, jxbh, r101=1, r102=1, r103=1, r104=1, r105=1, r106=1, r107=1, r108=1, r109=1, r201=3, r202=3, advice=''): """ 课程评价, 数值为 1-5, r1 类选项 1 为最好, 5 为最差, r2 类选项程度由深到浅, 3 为最好. 默认都是最好的选项 :param kcdm: 课程代码 :param jxbh: 教学班号 :param r101: 教学态度认真,课前准备充分 :param r102: 教授内容充实,要点重点突出 :param r103: 理论联系实际,反映最新成果 :param r104: 教学方法灵活,师生互动得当 :param r105: 运用现代技术,教学手段多样 :param r106: 注重因材施教,加强能力培养 :param r107: 严格要求管理,关心爱护学生 :param r108: 处处为人师表,注重教书育人 :param r109: 教学综合效果 :param r201: 课程内容 :param r202: 课程负担 :param advice: 其他建议,不能超过120字且不能使用分号,单引号,都好 :return: """ return self.query(EvaluateCourse( kcdm, jxbh, r101, r102, r103, r104, r105, r106, r107, r108, r109, r201, r202, advice )) def change_course(self, select_courses=None, delete_courses=None): """ 修改个人的课程 @structure [{'费用': float, '教学班号': str, '课程名称': str, '课程代码': str, '学分': float, '课程类型': str}] :param select_courses: 形如 ``[{'kcdm': '9900039X', 'jxbhs': {'0001', '0002'}}]`` 的课程代码与教学班号列表, jxbhs 可以为空代表选择所有可选班级 :param delete_courses: 需要删除的课程代码集合, 如 ``{'0200011B'}`` :return: 选课结果, 返回选中的课程教学班列表, 结构与 ``get_selected_courses`` 一致 """ # 框架重构后调整接口的调用 t = self.get_system_status() if t['当前轮数'] is None: raise ValueError('当前为 %s,选课系统尚未开启', t['当前学期']) if not (select_courses or delete_courses): raise ValueError('select_courses, delete_courses 参数不能都为空!') # 参数处理 select_courses = select_courses or [] delete_courses = {l.upper() for l in (delete_courses or [])} selected_courses = self.get_selected_courses() selected_kcdms = {course['课程代码'] for course in selected_courses} # 尝试删除没有被选中的课程会出错 unselected = delete_courses.difference(selected_kcdms) if unselected: msg = '无法删除没有被选的课程 {}'.format(unselected) logger.warning(msg) # 要提交的 kcdm 数据 kcdms_data = [] # 要提交的 jxbh 数据 jxbhs_data = [] # 必须添加已选课程, 同时去掉要删除的课程 for course in selected_courses: if course['课程代码'] not in delete_courses: kcdms_data.append(course['课程代码']) jxbhs_data.append(course['教学班号']) # 选课 for kv in select_courses: kcdm = kv['kcdm'].upper() jxbhs = set(kv['jxbhs']) if kv.get('jxbhs') else set() teaching_classes = self.get_course_classes(kcdm) if not teaching_classes: logger.warning('课程[%s]没有可选班级', kcdm) continue # 反正是统一提交, 不需要判断是否已满 optional_jxbhs = {c['教学班号'] for c in teaching_classes['可选班级']} if jxbhs: wrong_jxbhs = jxbhs.difference(optional_jxbhs) if wrong_jxbhs: msg = '课程[{}]{}没有教学班号{}'.format(kcdm, teaching_classes['课程名称'], wrong_jxbhs) logger.warning(msg) jxbhs = jxbhs.intersection(optional_jxbhs) else: jxbhs = optional_jxbhs for jxbh in jxbhs: kcdms_data.append(kcdm) jxbhs_data.append(jxbh) return self.query(ChangeCourse(self.session.account, select_courses, delete_courses)) # ---------- 不需要专门的请求 ---------- def check_courses(self, kcdms): """ 检查课程是否被选 @structure [bool] :param kcdms: 课程代码列表 :return: 与课程代码列表长度一致的布尔值列表, 已为True,未选为False """ selected_courses = self.get_selected_courses() selected_kcdms = {course['课程代码'] for course in selected_courses} result = [True if kcdm in selected_kcdms else False for kcdm in kcdms] return result
earlzo/hfut
hfut/session.py
BaseSession.send
python
def send(self, request, **kwargs): response = super(BaseSession, self).send(request, **kwargs) if ENV['RAISE_FOR_STATUS']: response.raise_for_status() parsed = parse.urlparse(response.url) if parsed.netloc == parse.urlparse(self.host).netloc: response.encoding = ENV['SITE_ENCODING'] # 快速判断响应 IP 是否被封, 那个警告响应内容长度为 327 或 328, 保留一点余量确保准确 min_length, max_length, pattern = ENV['IP_BANNED_RESPONSE'] if min_length <= len(response.content) <= max_length and pattern.search(response.text): msg = '当前 IP 已被锁定, 如果可以请尝试切换教务系统地址, 否则请在更换网络环境或等待解封后重试!' raise IPBanned(msg) self.histories.append(response) logger.debug(report_response(response, redirection=kwargs.get('allow_redirects'))) return response
所有接口用来发送请求的方法, 只是 :meth:`requests.sessions.Session.send` 的一个钩子方法, 用来处理请求前后的工作
train
https://github.com/earlzo/hfut/blob/09270a9647fba79f26fd1a8a3c53c0678b5257a1/hfut/session.py#L56-L75
[ "def report_response(response,\n request_headers=True, request_body=True,\n response_headers=False, response_body=False,\n redirection=False):\n \"\"\"\n 生成响应报告\n\n :param response: ``requests.models.Response`` 对象\n :param request_headers: 是否加入请求头...
class BaseSession(requests.Session): """ 所有接口会话类的基类 """ def __init__(self, campus): """ 所以接口会话类的基类 :param campus: 校区代码, 请使用 ``value`` 模块中的 ``HF``, ``XC`` 分别来区分合肥校区和宣城校区 """ super(BaseSession, self).__init__() self.headers = ENV['DEFAULT_HEADERS'] self.histories = deque(maxlen=ENV['MAX_HISTORIES']) # 初始化时根据合肥选择不同的地址 self.campus = campus.upper() self.host = ENV[self.campus] def prepare_request(self, request): parsed = parse.urlparse(request.url) # 非法字符检查 if ENV['REQUEST_ARGUMENTS_CHECK'] and (not parsed.netloc or parsed.netloc == parse.urlparse(self.host).netloc): for k, v in reduce(lambda x, y: x + list(y.items()), (request.params, request.data), []): pattern = ENV['ILLEGAL_CHARACTERS_PATTERN'] result = pattern.search(str(k)) or pattern.search(str(v)) if result: msg = ''.join(['参数中出现非法字符: ', result.group()]) raise ValidationError(msg) if not parsed.netloc: # requests 在准备 url 进行解析, 因此只能在准备前将 url 换成完整的地址 # requests.models.PreparedRequest#prepare_url request.url = parse.urljoin(self.host, request.url) return super(BaseSession, self).prepare_request(request) def __str__(self): return '<BaseSession(%s)>' % self.campus
earlzo/hfut
hfut/log.py
report_response
python
def report_response(response, request_headers=True, request_body=True, response_headers=False, response_body=False, redirection=False): # https://docs.python.org/3/library/string.html#formatstrings url = 'Url: [{method}]{url} {status} {elapsed:.2f}ms'.format( method=response.request.method, url=response.url, status=response.status_code, elapsed=response.elapsed.total_seconds() * 1000 ) pieces = [url] if request_headers: request_headers = 'Request headers: {request_headers}'.format(request_headers=response.request.headers) pieces.append(request_headers) if request_body: request_body = 'Request body: {request_body}'.format(request_body=response.request.body) pieces.append(request_body) if response_headers: response_headers = 'Response headers: {response_headers}'.format(response_headers=response.headers) pieces.append(response_headers) if response_body: response_body = 'Response body: {response_body}'.format(response_body=response.text) pieces.append(response_body) reporter = '\n'.join(pieces) if redirection and response.history: for h in response.history[::-1]: redirect_reporter = report_response( h, request_headers, request_body, response_headers, response_body, redirection=False ) reporter = '\n'.join([redirect_reporter, ' Redirect ↓ '.center(72, '-'), reporter]) return reporter
生成响应报告 :param response: ``requests.models.Response`` 对象 :param request_headers: 是否加入请求头 :param request_body: 是否加入请求体 :param response_headers: 是否加入响应头 :param response_body: 是否加入响应体 :param redirection: 是否加入重定向响应 :return: str
train
https://github.com/earlzo/hfut/blob/09270a9647fba79f26fd1a8a3c53c0678b5257a1/hfut/log.py#L20-L67
[ "def report_response(response,\n request_headers=True, request_body=True,\n response_headers=False, response_body=False,\n redirection=False):\n \"\"\"\n 生成响应报告\n\n :param response: ``requests.models.Response`` 对象\n :param request_headers: 是否加入请求头...
# -*- coding:utf-8 -*- """ 日志模块 """ from __future__ import unicode_literals from logging import Logger, WARNING, StreamHandler, Formatter __all__ = ['logger', 'report_response', 'log_result_not_found'] logger = Logger('hfut', level=WARNING) sh = StreamHandler() # https://docs.python.org/3/library/logging.html#logrecord-attributes fmt = Formatter('[%(levelname)s]: %(message)s') sh.setFormatter(fmt) logger.addHandler(sh) def log_result_not_found(response): msg = '\n'.join([ '没有解析到结果, 可能是参数不正确, 服务器出错, 解析有问题, 如果本库有问题请及时进行反馈.', report_response(response, response_headers=True, response_body=True, redirection=True) ]) logger.warning(msg)
nathankw/pulsarpy
pulsarpy/elasticsearch_utils.py
Connection.get_record_by_name
python
def get_record_by_name(self, index, name): result = self.ES.search( index=index, body={ "query": { "match_phrase": { "name": name, } } } ) hits = result["hits"]["hits"] if not hits: return {} elif len(hits) == 1: return hits[0]["_source"] else: # Mult. records found with same prefix. See if a single record whose name attr matches # the match phrase exactly (in a lower-case comparison). for h in hits: source = h["_source"] record_name = source["name"] if record_name.lower().strip() == name.lower().strip(): return source msg = "match_phrase search found multiple records matching query '{}' for index '{}'.".format(name, index) raise MultipleHitsException(msg)
Searches for a single document in the given index on the 'name' field . Performs a case-insensitive search by utilizing Elasticsearch's `match_phrase` query. Args: index: `str`. The name of an Elasticsearch index (i.e. biosamples). name: `str`. The value of a document's name key to search for. Returns: `dict` containing the document that was indexed into Elasticsearch. Raises: `MultipleHitsException`: More than 1 hit is returned.
train
https://github.com/nathankw/pulsarpy/blob/359b040c0f2383b88c0b5548715fefd35f5f634c/pulsarpy/elasticsearch_utils.py#L38-L77
null
class Connection(): def __init__(self): ES_URL = os.environ.get("ES_URL", None) if not ES_URL: print("Warning: environment variable ES_URL not set.") ES_USER = os.environ.get("ES_USER", "") if not ES_USER: print("Warning: environment variable ES_USER not set.") ES_PW = os.environ.get("ES_PW", "") if not ES_PW: print("Warning: environment variable ES_PW not set.") ES_AUTH = (ES_USER, ES_PW) self.ES = Elasticsearch(ES_URL, http_auth=ES_AUTH) def get_record_by_name(self, index, name): """ Searches for a single document in the given index on the 'name' field . Performs a case-insensitive search by utilizing Elasticsearch's `match_phrase` query. Args: index: `str`. The name of an Elasticsearch index (i.e. biosamples). name: `str`. The value of a document's name key to search for. Returns: `dict` containing the document that was indexed into Elasticsearch. Raises: `MultipleHitsException`: More than 1 hit is returned. """ result = self.ES.search( index=index, body={ "query": { "match_phrase": { "name": name, } } } ) hits = result["hits"]["hits"] if not hits: return {} elif len(hits) == 1: return hits[0]["_source"] else: # Mult. records found with same prefix. See if a single record whose name attr matches # the match phrase exactly (in a lower-case comparison). for h in hits: source = h["_source"] record_name = source["name"] if record_name.lower().strip() == name.lower().strip(): return source msg = "match_phrase search found multiple records matching query '{}' for index '{}'.".format(name, index) raise MultipleHitsException(msg)
nathankw/pulsarpy
pulsarpy/models.py
Meta.get_logfile_name
python
def get_logfile_name(tag): if not os.path.exists(p.LOG_DIR): os.mkdir(p.LOG_DIR) filename = "log_" + p.HOST + "_" + tag + ".txt" filename = os.path.join(p.LOG_DIR, filename) return filename
Creates a name for a log file that is meant to be used in a call to ``logging.FileHandler``. The log file name will incldue the path to the log directory given by the `p.LOG_DIR` constant. The format of the file name is: 'log_$HOST_$TAG.txt', where $HOST is the hostname part of the URL given by ``URL``, and $TAG is the value of the 'tag' argument. The log directory will be created if need be. Args: tag: `str`. A tag name to add to at the end of the log file name for clarity on the log file's purpose.
train
https://github.com/nathankw/pulsarpy/blob/359b040c0f2383b88c0b5548715fefd35f5f634c/pulsarpy/models.py#L114-L131
null
class Meta(type): #: A list where each item is set to each instance's MODEL_ABBR class variable. _MODEL_ABBREVS = [] @staticmethod @staticmethod def add_file_handler(logger, level, tag): """ Adds a ``logging.FileHandler`` handler to the specified ``logging`` instance that will log the messages it receives at the specified error level or greater. The log file name will be of the form log_$HOST_$TAG.txt, where $HOST is the hostname part of the URL given by ``p.URL``, and $TAG is the value of the 'tag' argument. Args: logger: The `logging.Logger` instance to add the `logging.FileHandler` to. level: `int`. A logging level (i.e. given by one of the constants `logging.DEBUG`, `logging.INFO`, `logging.WARNING`, `logging.ERROR`, `logging.CRITICAL`). tag: `str`. A tag name to add to at the end of the log file name for clarity on the log file's purpose. """ f_formatter = logging.Formatter('%(asctime)s:%(name)s:\t%(message)s') filename = Meta.get_logfile_name(tag) handler = logging.FileHandler(filename=filename, mode="a") handler.setLevel(level) handler.setFormatter(f_formatter) logger.addHandler(handler) def __init__(newcls, classname, supers, classdict): #: Used primarily for setting the lower-cased and underscored model name in the payload #: for post and patch operations. newcls.MODEL_NAME = inflection.underscore(newcls.__name__) #: Elasticsearch index name for the Pulsar model. newcls.ES_INDEX_NAME = inflection.pluralize(newcls.MODEL_NAME) newcls.URL = os.path.join(p.URL, inflection.pluralize(newcls.MODEL_NAME)) if getattr(newcls, "MODEL_ABBR"): Meta._MODEL_ABBREVS.append(newcls.MODEL_ABBR)
nathankw/pulsarpy
pulsarpy/models.py
Model._get
python
def _get(self, rec_id=None, upstream=None): if rec_id: self.record_url = self.__class__.get_record_url(rec_id) self.debug_logger.debug("GET {} record with ID {}: {}".format(self.__class__.__name__, rec_id, self.record_url)) response = requests.get(url=self.record_url, headers=HEADERS, verify=False) if not response.ok and response.status_code == requests.codes.NOT_FOUND: raise RecordNotFound("Search for {} record with ID '{}' returned no results.".format(self.__class__.__name__, rec_id)) self.write_response_html_to_file(response,"get_bob.html") response.raise_for_status() return response.json() elif upstream: rec_json = self.__class__.find_by({"upstream_identifier": upstream}, require=True) self.record_url = self.__class__.get_record_url(rec_json["id"]) return rec_json
Fetches a record by the record's ID or upstream_identifier. Raises: `pulsarpy.models.RecordNotFound`: A record could not be found.
train
https://github.com/nathankw/pulsarpy/blob/359b040c0f2383b88c0b5548715fefd35f5f634c/pulsarpy/models.py#L296-L315
[ "def write_response_html_to_file(response,filename):\n \"\"\"\n An aid in troubleshooting internal application errors, i.e. <Response [500]>, to be mainly\n beneficial when developing the server-side API. This method will write the response HTML\n for viewing the error details in the browesr.\n\n Ar...
class Model(metaclass=Meta): """ The superclass of all model classes. A model subclass is defined for each Rails model. An instance of a model class represents a record of the given Rails model. Subclasses don't typically define their own init method, but if they do, they need to make a call to 'super' to run the init method defined here as well. Subclasses must be instantiated with the rec_id argument set to a record's ID. A GET will immediately be done and the record's attributes will be stored in the self.attrs `dict`. The record's attributes can be accessed as normal instance attributes (i.e. ``record.name) rather than explicitly indexing the attrs dictionary, thanks to the employment of ``__getattr__()``. Similarly, record attributes can be updated via normal assignment operations, i.e. (``record.name = "bob"``), thanks to employment of ``__setattr__()``. Required Environment Variables: 1) PULSAR_API_URL 2) PULSAR_TOKEN """ #: Most models have an attribute alled upstream_identifier that is used to store the value of the #: record in an "upstream" database that is submitted to, i.e. the ENCODE Portal. Not all models #: have this attribute since not all are used for submission to an upstream portal. UPSTREAM_ATTR = "upstream_identifier" MODEL_ABBR = "" # subclasses define #: Abstract attribute of type `dict` that each subclass should fulfull if it has any foreign keys. #: Each key is a foreign key name and the value is the class name of the model it refers to. FKEY_MAP = {} #: A prefix that can be added in front of record IDs, names, model-record ID. This is useful #: when its necessary to add emphasis that these records exist or came from Pulsar ( i.e. when #: submitting them to an upstream database. PULSAR_LIMS_PREFIX = "p" #: This class adds a file handler, such that all messages sent to it are logged to this #: file in addition to STDOUT. debug_logger = logging.getLogger(p.DEBUG_LOGGER_NAME) # Add debug file handler to debug_logger: Meta.add_file_handler(logger=debug_logger, level=logging.DEBUG, tag="debug") #: A ``logging`` instance with a file handler for logging terse error messages. #: The log file resides locally within the directory specified by the constant #: ``p.LOG_DIR``. Accepts messages >= ``logging.ERROR``. error_logger = logging.getLogger(p.ERROR_LOGGER_NAME) log_level = logging.ERROR error_logger.setLevel(log_level) Meta.add_file_handler(logger=error_logger, level=log_level, tag="error") #: A ``logging`` instance with a file handler for logging successful POST operations. #: The log file resides locally within the directory specified by the constant #: ``p.LOG_DIR``. Accepts messages >= ``logging.INFO``. post_logger = logging.getLogger(p.POST_LOGGER_NAME) log_level = logging.INFO post_logger.setLevel(log_level) Meta.add_file_handler(logger=post_logger, level=log_level, tag="posted") log_msg = "-----------------------------------------------------------------------------------" # Check if neccessary environment variables are set: if not p.URL: debug_logger.debug("Warning: Environment variable PULSAR_API_URL not set.") elif not p.API_TOKEN: debug_logger.debug("Warning: Environment variable PULSAR_TOKEN not set.") debug_logger.debug(log_msg) error_logger.error(log_msg) log_msg = "Connecting to {}".format(p.URL) error_logger.error(log_msg) debug_logger.debug(log_msg) #: Connection to Elasticsearch. Expects that the envrionment variables ES_URL, ES_USER, and #: ES_PW are set, which signifiy the Elasticsearch cluster URL, login username and login #: password, respectively. ES = pulsarpy.elasticsearch_utils.Connection() def __init__(self, uid=None, upstream=None): """ Find the record of the given model specified by self.MODEL_NAME. The record can be looked up in a few ways, depending on which argument is specified (uid or upstream). If both are specified, then the upstream argument will be ignored. Args: uid: The database identifier of the record to fetch, which can be specified either as the primary id (i.e. 8) or the model prefix plus the primary id (i.e. B-8). Could also be the record's name if it has a name attribute (not all models do) and if so will be converted to the record ID. upstream: If set, then the record will be searched on its upstream_identifier attribute. """ # self.attrs will store the actual record's attributes. Initialize value now to empty dict # since it is expected to be set already in self.__setattr__(). self.__dict__["attrs"] = {} # rec_id could be the record's name. Check for that scenario, and convert to record ID if # necessary. if uid: rec_id = self.__class__.replace_name_with_id(uid) rec_json = self._get(rec_id=rec_id) elif upstream: rec_json = self._get(upstream=upstream) else: raise ValueError("Either the 'uid' or 'upstream' parameter must be set.") # Convert None values to empty string for key in rec_json: if rec_json[key] == None: rec_json[key] = "" self.rec_id = rec_json["id"] self.__dict__["attrs"] = rec_json #avoid call to self.__setitem__() for this attr. def __getattr__(self, name): """ Treats database attributes for the record as Python attributes. An attribute is looked up in self.attrs. """ return self.attrs[name] def __setattr__(self, name, value): """ Sets the value of an attribute in self.attrs. """ if name not in self.attrs: return object.__setattr__(self, name, value) object.__setattr__(self, self.attrs[name], value) #self.__dict__["attrs"][name] = value #this works too def __getitem__(self, item): return self.attrs[item] def __setitem__(self, item, value): self.attrs[item] = value @classmethod def get_record_url(self, rec_id): return os.path.join(self.URL, str(rec_id)) @classmethod def log_post(cls, res_json): msg = cls.__name__ + "\t" + str(res_json["id"]) + "\t" name = res_json.get("name") if name: msg += name cls.post_logger.info(msg) @classmethod def replace_name_with_id(cls, name): """ Used to replace a foreign key reference using a name with an ID. Works by searching the record in Pulsar and expects to find exactly one hit. First, will check if the foreign key reference is an integer value and if so, returns that as it is presumed to be the foreign key. Raises: `pulsarpy.elasticsearch_utils.MultipleHitsException`: Multiple hits were returned from the name search. `pulsarpy.models.RecordNotFound`: No results were produced from the name search. """ try: int(name) return name #Already a presumed ID. except ValueError: pass #Not an int, so maybe a combination of MODEL_ABBR and Primary Key, i.e. B-8. if name.split("-")[0] in Meta._MODEL_ABBREVS: return int(name.split("-", 1)[1]) try: result = cls.ES.get_record_by_name(cls.ES_INDEX_NAME, name) if result: return result["id"] except pulsarpy.elasticsearch_utils.MultipleHitsException as e: raise raise RecordNotFound("Name '{}' for model '{}' not found.".format(name, cls.__name__)) @classmethod def add_model_name_to_payload(cls, payload): """ Checks whether the model name in question is in the payload. If not, the entire payload is set as a value of a key by the name of the model. This method is useful when some server-side Rails API calls expect the parameters to include the parameterized model name. For example, server-side endpoints that handle the updating of a biosample record or the creation of a new biosmample record will expect the payload to be of the form:: { "biosample": { "name": "new biosample", "donor": 3, ... } } Args: payload: `dict`. The data to send in an HTTP request. Returns: `dict`. """ if not cls.MODEL_NAME in payload: payload = {cls.MODEL_NAME: payload} return payload @staticmethod def check_boolean_fields(payload): for key in payload: val = payload[key] if type(val) != str: continue val = val.lower() if val in ["yes", "true", "pass"]: val = True payload[key] = val elif val == ["no", "false", "fail"]: val = False payload[key] = val return payload def get_upstream(self): return self.attrs.get(Model.UPSTREAM_ATTR) def abbrev_id(self): """ This method is called when posting to the ENCODE Portal to grab an alias for the record being submitted. The alias here is composed of the record ID in Pulsar (i.e. B-1 for the Biosample with ID 1). However, the record ID is prefexed with a 'p' to designate that this record was submitted from Pulsar. This is used to generate a unique alias considering that we used to uses a different LIMS (Syapse) to submit records. Many of the models in Syapse used the same model prefix as is used in Pulsar, i.e. (B)Biosample and (L)Library. Thus, w/o the 'p' prefix, the same alias could be generated in Pulsar as a previous one used in Syapse. """ return self.PULSAR_LIMS_PREFIX + self.MODEL_ABBR + "-" + str(self.id) def delete(self): """Deletes the record. """ res = requests.delete(url=self.record_url, headers=HEADERS, verify=False) #self.write_response_html_to_file(res,"bob_delete.html") if res.status_code == 204: #No content. Can't render json: return {} return res.json() @classmethod def find_by(cls, payload, require=False): """ Searches the model in question by AND joining the query parameters. Implements a Railsy way of looking for a record using a method by the same name and passing in the query as a dict. as well. Only the first hit is returned, and there is no particular ordering specified in the server-side API method. Args: payload: `dict`. The attributes of a record to restrict the search to. require: `bool`. True means to raise a `pulsarpy.models.RecordNotFound` exception if no record is found. Returns: `dict`: The JSON serialization of the record, if any, found by the API call. `None`: If the API call didnt' return any results. Raises: `pulsarpy.models.RecordNotFound`: No records were found, and the `require` parameter is True. """ if not isinstance(payload, dict): raise ValueError("The 'payload' parameter must be provided a dictionary object.") url = os.path.join(cls.URL, "find_by") payload = {"find_by": payload} cls.debug_logger.debug("Searching Pulsar {} for {}".format(cls.__name__, json.dumps(payload, indent=4))) res = requests.post(url=url, json=payload, headers=HEADERS, verify=False) #cls.write_response_html_to_file(res,"bob.html") res.raise_for_status() res_json = res.json() if res_json: try: res_json = res_json[cls.MODEL_NAME] except KeyError: # Key won't be present if there isn't a serializer for it on the server. pass else: if require: raise RecordNotFound("Can't find any {} records with search criteria: '{}'.".format(cls.__name__, payload)) return res_json @classmethod def find_by_or(cls, payload): """ Searches the model in question by OR joining the query parameters. Implements a Railsy way of looking for a record using a method by the same name and passing in the query as a string (for the OR operator joining to be specified). Only the first hit is returned, and there is not particular ordering specified in the server-side API method. Args: payload: `dict`. The attributes of a record to search for by using OR operator joining for each query parameter. Returns: `dict`: The JSON serialization of the record, if any, found by the API call. `None`: If the API call didnt' return any results. """ if not isinstance(payload, dict): raise ValueError("The 'payload' parameter must be provided a dictionary object.") url = os.path.join(cls.URL, "find_by_or") payload = {"find_by_or": payload} cls.debug_logger.debug("Searching Pulsar {} for {}".format(cls.__name__, json.dumps(payload, indent=4))) res = requests.post(url=url, json=payload, headers=HEADERS, verify=False) cls.write_response_html_to_file(res,"bob.html") if res: try: res = res[cls.MODEL_NAME] except KeyError: # Key won't be present if there isn't a serializer for it on the server. pass return res @classmethod def index(cls): """Fetches all records. Returns: `dict`. The JSON formatted response. Raises: `requests.exceptions.HTTPError`: The status code is not ok. """ res = requests.get(cls.URL, headers=HEADERS, verify=False) res.raise_for_status() return res.json() def patch(self, payload, append_to_arrays=True): """ Patches current record and udpates the current instance's 'attrs' attribute to reflect the new changes. Args: payload - hash. This will be JSON-formatted prior to sending the request. Returns: `dict`. The JSON formatted response. Raises: `requests.exceptions.HTTPError`: The status code is not ok. """ if not isinstance(payload, dict): raise ValueError("The 'payload' parameter must be provided a dictionary object.") payload = self.__class__.set_id_in_fkeys(payload) if append_to_arrays: for key in payload: val = payload[key] if type(val) == list: val.extend(getattr(self, key)) payload[key] = list(set(val)) payload = self.check_boolean_fields(payload) payload = self.__class__.add_model_name_to_payload(payload) self.debug_logger.debug("PATCHING payload {}".format(json.dumps(payload, indent=4))) res = requests.patch(url=self.record_url, json=payload, headers=HEADERS, verify=False) self.write_response_html_to_file(res,"bob.html") res.raise_for_status() json_res = res.json() self.debug_logger.debug("Success") self.attrs = json_res return json_res @classmethod def set_id_in_fkeys(cls, payload): """ Looks for any keys in the payload that end with either _id or _ids, signaling a foreign key field. For each foreign key field, checks whether the value is using the name of the record or the actual primary ID of the record (which may include the model abbreviation, i.e. B-1). If the former case, the name is replaced with the record's primary ID. Args: payload: `dict`. The payload to POST or PATCH. Returns: `dict`. The payload. """ for key in payload: val = payload[key] if not val: continue if key.endswith("_id"): model = getattr(THIS_MODULE, cls.FKEY_MAP[key]) rec_id = model.replace_name_with_id(name=val) payload[key] = rec_id elif key.endswith("_ids"): model = getattr(THIS_MODULE, cls.FKEY_MAP[key]) rec_ids = [] for v in val: rec_id = model.replace_name_with_id(name=v) rec_ids.append(rec_id) payload[key] = rec_ids return payload @classmethod def prepost_hooks(cls, payload): return payload @classmethod def post(cls, payload): """Posts the data to the specified record. Args: payload: `dict`. This will be JSON-formatted prior to sending the request. Returns: `dict`. The JSON formatted response. Raises: `Requests.exceptions.HTTPError`: The status code is not ok. `RecordNotUnique`: The Rails server returned the exception ActiveRecord::RecordNotUnique. """ if not isinstance(payload, dict): raise ValueError("The 'payload' parameter must be provided a dictionary object.") payload = cls.set_id_in_fkeys(payload) payload = cls.check_boolean_fields(payload) payload = cls.add_model_name_to_payload(payload) # Run any pre-post hooks: payload = cls.prepost_hooks(payload) cls.debug_logger.debug("POSTING payload {}".format(json.dumps(payload, indent=4))) res = requests.post(url=cls.URL, json=(payload), headers=HEADERS, verify=False) cls.write_response_html_to_file(res,"bob.html") if not res.ok: cls.log_error(res.text) res_json = res.json() if "exception" in res_json: exc_type = res_json["exception"] if exc_type == "ActiveRecord::RecordNotUnique": raise RecordNotUnique() res.raise_for_status() res = res.json() cls.log_post(res) cls.debug_logger.debug("Success") return res @classmethod def log_error(cls, msg): """ Logs the provided error message to both the error logger and the debug logger logging instances. Args: msg: `str`. The error message to log. """ cls.error_logger.error(msg) cls.debug_logger.debug(msg) @staticmethod def write_response_html_to_file(response,filename): """ An aid in troubleshooting internal application errors, i.e. <Response [500]>, to be mainly beneficial when developing the server-side API. This method will write the response HTML for viewing the error details in the browesr. Args: response: `requests.models.Response` instance. filename: `str`. The output file name. """ fout = open(filename,'w') if not str(response.status_code).startswith("2"): Model.debug_logger.debug(response.text) fout.write(response.text) fout.close()
nathankw/pulsarpy
pulsarpy/models.py
Model.replace_name_with_id
python
def replace_name_with_id(cls, name): try: int(name) return name #Already a presumed ID. except ValueError: pass #Not an int, so maybe a combination of MODEL_ABBR and Primary Key, i.e. B-8. if name.split("-")[0] in Meta._MODEL_ABBREVS: return int(name.split("-", 1)[1]) try: result = cls.ES.get_record_by_name(cls.ES_INDEX_NAME, name) if result: return result["id"] except pulsarpy.elasticsearch_utils.MultipleHitsException as e: raise raise RecordNotFound("Name '{}' for model '{}' not found.".format(name, cls.__name__))
Used to replace a foreign key reference using a name with an ID. Works by searching the record in Pulsar and expects to find exactly one hit. First, will check if the foreign key reference is an integer value and if so, returns that as it is presumed to be the foreign key. Raises: `pulsarpy.elasticsearch_utils.MultipleHitsException`: Multiple hits were returned from the name search. `pulsarpy.models.RecordNotFound`: No results were produced from the name search.
train
https://github.com/nathankw/pulsarpy/blob/359b040c0f2383b88c0b5548715fefd35f5f634c/pulsarpy/models.py#L330-L354
null
class Model(metaclass=Meta): """ The superclass of all model classes. A model subclass is defined for each Rails model. An instance of a model class represents a record of the given Rails model. Subclasses don't typically define their own init method, but if they do, they need to make a call to 'super' to run the init method defined here as well. Subclasses must be instantiated with the rec_id argument set to a record's ID. A GET will immediately be done and the record's attributes will be stored in the self.attrs `dict`. The record's attributes can be accessed as normal instance attributes (i.e. ``record.name) rather than explicitly indexing the attrs dictionary, thanks to the employment of ``__getattr__()``. Similarly, record attributes can be updated via normal assignment operations, i.e. (``record.name = "bob"``), thanks to employment of ``__setattr__()``. Required Environment Variables: 1) PULSAR_API_URL 2) PULSAR_TOKEN """ #: Most models have an attribute alled upstream_identifier that is used to store the value of the #: record in an "upstream" database that is submitted to, i.e. the ENCODE Portal. Not all models #: have this attribute since not all are used for submission to an upstream portal. UPSTREAM_ATTR = "upstream_identifier" MODEL_ABBR = "" # subclasses define #: Abstract attribute of type `dict` that each subclass should fulfull if it has any foreign keys. #: Each key is a foreign key name and the value is the class name of the model it refers to. FKEY_MAP = {} #: A prefix that can be added in front of record IDs, names, model-record ID. This is useful #: when its necessary to add emphasis that these records exist or came from Pulsar ( i.e. when #: submitting them to an upstream database. PULSAR_LIMS_PREFIX = "p" #: This class adds a file handler, such that all messages sent to it are logged to this #: file in addition to STDOUT. debug_logger = logging.getLogger(p.DEBUG_LOGGER_NAME) # Add debug file handler to debug_logger: Meta.add_file_handler(logger=debug_logger, level=logging.DEBUG, tag="debug") #: A ``logging`` instance with a file handler for logging terse error messages. #: The log file resides locally within the directory specified by the constant #: ``p.LOG_DIR``. Accepts messages >= ``logging.ERROR``. error_logger = logging.getLogger(p.ERROR_LOGGER_NAME) log_level = logging.ERROR error_logger.setLevel(log_level) Meta.add_file_handler(logger=error_logger, level=log_level, tag="error") #: A ``logging`` instance with a file handler for logging successful POST operations. #: The log file resides locally within the directory specified by the constant #: ``p.LOG_DIR``. Accepts messages >= ``logging.INFO``. post_logger = logging.getLogger(p.POST_LOGGER_NAME) log_level = logging.INFO post_logger.setLevel(log_level) Meta.add_file_handler(logger=post_logger, level=log_level, tag="posted") log_msg = "-----------------------------------------------------------------------------------" # Check if neccessary environment variables are set: if not p.URL: debug_logger.debug("Warning: Environment variable PULSAR_API_URL not set.") elif not p.API_TOKEN: debug_logger.debug("Warning: Environment variable PULSAR_TOKEN not set.") debug_logger.debug(log_msg) error_logger.error(log_msg) log_msg = "Connecting to {}".format(p.URL) error_logger.error(log_msg) debug_logger.debug(log_msg) #: Connection to Elasticsearch. Expects that the envrionment variables ES_URL, ES_USER, and #: ES_PW are set, which signifiy the Elasticsearch cluster URL, login username and login #: password, respectively. ES = pulsarpy.elasticsearch_utils.Connection() def __init__(self, uid=None, upstream=None): """ Find the record of the given model specified by self.MODEL_NAME. The record can be looked up in a few ways, depending on which argument is specified (uid or upstream). If both are specified, then the upstream argument will be ignored. Args: uid: The database identifier of the record to fetch, which can be specified either as the primary id (i.e. 8) or the model prefix plus the primary id (i.e. B-8). Could also be the record's name if it has a name attribute (not all models do) and if so will be converted to the record ID. upstream: If set, then the record will be searched on its upstream_identifier attribute. """ # self.attrs will store the actual record's attributes. Initialize value now to empty dict # since it is expected to be set already in self.__setattr__(). self.__dict__["attrs"] = {} # rec_id could be the record's name. Check for that scenario, and convert to record ID if # necessary. if uid: rec_id = self.__class__.replace_name_with_id(uid) rec_json = self._get(rec_id=rec_id) elif upstream: rec_json = self._get(upstream=upstream) else: raise ValueError("Either the 'uid' or 'upstream' parameter must be set.") # Convert None values to empty string for key in rec_json: if rec_json[key] == None: rec_json[key] = "" self.rec_id = rec_json["id"] self.__dict__["attrs"] = rec_json #avoid call to self.__setitem__() for this attr. def __getattr__(self, name): """ Treats database attributes for the record as Python attributes. An attribute is looked up in self.attrs. """ return self.attrs[name] def __setattr__(self, name, value): """ Sets the value of an attribute in self.attrs. """ if name not in self.attrs: return object.__setattr__(self, name, value) object.__setattr__(self, self.attrs[name], value) #self.__dict__["attrs"][name] = value #this works too def __getitem__(self, item): return self.attrs[item] def __setitem__(self, item, value): self.attrs[item] = value def _get(self, rec_id=None, upstream=None): """ Fetches a record by the record's ID or upstream_identifier. Raises: `pulsarpy.models.RecordNotFound`: A record could not be found. """ if rec_id: self.record_url = self.__class__.get_record_url(rec_id) self.debug_logger.debug("GET {} record with ID {}: {}".format(self.__class__.__name__, rec_id, self.record_url)) response = requests.get(url=self.record_url, headers=HEADERS, verify=False) if not response.ok and response.status_code == requests.codes.NOT_FOUND: raise RecordNotFound("Search for {} record with ID '{}' returned no results.".format(self.__class__.__name__, rec_id)) self.write_response_html_to_file(response,"get_bob.html") response.raise_for_status() return response.json() elif upstream: rec_json = self.__class__.find_by({"upstream_identifier": upstream}, require=True) self.record_url = self.__class__.get_record_url(rec_json["id"]) return rec_json @classmethod def get_record_url(self, rec_id): return os.path.join(self.URL, str(rec_id)) @classmethod def log_post(cls, res_json): msg = cls.__name__ + "\t" + str(res_json["id"]) + "\t" name = res_json.get("name") if name: msg += name cls.post_logger.info(msg) @classmethod @classmethod def add_model_name_to_payload(cls, payload): """ Checks whether the model name in question is in the payload. If not, the entire payload is set as a value of a key by the name of the model. This method is useful when some server-side Rails API calls expect the parameters to include the parameterized model name. For example, server-side endpoints that handle the updating of a biosample record or the creation of a new biosmample record will expect the payload to be of the form:: { "biosample": { "name": "new biosample", "donor": 3, ... } } Args: payload: `dict`. The data to send in an HTTP request. Returns: `dict`. """ if not cls.MODEL_NAME in payload: payload = {cls.MODEL_NAME: payload} return payload @staticmethod def check_boolean_fields(payload): for key in payload: val = payload[key] if type(val) != str: continue val = val.lower() if val in ["yes", "true", "pass"]: val = True payload[key] = val elif val == ["no", "false", "fail"]: val = False payload[key] = val return payload def get_upstream(self): return self.attrs.get(Model.UPSTREAM_ATTR) def abbrev_id(self): """ This method is called when posting to the ENCODE Portal to grab an alias for the record being submitted. The alias here is composed of the record ID in Pulsar (i.e. B-1 for the Biosample with ID 1). However, the record ID is prefexed with a 'p' to designate that this record was submitted from Pulsar. This is used to generate a unique alias considering that we used to uses a different LIMS (Syapse) to submit records. Many of the models in Syapse used the same model prefix as is used in Pulsar, i.e. (B)Biosample and (L)Library. Thus, w/o the 'p' prefix, the same alias could be generated in Pulsar as a previous one used in Syapse. """ return self.PULSAR_LIMS_PREFIX + self.MODEL_ABBR + "-" + str(self.id) def delete(self): """Deletes the record. """ res = requests.delete(url=self.record_url, headers=HEADERS, verify=False) #self.write_response_html_to_file(res,"bob_delete.html") if res.status_code == 204: #No content. Can't render json: return {} return res.json() @classmethod def find_by(cls, payload, require=False): """ Searches the model in question by AND joining the query parameters. Implements a Railsy way of looking for a record using a method by the same name and passing in the query as a dict. as well. Only the first hit is returned, and there is no particular ordering specified in the server-side API method. Args: payload: `dict`. The attributes of a record to restrict the search to. require: `bool`. True means to raise a `pulsarpy.models.RecordNotFound` exception if no record is found. Returns: `dict`: The JSON serialization of the record, if any, found by the API call. `None`: If the API call didnt' return any results. Raises: `pulsarpy.models.RecordNotFound`: No records were found, and the `require` parameter is True. """ if not isinstance(payload, dict): raise ValueError("The 'payload' parameter must be provided a dictionary object.") url = os.path.join(cls.URL, "find_by") payload = {"find_by": payload} cls.debug_logger.debug("Searching Pulsar {} for {}".format(cls.__name__, json.dumps(payload, indent=4))) res = requests.post(url=url, json=payload, headers=HEADERS, verify=False) #cls.write_response_html_to_file(res,"bob.html") res.raise_for_status() res_json = res.json() if res_json: try: res_json = res_json[cls.MODEL_NAME] except KeyError: # Key won't be present if there isn't a serializer for it on the server. pass else: if require: raise RecordNotFound("Can't find any {} records with search criteria: '{}'.".format(cls.__name__, payload)) return res_json @classmethod def find_by_or(cls, payload): """ Searches the model in question by OR joining the query parameters. Implements a Railsy way of looking for a record using a method by the same name and passing in the query as a string (for the OR operator joining to be specified). Only the first hit is returned, and there is not particular ordering specified in the server-side API method. Args: payload: `dict`. The attributes of a record to search for by using OR operator joining for each query parameter. Returns: `dict`: The JSON serialization of the record, if any, found by the API call. `None`: If the API call didnt' return any results. """ if not isinstance(payload, dict): raise ValueError("The 'payload' parameter must be provided a dictionary object.") url = os.path.join(cls.URL, "find_by_or") payload = {"find_by_or": payload} cls.debug_logger.debug("Searching Pulsar {} for {}".format(cls.__name__, json.dumps(payload, indent=4))) res = requests.post(url=url, json=payload, headers=HEADERS, verify=False) cls.write_response_html_to_file(res,"bob.html") if res: try: res = res[cls.MODEL_NAME] except KeyError: # Key won't be present if there isn't a serializer for it on the server. pass return res @classmethod def index(cls): """Fetches all records. Returns: `dict`. The JSON formatted response. Raises: `requests.exceptions.HTTPError`: The status code is not ok. """ res = requests.get(cls.URL, headers=HEADERS, verify=False) res.raise_for_status() return res.json() def patch(self, payload, append_to_arrays=True): """ Patches current record and udpates the current instance's 'attrs' attribute to reflect the new changes. Args: payload - hash. This will be JSON-formatted prior to sending the request. Returns: `dict`. The JSON formatted response. Raises: `requests.exceptions.HTTPError`: The status code is not ok. """ if not isinstance(payload, dict): raise ValueError("The 'payload' parameter must be provided a dictionary object.") payload = self.__class__.set_id_in_fkeys(payload) if append_to_arrays: for key in payload: val = payload[key] if type(val) == list: val.extend(getattr(self, key)) payload[key] = list(set(val)) payload = self.check_boolean_fields(payload) payload = self.__class__.add_model_name_to_payload(payload) self.debug_logger.debug("PATCHING payload {}".format(json.dumps(payload, indent=4))) res = requests.patch(url=self.record_url, json=payload, headers=HEADERS, verify=False) self.write_response_html_to_file(res,"bob.html") res.raise_for_status() json_res = res.json() self.debug_logger.debug("Success") self.attrs = json_res return json_res @classmethod def set_id_in_fkeys(cls, payload): """ Looks for any keys in the payload that end with either _id or _ids, signaling a foreign key field. For each foreign key field, checks whether the value is using the name of the record or the actual primary ID of the record (which may include the model abbreviation, i.e. B-1). If the former case, the name is replaced with the record's primary ID. Args: payload: `dict`. The payload to POST or PATCH. Returns: `dict`. The payload. """ for key in payload: val = payload[key] if not val: continue if key.endswith("_id"): model = getattr(THIS_MODULE, cls.FKEY_MAP[key]) rec_id = model.replace_name_with_id(name=val) payload[key] = rec_id elif key.endswith("_ids"): model = getattr(THIS_MODULE, cls.FKEY_MAP[key]) rec_ids = [] for v in val: rec_id = model.replace_name_with_id(name=v) rec_ids.append(rec_id) payload[key] = rec_ids return payload @classmethod def prepost_hooks(cls, payload): return payload @classmethod def post(cls, payload): """Posts the data to the specified record. Args: payload: `dict`. This will be JSON-formatted prior to sending the request. Returns: `dict`. The JSON formatted response. Raises: `Requests.exceptions.HTTPError`: The status code is not ok. `RecordNotUnique`: The Rails server returned the exception ActiveRecord::RecordNotUnique. """ if not isinstance(payload, dict): raise ValueError("The 'payload' parameter must be provided a dictionary object.") payload = cls.set_id_in_fkeys(payload) payload = cls.check_boolean_fields(payload) payload = cls.add_model_name_to_payload(payload) # Run any pre-post hooks: payload = cls.prepost_hooks(payload) cls.debug_logger.debug("POSTING payload {}".format(json.dumps(payload, indent=4))) res = requests.post(url=cls.URL, json=(payload), headers=HEADERS, verify=False) cls.write_response_html_to_file(res,"bob.html") if not res.ok: cls.log_error(res.text) res_json = res.json() if "exception" in res_json: exc_type = res_json["exception"] if exc_type == "ActiveRecord::RecordNotUnique": raise RecordNotUnique() res.raise_for_status() res = res.json() cls.log_post(res) cls.debug_logger.debug("Success") return res @classmethod def log_error(cls, msg): """ Logs the provided error message to both the error logger and the debug logger logging instances. Args: msg: `str`. The error message to log. """ cls.error_logger.error(msg) cls.debug_logger.debug(msg) @staticmethod def write_response_html_to_file(response,filename): """ An aid in troubleshooting internal application errors, i.e. <Response [500]>, to be mainly beneficial when developing the server-side API. This method will write the response HTML for viewing the error details in the browesr. Args: response: `requests.models.Response` instance. filename: `str`. The output file name. """ fout = open(filename,'w') if not str(response.status_code).startswith("2"): Model.debug_logger.debug(response.text) fout.write(response.text) fout.close()
nathankw/pulsarpy
pulsarpy/models.py
Model.add_model_name_to_payload
python
def add_model_name_to_payload(cls, payload): if not cls.MODEL_NAME in payload: payload = {cls.MODEL_NAME: payload} return payload
Checks whether the model name in question is in the payload. If not, the entire payload is set as a value of a key by the name of the model. This method is useful when some server-side Rails API calls expect the parameters to include the parameterized model name. For example, server-side endpoints that handle the updating of a biosample record or the creation of a new biosmample record will expect the payload to be of the form:: { "biosample": { "name": "new biosample", "donor": 3, ... } } Args: payload: `dict`. The data to send in an HTTP request. Returns: `dict`.
train
https://github.com/nathankw/pulsarpy/blob/359b040c0f2383b88c0b5548715fefd35f5f634c/pulsarpy/models.py#L358-L381
null
class Model(metaclass=Meta): """ The superclass of all model classes. A model subclass is defined for each Rails model. An instance of a model class represents a record of the given Rails model. Subclasses don't typically define their own init method, but if they do, they need to make a call to 'super' to run the init method defined here as well. Subclasses must be instantiated with the rec_id argument set to a record's ID. A GET will immediately be done and the record's attributes will be stored in the self.attrs `dict`. The record's attributes can be accessed as normal instance attributes (i.e. ``record.name) rather than explicitly indexing the attrs dictionary, thanks to the employment of ``__getattr__()``. Similarly, record attributes can be updated via normal assignment operations, i.e. (``record.name = "bob"``), thanks to employment of ``__setattr__()``. Required Environment Variables: 1) PULSAR_API_URL 2) PULSAR_TOKEN """ #: Most models have an attribute alled upstream_identifier that is used to store the value of the #: record in an "upstream" database that is submitted to, i.e. the ENCODE Portal. Not all models #: have this attribute since not all are used for submission to an upstream portal. UPSTREAM_ATTR = "upstream_identifier" MODEL_ABBR = "" # subclasses define #: Abstract attribute of type `dict` that each subclass should fulfull if it has any foreign keys. #: Each key is a foreign key name and the value is the class name of the model it refers to. FKEY_MAP = {} #: A prefix that can be added in front of record IDs, names, model-record ID. This is useful #: when its necessary to add emphasis that these records exist or came from Pulsar ( i.e. when #: submitting them to an upstream database. PULSAR_LIMS_PREFIX = "p" #: This class adds a file handler, such that all messages sent to it are logged to this #: file in addition to STDOUT. debug_logger = logging.getLogger(p.DEBUG_LOGGER_NAME) # Add debug file handler to debug_logger: Meta.add_file_handler(logger=debug_logger, level=logging.DEBUG, tag="debug") #: A ``logging`` instance with a file handler for logging terse error messages. #: The log file resides locally within the directory specified by the constant #: ``p.LOG_DIR``. Accepts messages >= ``logging.ERROR``. error_logger = logging.getLogger(p.ERROR_LOGGER_NAME) log_level = logging.ERROR error_logger.setLevel(log_level) Meta.add_file_handler(logger=error_logger, level=log_level, tag="error") #: A ``logging`` instance with a file handler for logging successful POST operations. #: The log file resides locally within the directory specified by the constant #: ``p.LOG_DIR``. Accepts messages >= ``logging.INFO``. post_logger = logging.getLogger(p.POST_LOGGER_NAME) log_level = logging.INFO post_logger.setLevel(log_level) Meta.add_file_handler(logger=post_logger, level=log_level, tag="posted") log_msg = "-----------------------------------------------------------------------------------" # Check if neccessary environment variables are set: if not p.URL: debug_logger.debug("Warning: Environment variable PULSAR_API_URL not set.") elif not p.API_TOKEN: debug_logger.debug("Warning: Environment variable PULSAR_TOKEN not set.") debug_logger.debug(log_msg) error_logger.error(log_msg) log_msg = "Connecting to {}".format(p.URL) error_logger.error(log_msg) debug_logger.debug(log_msg) #: Connection to Elasticsearch. Expects that the envrionment variables ES_URL, ES_USER, and #: ES_PW are set, which signifiy the Elasticsearch cluster URL, login username and login #: password, respectively. ES = pulsarpy.elasticsearch_utils.Connection() def __init__(self, uid=None, upstream=None): """ Find the record of the given model specified by self.MODEL_NAME. The record can be looked up in a few ways, depending on which argument is specified (uid or upstream). If both are specified, then the upstream argument will be ignored. Args: uid: The database identifier of the record to fetch, which can be specified either as the primary id (i.e. 8) or the model prefix plus the primary id (i.e. B-8). Could also be the record's name if it has a name attribute (not all models do) and if so will be converted to the record ID. upstream: If set, then the record will be searched on its upstream_identifier attribute. """ # self.attrs will store the actual record's attributes. Initialize value now to empty dict # since it is expected to be set already in self.__setattr__(). self.__dict__["attrs"] = {} # rec_id could be the record's name. Check for that scenario, and convert to record ID if # necessary. if uid: rec_id = self.__class__.replace_name_with_id(uid) rec_json = self._get(rec_id=rec_id) elif upstream: rec_json = self._get(upstream=upstream) else: raise ValueError("Either the 'uid' or 'upstream' parameter must be set.") # Convert None values to empty string for key in rec_json: if rec_json[key] == None: rec_json[key] = "" self.rec_id = rec_json["id"] self.__dict__["attrs"] = rec_json #avoid call to self.__setitem__() for this attr. def __getattr__(self, name): """ Treats database attributes for the record as Python attributes. An attribute is looked up in self.attrs. """ return self.attrs[name] def __setattr__(self, name, value): """ Sets the value of an attribute in self.attrs. """ if name not in self.attrs: return object.__setattr__(self, name, value) object.__setattr__(self, self.attrs[name], value) #self.__dict__["attrs"][name] = value #this works too def __getitem__(self, item): return self.attrs[item] def __setitem__(self, item, value): self.attrs[item] = value def _get(self, rec_id=None, upstream=None): """ Fetches a record by the record's ID or upstream_identifier. Raises: `pulsarpy.models.RecordNotFound`: A record could not be found. """ if rec_id: self.record_url = self.__class__.get_record_url(rec_id) self.debug_logger.debug("GET {} record with ID {}: {}".format(self.__class__.__name__, rec_id, self.record_url)) response = requests.get(url=self.record_url, headers=HEADERS, verify=False) if not response.ok and response.status_code == requests.codes.NOT_FOUND: raise RecordNotFound("Search for {} record with ID '{}' returned no results.".format(self.__class__.__name__, rec_id)) self.write_response_html_to_file(response,"get_bob.html") response.raise_for_status() return response.json() elif upstream: rec_json = self.__class__.find_by({"upstream_identifier": upstream}, require=True) self.record_url = self.__class__.get_record_url(rec_json["id"]) return rec_json @classmethod def get_record_url(self, rec_id): return os.path.join(self.URL, str(rec_id)) @classmethod def log_post(cls, res_json): msg = cls.__name__ + "\t" + str(res_json["id"]) + "\t" name = res_json.get("name") if name: msg += name cls.post_logger.info(msg) @classmethod def replace_name_with_id(cls, name): """ Used to replace a foreign key reference using a name with an ID. Works by searching the record in Pulsar and expects to find exactly one hit. First, will check if the foreign key reference is an integer value and if so, returns that as it is presumed to be the foreign key. Raises: `pulsarpy.elasticsearch_utils.MultipleHitsException`: Multiple hits were returned from the name search. `pulsarpy.models.RecordNotFound`: No results were produced from the name search. """ try: int(name) return name #Already a presumed ID. except ValueError: pass #Not an int, so maybe a combination of MODEL_ABBR and Primary Key, i.e. B-8. if name.split("-")[0] in Meta._MODEL_ABBREVS: return int(name.split("-", 1)[1]) try: result = cls.ES.get_record_by_name(cls.ES_INDEX_NAME, name) if result: return result["id"] except pulsarpy.elasticsearch_utils.MultipleHitsException as e: raise raise RecordNotFound("Name '{}' for model '{}' not found.".format(name, cls.__name__)) @classmethod @staticmethod def check_boolean_fields(payload): for key in payload: val = payload[key] if type(val) != str: continue val = val.lower() if val in ["yes", "true", "pass"]: val = True payload[key] = val elif val == ["no", "false", "fail"]: val = False payload[key] = val return payload def get_upstream(self): return self.attrs.get(Model.UPSTREAM_ATTR) def abbrev_id(self): """ This method is called when posting to the ENCODE Portal to grab an alias for the record being submitted. The alias here is composed of the record ID in Pulsar (i.e. B-1 for the Biosample with ID 1). However, the record ID is prefexed with a 'p' to designate that this record was submitted from Pulsar. This is used to generate a unique alias considering that we used to uses a different LIMS (Syapse) to submit records. Many of the models in Syapse used the same model prefix as is used in Pulsar, i.e. (B)Biosample and (L)Library. Thus, w/o the 'p' prefix, the same alias could be generated in Pulsar as a previous one used in Syapse. """ return self.PULSAR_LIMS_PREFIX + self.MODEL_ABBR + "-" + str(self.id) def delete(self): """Deletes the record. """ res = requests.delete(url=self.record_url, headers=HEADERS, verify=False) #self.write_response_html_to_file(res,"bob_delete.html") if res.status_code == 204: #No content. Can't render json: return {} return res.json() @classmethod def find_by(cls, payload, require=False): """ Searches the model in question by AND joining the query parameters. Implements a Railsy way of looking for a record using a method by the same name and passing in the query as a dict. as well. Only the first hit is returned, and there is no particular ordering specified in the server-side API method. Args: payload: `dict`. The attributes of a record to restrict the search to. require: `bool`. True means to raise a `pulsarpy.models.RecordNotFound` exception if no record is found. Returns: `dict`: The JSON serialization of the record, if any, found by the API call. `None`: If the API call didnt' return any results. Raises: `pulsarpy.models.RecordNotFound`: No records were found, and the `require` parameter is True. """ if not isinstance(payload, dict): raise ValueError("The 'payload' parameter must be provided a dictionary object.") url = os.path.join(cls.URL, "find_by") payload = {"find_by": payload} cls.debug_logger.debug("Searching Pulsar {} for {}".format(cls.__name__, json.dumps(payload, indent=4))) res = requests.post(url=url, json=payload, headers=HEADERS, verify=False) #cls.write_response_html_to_file(res,"bob.html") res.raise_for_status() res_json = res.json() if res_json: try: res_json = res_json[cls.MODEL_NAME] except KeyError: # Key won't be present if there isn't a serializer for it on the server. pass else: if require: raise RecordNotFound("Can't find any {} records with search criteria: '{}'.".format(cls.__name__, payload)) return res_json @classmethod def find_by_or(cls, payload): """ Searches the model in question by OR joining the query parameters. Implements a Railsy way of looking for a record using a method by the same name and passing in the query as a string (for the OR operator joining to be specified). Only the first hit is returned, and there is not particular ordering specified in the server-side API method. Args: payload: `dict`. The attributes of a record to search for by using OR operator joining for each query parameter. Returns: `dict`: The JSON serialization of the record, if any, found by the API call. `None`: If the API call didnt' return any results. """ if not isinstance(payload, dict): raise ValueError("The 'payload' parameter must be provided a dictionary object.") url = os.path.join(cls.URL, "find_by_or") payload = {"find_by_or": payload} cls.debug_logger.debug("Searching Pulsar {} for {}".format(cls.__name__, json.dumps(payload, indent=4))) res = requests.post(url=url, json=payload, headers=HEADERS, verify=False) cls.write_response_html_to_file(res,"bob.html") if res: try: res = res[cls.MODEL_NAME] except KeyError: # Key won't be present if there isn't a serializer for it on the server. pass return res @classmethod def index(cls): """Fetches all records. Returns: `dict`. The JSON formatted response. Raises: `requests.exceptions.HTTPError`: The status code is not ok. """ res = requests.get(cls.URL, headers=HEADERS, verify=False) res.raise_for_status() return res.json() def patch(self, payload, append_to_arrays=True): """ Patches current record and udpates the current instance's 'attrs' attribute to reflect the new changes. Args: payload - hash. This will be JSON-formatted prior to sending the request. Returns: `dict`. The JSON formatted response. Raises: `requests.exceptions.HTTPError`: The status code is not ok. """ if not isinstance(payload, dict): raise ValueError("The 'payload' parameter must be provided a dictionary object.") payload = self.__class__.set_id_in_fkeys(payload) if append_to_arrays: for key in payload: val = payload[key] if type(val) == list: val.extend(getattr(self, key)) payload[key] = list(set(val)) payload = self.check_boolean_fields(payload) payload = self.__class__.add_model_name_to_payload(payload) self.debug_logger.debug("PATCHING payload {}".format(json.dumps(payload, indent=4))) res = requests.patch(url=self.record_url, json=payload, headers=HEADERS, verify=False) self.write_response_html_to_file(res,"bob.html") res.raise_for_status() json_res = res.json() self.debug_logger.debug("Success") self.attrs = json_res return json_res @classmethod def set_id_in_fkeys(cls, payload): """ Looks for any keys in the payload that end with either _id or _ids, signaling a foreign key field. For each foreign key field, checks whether the value is using the name of the record or the actual primary ID of the record (which may include the model abbreviation, i.e. B-1). If the former case, the name is replaced with the record's primary ID. Args: payload: `dict`. The payload to POST or PATCH. Returns: `dict`. The payload. """ for key in payload: val = payload[key] if not val: continue if key.endswith("_id"): model = getattr(THIS_MODULE, cls.FKEY_MAP[key]) rec_id = model.replace_name_with_id(name=val) payload[key] = rec_id elif key.endswith("_ids"): model = getattr(THIS_MODULE, cls.FKEY_MAP[key]) rec_ids = [] for v in val: rec_id = model.replace_name_with_id(name=v) rec_ids.append(rec_id) payload[key] = rec_ids return payload @classmethod def prepost_hooks(cls, payload): return payload @classmethod def post(cls, payload): """Posts the data to the specified record. Args: payload: `dict`. This will be JSON-formatted prior to sending the request. Returns: `dict`. The JSON formatted response. Raises: `Requests.exceptions.HTTPError`: The status code is not ok. `RecordNotUnique`: The Rails server returned the exception ActiveRecord::RecordNotUnique. """ if not isinstance(payload, dict): raise ValueError("The 'payload' parameter must be provided a dictionary object.") payload = cls.set_id_in_fkeys(payload) payload = cls.check_boolean_fields(payload) payload = cls.add_model_name_to_payload(payload) # Run any pre-post hooks: payload = cls.prepost_hooks(payload) cls.debug_logger.debug("POSTING payload {}".format(json.dumps(payload, indent=4))) res = requests.post(url=cls.URL, json=(payload), headers=HEADERS, verify=False) cls.write_response_html_to_file(res,"bob.html") if not res.ok: cls.log_error(res.text) res_json = res.json() if "exception" in res_json: exc_type = res_json["exception"] if exc_type == "ActiveRecord::RecordNotUnique": raise RecordNotUnique() res.raise_for_status() res = res.json() cls.log_post(res) cls.debug_logger.debug("Success") return res @classmethod def log_error(cls, msg): """ Logs the provided error message to both the error logger and the debug logger logging instances. Args: msg: `str`. The error message to log. """ cls.error_logger.error(msg) cls.debug_logger.debug(msg) @staticmethod def write_response_html_to_file(response,filename): """ An aid in troubleshooting internal application errors, i.e. <Response [500]>, to be mainly beneficial when developing the server-side API. This method will write the response HTML for viewing the error details in the browesr. Args: response: `requests.models.Response` instance. filename: `str`. The output file name. """ fout = open(filename,'w') if not str(response.status_code).startswith("2"): Model.debug_logger.debug(response.text) fout.write(response.text) fout.close()
nathankw/pulsarpy
pulsarpy/models.py
Model.delete
python
def delete(self): res = requests.delete(url=self.record_url, headers=HEADERS, verify=False) #self.write_response_html_to_file(res,"bob_delete.html") if res.status_code == 204: #No content. Can't render json: return {} return res.json()
Deletes the record.
train
https://github.com/nathankw/pulsarpy/blob/359b040c0f2383b88c0b5548715fefd35f5f634c/pulsarpy/models.py#L413-L421
null
class Model(metaclass=Meta): """ The superclass of all model classes. A model subclass is defined for each Rails model. An instance of a model class represents a record of the given Rails model. Subclasses don't typically define their own init method, but if they do, they need to make a call to 'super' to run the init method defined here as well. Subclasses must be instantiated with the rec_id argument set to a record's ID. A GET will immediately be done and the record's attributes will be stored in the self.attrs `dict`. The record's attributes can be accessed as normal instance attributes (i.e. ``record.name) rather than explicitly indexing the attrs dictionary, thanks to the employment of ``__getattr__()``. Similarly, record attributes can be updated via normal assignment operations, i.e. (``record.name = "bob"``), thanks to employment of ``__setattr__()``. Required Environment Variables: 1) PULSAR_API_URL 2) PULSAR_TOKEN """ #: Most models have an attribute alled upstream_identifier that is used to store the value of the #: record in an "upstream" database that is submitted to, i.e. the ENCODE Portal. Not all models #: have this attribute since not all are used for submission to an upstream portal. UPSTREAM_ATTR = "upstream_identifier" MODEL_ABBR = "" # subclasses define #: Abstract attribute of type `dict` that each subclass should fulfull if it has any foreign keys. #: Each key is a foreign key name and the value is the class name of the model it refers to. FKEY_MAP = {} #: A prefix that can be added in front of record IDs, names, model-record ID. This is useful #: when its necessary to add emphasis that these records exist or came from Pulsar ( i.e. when #: submitting them to an upstream database. PULSAR_LIMS_PREFIX = "p" #: This class adds a file handler, such that all messages sent to it are logged to this #: file in addition to STDOUT. debug_logger = logging.getLogger(p.DEBUG_LOGGER_NAME) # Add debug file handler to debug_logger: Meta.add_file_handler(logger=debug_logger, level=logging.DEBUG, tag="debug") #: A ``logging`` instance with a file handler for logging terse error messages. #: The log file resides locally within the directory specified by the constant #: ``p.LOG_DIR``. Accepts messages >= ``logging.ERROR``. error_logger = logging.getLogger(p.ERROR_LOGGER_NAME) log_level = logging.ERROR error_logger.setLevel(log_level) Meta.add_file_handler(logger=error_logger, level=log_level, tag="error") #: A ``logging`` instance with a file handler for logging successful POST operations. #: The log file resides locally within the directory specified by the constant #: ``p.LOG_DIR``. Accepts messages >= ``logging.INFO``. post_logger = logging.getLogger(p.POST_LOGGER_NAME) log_level = logging.INFO post_logger.setLevel(log_level) Meta.add_file_handler(logger=post_logger, level=log_level, tag="posted") log_msg = "-----------------------------------------------------------------------------------" # Check if neccessary environment variables are set: if not p.URL: debug_logger.debug("Warning: Environment variable PULSAR_API_URL not set.") elif not p.API_TOKEN: debug_logger.debug("Warning: Environment variable PULSAR_TOKEN not set.") debug_logger.debug(log_msg) error_logger.error(log_msg) log_msg = "Connecting to {}".format(p.URL) error_logger.error(log_msg) debug_logger.debug(log_msg) #: Connection to Elasticsearch. Expects that the envrionment variables ES_URL, ES_USER, and #: ES_PW are set, which signifiy the Elasticsearch cluster URL, login username and login #: password, respectively. ES = pulsarpy.elasticsearch_utils.Connection() def __init__(self, uid=None, upstream=None): """ Find the record of the given model specified by self.MODEL_NAME. The record can be looked up in a few ways, depending on which argument is specified (uid or upstream). If both are specified, then the upstream argument will be ignored. Args: uid: The database identifier of the record to fetch, which can be specified either as the primary id (i.e. 8) or the model prefix plus the primary id (i.e. B-8). Could also be the record's name if it has a name attribute (not all models do) and if so will be converted to the record ID. upstream: If set, then the record will be searched on its upstream_identifier attribute. """ # self.attrs will store the actual record's attributes. Initialize value now to empty dict # since it is expected to be set already in self.__setattr__(). self.__dict__["attrs"] = {} # rec_id could be the record's name. Check for that scenario, and convert to record ID if # necessary. if uid: rec_id = self.__class__.replace_name_with_id(uid) rec_json = self._get(rec_id=rec_id) elif upstream: rec_json = self._get(upstream=upstream) else: raise ValueError("Either the 'uid' or 'upstream' parameter must be set.") # Convert None values to empty string for key in rec_json: if rec_json[key] == None: rec_json[key] = "" self.rec_id = rec_json["id"] self.__dict__["attrs"] = rec_json #avoid call to self.__setitem__() for this attr. def __getattr__(self, name): """ Treats database attributes for the record as Python attributes. An attribute is looked up in self.attrs. """ return self.attrs[name] def __setattr__(self, name, value): """ Sets the value of an attribute in self.attrs. """ if name not in self.attrs: return object.__setattr__(self, name, value) object.__setattr__(self, self.attrs[name], value) #self.__dict__["attrs"][name] = value #this works too def __getitem__(self, item): return self.attrs[item] def __setitem__(self, item, value): self.attrs[item] = value def _get(self, rec_id=None, upstream=None): """ Fetches a record by the record's ID or upstream_identifier. Raises: `pulsarpy.models.RecordNotFound`: A record could not be found. """ if rec_id: self.record_url = self.__class__.get_record_url(rec_id) self.debug_logger.debug("GET {} record with ID {}: {}".format(self.__class__.__name__, rec_id, self.record_url)) response = requests.get(url=self.record_url, headers=HEADERS, verify=False) if not response.ok and response.status_code == requests.codes.NOT_FOUND: raise RecordNotFound("Search for {} record with ID '{}' returned no results.".format(self.__class__.__name__, rec_id)) self.write_response_html_to_file(response,"get_bob.html") response.raise_for_status() return response.json() elif upstream: rec_json = self.__class__.find_by({"upstream_identifier": upstream}, require=True) self.record_url = self.__class__.get_record_url(rec_json["id"]) return rec_json @classmethod def get_record_url(self, rec_id): return os.path.join(self.URL, str(rec_id)) @classmethod def log_post(cls, res_json): msg = cls.__name__ + "\t" + str(res_json["id"]) + "\t" name = res_json.get("name") if name: msg += name cls.post_logger.info(msg) @classmethod def replace_name_with_id(cls, name): """ Used to replace a foreign key reference using a name with an ID. Works by searching the record in Pulsar and expects to find exactly one hit. First, will check if the foreign key reference is an integer value and if so, returns that as it is presumed to be the foreign key. Raises: `pulsarpy.elasticsearch_utils.MultipleHitsException`: Multiple hits were returned from the name search. `pulsarpy.models.RecordNotFound`: No results were produced from the name search. """ try: int(name) return name #Already a presumed ID. except ValueError: pass #Not an int, so maybe a combination of MODEL_ABBR and Primary Key, i.e. B-8. if name.split("-")[0] in Meta._MODEL_ABBREVS: return int(name.split("-", 1)[1]) try: result = cls.ES.get_record_by_name(cls.ES_INDEX_NAME, name) if result: return result["id"] except pulsarpy.elasticsearch_utils.MultipleHitsException as e: raise raise RecordNotFound("Name '{}' for model '{}' not found.".format(name, cls.__name__)) @classmethod def add_model_name_to_payload(cls, payload): """ Checks whether the model name in question is in the payload. If not, the entire payload is set as a value of a key by the name of the model. This method is useful when some server-side Rails API calls expect the parameters to include the parameterized model name. For example, server-side endpoints that handle the updating of a biosample record or the creation of a new biosmample record will expect the payload to be of the form:: { "biosample": { "name": "new biosample", "donor": 3, ... } } Args: payload: `dict`. The data to send in an HTTP request. Returns: `dict`. """ if not cls.MODEL_NAME in payload: payload = {cls.MODEL_NAME: payload} return payload @staticmethod def check_boolean_fields(payload): for key in payload: val = payload[key] if type(val) != str: continue val = val.lower() if val in ["yes", "true", "pass"]: val = True payload[key] = val elif val == ["no", "false", "fail"]: val = False payload[key] = val return payload def get_upstream(self): return self.attrs.get(Model.UPSTREAM_ATTR) def abbrev_id(self): """ This method is called when posting to the ENCODE Portal to grab an alias for the record being submitted. The alias here is composed of the record ID in Pulsar (i.e. B-1 for the Biosample with ID 1). However, the record ID is prefexed with a 'p' to designate that this record was submitted from Pulsar. This is used to generate a unique alias considering that we used to uses a different LIMS (Syapse) to submit records. Many of the models in Syapse used the same model prefix as is used in Pulsar, i.e. (B)Biosample and (L)Library. Thus, w/o the 'p' prefix, the same alias could be generated in Pulsar as a previous one used in Syapse. """ return self.PULSAR_LIMS_PREFIX + self.MODEL_ABBR + "-" + str(self.id) @classmethod def find_by(cls, payload, require=False): """ Searches the model in question by AND joining the query parameters. Implements a Railsy way of looking for a record using a method by the same name and passing in the query as a dict. as well. Only the first hit is returned, and there is no particular ordering specified in the server-side API method. Args: payload: `dict`. The attributes of a record to restrict the search to. require: `bool`. True means to raise a `pulsarpy.models.RecordNotFound` exception if no record is found. Returns: `dict`: The JSON serialization of the record, if any, found by the API call. `None`: If the API call didnt' return any results. Raises: `pulsarpy.models.RecordNotFound`: No records were found, and the `require` parameter is True. """ if not isinstance(payload, dict): raise ValueError("The 'payload' parameter must be provided a dictionary object.") url = os.path.join(cls.URL, "find_by") payload = {"find_by": payload} cls.debug_logger.debug("Searching Pulsar {} for {}".format(cls.__name__, json.dumps(payload, indent=4))) res = requests.post(url=url, json=payload, headers=HEADERS, verify=False) #cls.write_response_html_to_file(res,"bob.html") res.raise_for_status() res_json = res.json() if res_json: try: res_json = res_json[cls.MODEL_NAME] except KeyError: # Key won't be present if there isn't a serializer for it on the server. pass else: if require: raise RecordNotFound("Can't find any {} records with search criteria: '{}'.".format(cls.__name__, payload)) return res_json @classmethod def find_by_or(cls, payload): """ Searches the model in question by OR joining the query parameters. Implements a Railsy way of looking for a record using a method by the same name and passing in the query as a string (for the OR operator joining to be specified). Only the first hit is returned, and there is not particular ordering specified in the server-side API method. Args: payload: `dict`. The attributes of a record to search for by using OR operator joining for each query parameter. Returns: `dict`: The JSON serialization of the record, if any, found by the API call. `None`: If the API call didnt' return any results. """ if not isinstance(payload, dict): raise ValueError("The 'payload' parameter must be provided a dictionary object.") url = os.path.join(cls.URL, "find_by_or") payload = {"find_by_or": payload} cls.debug_logger.debug("Searching Pulsar {} for {}".format(cls.__name__, json.dumps(payload, indent=4))) res = requests.post(url=url, json=payload, headers=HEADERS, verify=False) cls.write_response_html_to_file(res,"bob.html") if res: try: res = res[cls.MODEL_NAME] except KeyError: # Key won't be present if there isn't a serializer for it on the server. pass return res @classmethod def index(cls): """Fetches all records. Returns: `dict`. The JSON formatted response. Raises: `requests.exceptions.HTTPError`: The status code is not ok. """ res = requests.get(cls.URL, headers=HEADERS, verify=False) res.raise_for_status() return res.json() def patch(self, payload, append_to_arrays=True): """ Patches current record and udpates the current instance's 'attrs' attribute to reflect the new changes. Args: payload - hash. This will be JSON-formatted prior to sending the request. Returns: `dict`. The JSON formatted response. Raises: `requests.exceptions.HTTPError`: The status code is not ok. """ if not isinstance(payload, dict): raise ValueError("The 'payload' parameter must be provided a dictionary object.") payload = self.__class__.set_id_in_fkeys(payload) if append_to_arrays: for key in payload: val = payload[key] if type(val) == list: val.extend(getattr(self, key)) payload[key] = list(set(val)) payload = self.check_boolean_fields(payload) payload = self.__class__.add_model_name_to_payload(payload) self.debug_logger.debug("PATCHING payload {}".format(json.dumps(payload, indent=4))) res = requests.patch(url=self.record_url, json=payload, headers=HEADERS, verify=False) self.write_response_html_to_file(res,"bob.html") res.raise_for_status() json_res = res.json() self.debug_logger.debug("Success") self.attrs = json_res return json_res @classmethod def set_id_in_fkeys(cls, payload): """ Looks for any keys in the payload that end with either _id or _ids, signaling a foreign key field. For each foreign key field, checks whether the value is using the name of the record or the actual primary ID of the record (which may include the model abbreviation, i.e. B-1). If the former case, the name is replaced with the record's primary ID. Args: payload: `dict`. The payload to POST or PATCH. Returns: `dict`. The payload. """ for key in payload: val = payload[key] if not val: continue if key.endswith("_id"): model = getattr(THIS_MODULE, cls.FKEY_MAP[key]) rec_id = model.replace_name_with_id(name=val) payload[key] = rec_id elif key.endswith("_ids"): model = getattr(THIS_MODULE, cls.FKEY_MAP[key]) rec_ids = [] for v in val: rec_id = model.replace_name_with_id(name=v) rec_ids.append(rec_id) payload[key] = rec_ids return payload @classmethod def prepost_hooks(cls, payload): return payload @classmethod def post(cls, payload): """Posts the data to the specified record. Args: payload: `dict`. This will be JSON-formatted prior to sending the request. Returns: `dict`. The JSON formatted response. Raises: `Requests.exceptions.HTTPError`: The status code is not ok. `RecordNotUnique`: The Rails server returned the exception ActiveRecord::RecordNotUnique. """ if not isinstance(payload, dict): raise ValueError("The 'payload' parameter must be provided a dictionary object.") payload = cls.set_id_in_fkeys(payload) payload = cls.check_boolean_fields(payload) payload = cls.add_model_name_to_payload(payload) # Run any pre-post hooks: payload = cls.prepost_hooks(payload) cls.debug_logger.debug("POSTING payload {}".format(json.dumps(payload, indent=4))) res = requests.post(url=cls.URL, json=(payload), headers=HEADERS, verify=False) cls.write_response_html_to_file(res,"bob.html") if not res.ok: cls.log_error(res.text) res_json = res.json() if "exception" in res_json: exc_type = res_json["exception"] if exc_type == "ActiveRecord::RecordNotUnique": raise RecordNotUnique() res.raise_for_status() res = res.json() cls.log_post(res) cls.debug_logger.debug("Success") return res @classmethod def log_error(cls, msg): """ Logs the provided error message to both the error logger and the debug logger logging instances. Args: msg: `str`. The error message to log. """ cls.error_logger.error(msg) cls.debug_logger.debug(msg) @staticmethod def write_response_html_to_file(response,filename): """ An aid in troubleshooting internal application errors, i.e. <Response [500]>, to be mainly beneficial when developing the server-side API. This method will write the response HTML for viewing the error details in the browesr. Args: response: `requests.models.Response` instance. filename: `str`. The output file name. """ fout = open(filename,'w') if not str(response.status_code).startswith("2"): Model.debug_logger.debug(response.text) fout.write(response.text) fout.close()
nathankw/pulsarpy
pulsarpy/models.py
Model.find_by
python
def find_by(cls, payload, require=False): if not isinstance(payload, dict): raise ValueError("The 'payload' parameter must be provided a dictionary object.") url = os.path.join(cls.URL, "find_by") payload = {"find_by": payload} cls.debug_logger.debug("Searching Pulsar {} for {}".format(cls.__name__, json.dumps(payload, indent=4))) res = requests.post(url=url, json=payload, headers=HEADERS, verify=False) #cls.write_response_html_to_file(res,"bob.html") res.raise_for_status() res_json = res.json() if res_json: try: res_json = res_json[cls.MODEL_NAME] except KeyError: # Key won't be present if there isn't a serializer for it on the server. pass else: if require: raise RecordNotFound("Can't find any {} records with search criteria: '{}'.".format(cls.__name__, payload)) return res_json
Searches the model in question by AND joining the query parameters. Implements a Railsy way of looking for a record using a method by the same name and passing in the query as a dict. as well. Only the first hit is returned, and there is no particular ordering specified in the server-side API method. Args: payload: `dict`. The attributes of a record to restrict the search to. require: `bool`. True means to raise a `pulsarpy.models.RecordNotFound` exception if no record is found. Returns: `dict`: The JSON serialization of the record, if any, found by the API call. `None`: If the API call didnt' return any results. Raises: `pulsarpy.models.RecordNotFound`: No records were found, and the `require` parameter is True.
train
https://github.com/nathankw/pulsarpy/blob/359b040c0f2383b88c0b5548715fefd35f5f634c/pulsarpy/models.py#L424-L463
null
class Model(metaclass=Meta): """ The superclass of all model classes. A model subclass is defined for each Rails model. An instance of a model class represents a record of the given Rails model. Subclasses don't typically define their own init method, but if they do, they need to make a call to 'super' to run the init method defined here as well. Subclasses must be instantiated with the rec_id argument set to a record's ID. A GET will immediately be done and the record's attributes will be stored in the self.attrs `dict`. The record's attributes can be accessed as normal instance attributes (i.e. ``record.name) rather than explicitly indexing the attrs dictionary, thanks to the employment of ``__getattr__()``. Similarly, record attributes can be updated via normal assignment operations, i.e. (``record.name = "bob"``), thanks to employment of ``__setattr__()``. Required Environment Variables: 1) PULSAR_API_URL 2) PULSAR_TOKEN """ #: Most models have an attribute alled upstream_identifier that is used to store the value of the #: record in an "upstream" database that is submitted to, i.e. the ENCODE Portal. Not all models #: have this attribute since not all are used for submission to an upstream portal. UPSTREAM_ATTR = "upstream_identifier" MODEL_ABBR = "" # subclasses define #: Abstract attribute of type `dict` that each subclass should fulfull if it has any foreign keys. #: Each key is a foreign key name and the value is the class name of the model it refers to. FKEY_MAP = {} #: A prefix that can be added in front of record IDs, names, model-record ID. This is useful #: when its necessary to add emphasis that these records exist or came from Pulsar ( i.e. when #: submitting them to an upstream database. PULSAR_LIMS_PREFIX = "p" #: This class adds a file handler, such that all messages sent to it are logged to this #: file in addition to STDOUT. debug_logger = logging.getLogger(p.DEBUG_LOGGER_NAME) # Add debug file handler to debug_logger: Meta.add_file_handler(logger=debug_logger, level=logging.DEBUG, tag="debug") #: A ``logging`` instance with a file handler for logging terse error messages. #: The log file resides locally within the directory specified by the constant #: ``p.LOG_DIR``. Accepts messages >= ``logging.ERROR``. error_logger = logging.getLogger(p.ERROR_LOGGER_NAME) log_level = logging.ERROR error_logger.setLevel(log_level) Meta.add_file_handler(logger=error_logger, level=log_level, tag="error") #: A ``logging`` instance with a file handler for logging successful POST operations. #: The log file resides locally within the directory specified by the constant #: ``p.LOG_DIR``. Accepts messages >= ``logging.INFO``. post_logger = logging.getLogger(p.POST_LOGGER_NAME) log_level = logging.INFO post_logger.setLevel(log_level) Meta.add_file_handler(logger=post_logger, level=log_level, tag="posted") log_msg = "-----------------------------------------------------------------------------------" # Check if neccessary environment variables are set: if not p.URL: debug_logger.debug("Warning: Environment variable PULSAR_API_URL not set.") elif not p.API_TOKEN: debug_logger.debug("Warning: Environment variable PULSAR_TOKEN not set.") debug_logger.debug(log_msg) error_logger.error(log_msg) log_msg = "Connecting to {}".format(p.URL) error_logger.error(log_msg) debug_logger.debug(log_msg) #: Connection to Elasticsearch. Expects that the envrionment variables ES_URL, ES_USER, and #: ES_PW are set, which signifiy the Elasticsearch cluster URL, login username and login #: password, respectively. ES = pulsarpy.elasticsearch_utils.Connection() def __init__(self, uid=None, upstream=None): """ Find the record of the given model specified by self.MODEL_NAME. The record can be looked up in a few ways, depending on which argument is specified (uid or upstream). If both are specified, then the upstream argument will be ignored. Args: uid: The database identifier of the record to fetch, which can be specified either as the primary id (i.e. 8) or the model prefix plus the primary id (i.e. B-8). Could also be the record's name if it has a name attribute (not all models do) and if so will be converted to the record ID. upstream: If set, then the record will be searched on its upstream_identifier attribute. """ # self.attrs will store the actual record's attributes. Initialize value now to empty dict # since it is expected to be set already in self.__setattr__(). self.__dict__["attrs"] = {} # rec_id could be the record's name. Check for that scenario, and convert to record ID if # necessary. if uid: rec_id = self.__class__.replace_name_with_id(uid) rec_json = self._get(rec_id=rec_id) elif upstream: rec_json = self._get(upstream=upstream) else: raise ValueError("Either the 'uid' or 'upstream' parameter must be set.") # Convert None values to empty string for key in rec_json: if rec_json[key] == None: rec_json[key] = "" self.rec_id = rec_json["id"] self.__dict__["attrs"] = rec_json #avoid call to self.__setitem__() for this attr. def __getattr__(self, name): """ Treats database attributes for the record as Python attributes. An attribute is looked up in self.attrs. """ return self.attrs[name] def __setattr__(self, name, value): """ Sets the value of an attribute in self.attrs. """ if name not in self.attrs: return object.__setattr__(self, name, value) object.__setattr__(self, self.attrs[name], value) #self.__dict__["attrs"][name] = value #this works too def __getitem__(self, item): return self.attrs[item] def __setitem__(self, item, value): self.attrs[item] = value def _get(self, rec_id=None, upstream=None): """ Fetches a record by the record's ID or upstream_identifier. Raises: `pulsarpy.models.RecordNotFound`: A record could not be found. """ if rec_id: self.record_url = self.__class__.get_record_url(rec_id) self.debug_logger.debug("GET {} record with ID {}: {}".format(self.__class__.__name__, rec_id, self.record_url)) response = requests.get(url=self.record_url, headers=HEADERS, verify=False) if not response.ok and response.status_code == requests.codes.NOT_FOUND: raise RecordNotFound("Search for {} record with ID '{}' returned no results.".format(self.__class__.__name__, rec_id)) self.write_response_html_to_file(response,"get_bob.html") response.raise_for_status() return response.json() elif upstream: rec_json = self.__class__.find_by({"upstream_identifier": upstream}, require=True) self.record_url = self.__class__.get_record_url(rec_json["id"]) return rec_json @classmethod def get_record_url(self, rec_id): return os.path.join(self.URL, str(rec_id)) @classmethod def log_post(cls, res_json): msg = cls.__name__ + "\t" + str(res_json["id"]) + "\t" name = res_json.get("name") if name: msg += name cls.post_logger.info(msg) @classmethod def replace_name_with_id(cls, name): """ Used to replace a foreign key reference using a name with an ID. Works by searching the record in Pulsar and expects to find exactly one hit. First, will check if the foreign key reference is an integer value and if so, returns that as it is presumed to be the foreign key. Raises: `pulsarpy.elasticsearch_utils.MultipleHitsException`: Multiple hits were returned from the name search. `pulsarpy.models.RecordNotFound`: No results were produced from the name search. """ try: int(name) return name #Already a presumed ID. except ValueError: pass #Not an int, so maybe a combination of MODEL_ABBR and Primary Key, i.e. B-8. if name.split("-")[0] in Meta._MODEL_ABBREVS: return int(name.split("-", 1)[1]) try: result = cls.ES.get_record_by_name(cls.ES_INDEX_NAME, name) if result: return result["id"] except pulsarpy.elasticsearch_utils.MultipleHitsException as e: raise raise RecordNotFound("Name '{}' for model '{}' not found.".format(name, cls.__name__)) @classmethod def add_model_name_to_payload(cls, payload): """ Checks whether the model name in question is in the payload. If not, the entire payload is set as a value of a key by the name of the model. This method is useful when some server-side Rails API calls expect the parameters to include the parameterized model name. For example, server-side endpoints that handle the updating of a biosample record or the creation of a new biosmample record will expect the payload to be of the form:: { "biosample": { "name": "new biosample", "donor": 3, ... } } Args: payload: `dict`. The data to send in an HTTP request. Returns: `dict`. """ if not cls.MODEL_NAME in payload: payload = {cls.MODEL_NAME: payload} return payload @staticmethod def check_boolean_fields(payload): for key in payload: val = payload[key] if type(val) != str: continue val = val.lower() if val in ["yes", "true", "pass"]: val = True payload[key] = val elif val == ["no", "false", "fail"]: val = False payload[key] = val return payload def get_upstream(self): return self.attrs.get(Model.UPSTREAM_ATTR) def abbrev_id(self): """ This method is called when posting to the ENCODE Portal to grab an alias for the record being submitted. The alias here is composed of the record ID in Pulsar (i.e. B-1 for the Biosample with ID 1). However, the record ID is prefexed with a 'p' to designate that this record was submitted from Pulsar. This is used to generate a unique alias considering that we used to uses a different LIMS (Syapse) to submit records. Many of the models in Syapse used the same model prefix as is used in Pulsar, i.e. (B)Biosample and (L)Library. Thus, w/o the 'p' prefix, the same alias could be generated in Pulsar as a previous one used in Syapse. """ return self.PULSAR_LIMS_PREFIX + self.MODEL_ABBR + "-" + str(self.id) def delete(self): """Deletes the record. """ res = requests.delete(url=self.record_url, headers=HEADERS, verify=False) #self.write_response_html_to_file(res,"bob_delete.html") if res.status_code == 204: #No content. Can't render json: return {} return res.json() @classmethod @classmethod def find_by_or(cls, payload): """ Searches the model in question by OR joining the query parameters. Implements a Railsy way of looking for a record using a method by the same name and passing in the query as a string (for the OR operator joining to be specified). Only the first hit is returned, and there is not particular ordering specified in the server-side API method. Args: payload: `dict`. The attributes of a record to search for by using OR operator joining for each query parameter. Returns: `dict`: The JSON serialization of the record, if any, found by the API call. `None`: If the API call didnt' return any results. """ if not isinstance(payload, dict): raise ValueError("The 'payload' parameter must be provided a dictionary object.") url = os.path.join(cls.URL, "find_by_or") payload = {"find_by_or": payload} cls.debug_logger.debug("Searching Pulsar {} for {}".format(cls.__name__, json.dumps(payload, indent=4))) res = requests.post(url=url, json=payload, headers=HEADERS, verify=False) cls.write_response_html_to_file(res,"bob.html") if res: try: res = res[cls.MODEL_NAME] except KeyError: # Key won't be present if there isn't a serializer for it on the server. pass return res @classmethod def index(cls): """Fetches all records. Returns: `dict`. The JSON formatted response. Raises: `requests.exceptions.HTTPError`: The status code is not ok. """ res = requests.get(cls.URL, headers=HEADERS, verify=False) res.raise_for_status() return res.json() def patch(self, payload, append_to_arrays=True): """ Patches current record and udpates the current instance's 'attrs' attribute to reflect the new changes. Args: payload - hash. This will be JSON-formatted prior to sending the request. Returns: `dict`. The JSON formatted response. Raises: `requests.exceptions.HTTPError`: The status code is not ok. """ if not isinstance(payload, dict): raise ValueError("The 'payload' parameter must be provided a dictionary object.") payload = self.__class__.set_id_in_fkeys(payload) if append_to_arrays: for key in payload: val = payload[key] if type(val) == list: val.extend(getattr(self, key)) payload[key] = list(set(val)) payload = self.check_boolean_fields(payload) payload = self.__class__.add_model_name_to_payload(payload) self.debug_logger.debug("PATCHING payload {}".format(json.dumps(payload, indent=4))) res = requests.patch(url=self.record_url, json=payload, headers=HEADERS, verify=False) self.write_response_html_to_file(res,"bob.html") res.raise_for_status() json_res = res.json() self.debug_logger.debug("Success") self.attrs = json_res return json_res @classmethod def set_id_in_fkeys(cls, payload): """ Looks for any keys in the payload that end with either _id or _ids, signaling a foreign key field. For each foreign key field, checks whether the value is using the name of the record or the actual primary ID of the record (which may include the model abbreviation, i.e. B-1). If the former case, the name is replaced with the record's primary ID. Args: payload: `dict`. The payload to POST or PATCH. Returns: `dict`. The payload. """ for key in payload: val = payload[key] if not val: continue if key.endswith("_id"): model = getattr(THIS_MODULE, cls.FKEY_MAP[key]) rec_id = model.replace_name_with_id(name=val) payload[key] = rec_id elif key.endswith("_ids"): model = getattr(THIS_MODULE, cls.FKEY_MAP[key]) rec_ids = [] for v in val: rec_id = model.replace_name_with_id(name=v) rec_ids.append(rec_id) payload[key] = rec_ids return payload @classmethod def prepost_hooks(cls, payload): return payload @classmethod def post(cls, payload): """Posts the data to the specified record. Args: payload: `dict`. This will be JSON-formatted prior to sending the request. Returns: `dict`. The JSON formatted response. Raises: `Requests.exceptions.HTTPError`: The status code is not ok. `RecordNotUnique`: The Rails server returned the exception ActiveRecord::RecordNotUnique. """ if not isinstance(payload, dict): raise ValueError("The 'payload' parameter must be provided a dictionary object.") payload = cls.set_id_in_fkeys(payload) payload = cls.check_boolean_fields(payload) payload = cls.add_model_name_to_payload(payload) # Run any pre-post hooks: payload = cls.prepost_hooks(payload) cls.debug_logger.debug("POSTING payload {}".format(json.dumps(payload, indent=4))) res = requests.post(url=cls.URL, json=(payload), headers=HEADERS, verify=False) cls.write_response_html_to_file(res,"bob.html") if not res.ok: cls.log_error(res.text) res_json = res.json() if "exception" in res_json: exc_type = res_json["exception"] if exc_type == "ActiveRecord::RecordNotUnique": raise RecordNotUnique() res.raise_for_status() res = res.json() cls.log_post(res) cls.debug_logger.debug("Success") return res @classmethod def log_error(cls, msg): """ Logs the provided error message to both the error logger and the debug logger logging instances. Args: msg: `str`. The error message to log. """ cls.error_logger.error(msg) cls.debug_logger.debug(msg) @staticmethod def write_response_html_to_file(response,filename): """ An aid in troubleshooting internal application errors, i.e. <Response [500]>, to be mainly beneficial when developing the server-side API. This method will write the response HTML for viewing the error details in the browesr. Args: response: `requests.models.Response` instance. filename: `str`. The output file name. """ fout = open(filename,'w') if not str(response.status_code).startswith("2"): Model.debug_logger.debug(response.text) fout.write(response.text) fout.close()
nathankw/pulsarpy
pulsarpy/models.py
Model.find_by_or
python
def find_by_or(cls, payload): if not isinstance(payload, dict): raise ValueError("The 'payload' parameter must be provided a dictionary object.") url = os.path.join(cls.URL, "find_by_or") payload = {"find_by_or": payload} cls.debug_logger.debug("Searching Pulsar {} for {}".format(cls.__name__, json.dumps(payload, indent=4))) res = requests.post(url=url, json=payload, headers=HEADERS, verify=False) cls.write_response_html_to_file(res,"bob.html") if res: try: res = res[cls.MODEL_NAME] except KeyError: # Key won't be present if there isn't a serializer for it on the server. pass return res
Searches the model in question by OR joining the query parameters. Implements a Railsy way of looking for a record using a method by the same name and passing in the query as a string (for the OR operator joining to be specified). Only the first hit is returned, and there is not particular ordering specified in the server-side API method. Args: payload: `dict`. The attributes of a record to search for by using OR operator joining for each query parameter. Returns: `dict`: The JSON serialization of the record, if any, found by the API call. `None`: If the API call didnt' return any results.
train
https://github.com/nathankw/pulsarpy/blob/359b040c0f2383b88c0b5548715fefd35f5f634c/pulsarpy/models.py#L466-L497
null
class Model(metaclass=Meta): """ The superclass of all model classes. A model subclass is defined for each Rails model. An instance of a model class represents a record of the given Rails model. Subclasses don't typically define their own init method, but if they do, they need to make a call to 'super' to run the init method defined here as well. Subclasses must be instantiated with the rec_id argument set to a record's ID. A GET will immediately be done and the record's attributes will be stored in the self.attrs `dict`. The record's attributes can be accessed as normal instance attributes (i.e. ``record.name) rather than explicitly indexing the attrs dictionary, thanks to the employment of ``__getattr__()``. Similarly, record attributes can be updated via normal assignment operations, i.e. (``record.name = "bob"``), thanks to employment of ``__setattr__()``. Required Environment Variables: 1) PULSAR_API_URL 2) PULSAR_TOKEN """ #: Most models have an attribute alled upstream_identifier that is used to store the value of the #: record in an "upstream" database that is submitted to, i.e. the ENCODE Portal. Not all models #: have this attribute since not all are used for submission to an upstream portal. UPSTREAM_ATTR = "upstream_identifier" MODEL_ABBR = "" # subclasses define #: Abstract attribute of type `dict` that each subclass should fulfull if it has any foreign keys. #: Each key is a foreign key name and the value is the class name of the model it refers to. FKEY_MAP = {} #: A prefix that can be added in front of record IDs, names, model-record ID. This is useful #: when its necessary to add emphasis that these records exist or came from Pulsar ( i.e. when #: submitting them to an upstream database. PULSAR_LIMS_PREFIX = "p" #: This class adds a file handler, such that all messages sent to it are logged to this #: file in addition to STDOUT. debug_logger = logging.getLogger(p.DEBUG_LOGGER_NAME) # Add debug file handler to debug_logger: Meta.add_file_handler(logger=debug_logger, level=logging.DEBUG, tag="debug") #: A ``logging`` instance with a file handler for logging terse error messages. #: The log file resides locally within the directory specified by the constant #: ``p.LOG_DIR``. Accepts messages >= ``logging.ERROR``. error_logger = logging.getLogger(p.ERROR_LOGGER_NAME) log_level = logging.ERROR error_logger.setLevel(log_level) Meta.add_file_handler(logger=error_logger, level=log_level, tag="error") #: A ``logging`` instance with a file handler for logging successful POST operations. #: The log file resides locally within the directory specified by the constant #: ``p.LOG_DIR``. Accepts messages >= ``logging.INFO``. post_logger = logging.getLogger(p.POST_LOGGER_NAME) log_level = logging.INFO post_logger.setLevel(log_level) Meta.add_file_handler(logger=post_logger, level=log_level, tag="posted") log_msg = "-----------------------------------------------------------------------------------" # Check if neccessary environment variables are set: if not p.URL: debug_logger.debug("Warning: Environment variable PULSAR_API_URL not set.") elif not p.API_TOKEN: debug_logger.debug("Warning: Environment variable PULSAR_TOKEN not set.") debug_logger.debug(log_msg) error_logger.error(log_msg) log_msg = "Connecting to {}".format(p.URL) error_logger.error(log_msg) debug_logger.debug(log_msg) #: Connection to Elasticsearch. Expects that the envrionment variables ES_URL, ES_USER, and #: ES_PW are set, which signifiy the Elasticsearch cluster URL, login username and login #: password, respectively. ES = pulsarpy.elasticsearch_utils.Connection() def __init__(self, uid=None, upstream=None): """ Find the record of the given model specified by self.MODEL_NAME. The record can be looked up in a few ways, depending on which argument is specified (uid or upstream). If both are specified, then the upstream argument will be ignored. Args: uid: The database identifier of the record to fetch, which can be specified either as the primary id (i.e. 8) or the model prefix plus the primary id (i.e. B-8). Could also be the record's name if it has a name attribute (not all models do) and if so will be converted to the record ID. upstream: If set, then the record will be searched on its upstream_identifier attribute. """ # self.attrs will store the actual record's attributes. Initialize value now to empty dict # since it is expected to be set already in self.__setattr__(). self.__dict__["attrs"] = {} # rec_id could be the record's name. Check for that scenario, and convert to record ID if # necessary. if uid: rec_id = self.__class__.replace_name_with_id(uid) rec_json = self._get(rec_id=rec_id) elif upstream: rec_json = self._get(upstream=upstream) else: raise ValueError("Either the 'uid' or 'upstream' parameter must be set.") # Convert None values to empty string for key in rec_json: if rec_json[key] == None: rec_json[key] = "" self.rec_id = rec_json["id"] self.__dict__["attrs"] = rec_json #avoid call to self.__setitem__() for this attr. def __getattr__(self, name): """ Treats database attributes for the record as Python attributes. An attribute is looked up in self.attrs. """ return self.attrs[name] def __setattr__(self, name, value): """ Sets the value of an attribute in self.attrs. """ if name not in self.attrs: return object.__setattr__(self, name, value) object.__setattr__(self, self.attrs[name], value) #self.__dict__["attrs"][name] = value #this works too def __getitem__(self, item): return self.attrs[item] def __setitem__(self, item, value): self.attrs[item] = value def _get(self, rec_id=None, upstream=None): """ Fetches a record by the record's ID or upstream_identifier. Raises: `pulsarpy.models.RecordNotFound`: A record could not be found. """ if rec_id: self.record_url = self.__class__.get_record_url(rec_id) self.debug_logger.debug("GET {} record with ID {}: {}".format(self.__class__.__name__, rec_id, self.record_url)) response = requests.get(url=self.record_url, headers=HEADERS, verify=False) if not response.ok and response.status_code == requests.codes.NOT_FOUND: raise RecordNotFound("Search for {} record with ID '{}' returned no results.".format(self.__class__.__name__, rec_id)) self.write_response_html_to_file(response,"get_bob.html") response.raise_for_status() return response.json() elif upstream: rec_json = self.__class__.find_by({"upstream_identifier": upstream}, require=True) self.record_url = self.__class__.get_record_url(rec_json["id"]) return rec_json @classmethod def get_record_url(self, rec_id): return os.path.join(self.URL, str(rec_id)) @classmethod def log_post(cls, res_json): msg = cls.__name__ + "\t" + str(res_json["id"]) + "\t" name = res_json.get("name") if name: msg += name cls.post_logger.info(msg) @classmethod def replace_name_with_id(cls, name): """ Used to replace a foreign key reference using a name with an ID. Works by searching the record in Pulsar and expects to find exactly one hit. First, will check if the foreign key reference is an integer value and if so, returns that as it is presumed to be the foreign key. Raises: `pulsarpy.elasticsearch_utils.MultipleHitsException`: Multiple hits were returned from the name search. `pulsarpy.models.RecordNotFound`: No results were produced from the name search. """ try: int(name) return name #Already a presumed ID. except ValueError: pass #Not an int, so maybe a combination of MODEL_ABBR and Primary Key, i.e. B-8. if name.split("-")[0] in Meta._MODEL_ABBREVS: return int(name.split("-", 1)[1]) try: result = cls.ES.get_record_by_name(cls.ES_INDEX_NAME, name) if result: return result["id"] except pulsarpy.elasticsearch_utils.MultipleHitsException as e: raise raise RecordNotFound("Name '{}' for model '{}' not found.".format(name, cls.__name__)) @classmethod def add_model_name_to_payload(cls, payload): """ Checks whether the model name in question is in the payload. If not, the entire payload is set as a value of a key by the name of the model. This method is useful when some server-side Rails API calls expect the parameters to include the parameterized model name. For example, server-side endpoints that handle the updating of a biosample record or the creation of a new biosmample record will expect the payload to be of the form:: { "biosample": { "name": "new biosample", "donor": 3, ... } } Args: payload: `dict`. The data to send in an HTTP request. Returns: `dict`. """ if not cls.MODEL_NAME in payload: payload = {cls.MODEL_NAME: payload} return payload @staticmethod def check_boolean_fields(payload): for key in payload: val = payload[key] if type(val) != str: continue val = val.lower() if val in ["yes", "true", "pass"]: val = True payload[key] = val elif val == ["no", "false", "fail"]: val = False payload[key] = val return payload def get_upstream(self): return self.attrs.get(Model.UPSTREAM_ATTR) def abbrev_id(self): """ This method is called when posting to the ENCODE Portal to grab an alias for the record being submitted. The alias here is composed of the record ID in Pulsar (i.e. B-1 for the Biosample with ID 1). However, the record ID is prefexed with a 'p' to designate that this record was submitted from Pulsar. This is used to generate a unique alias considering that we used to uses a different LIMS (Syapse) to submit records. Many of the models in Syapse used the same model prefix as is used in Pulsar, i.e. (B)Biosample and (L)Library. Thus, w/o the 'p' prefix, the same alias could be generated in Pulsar as a previous one used in Syapse. """ return self.PULSAR_LIMS_PREFIX + self.MODEL_ABBR + "-" + str(self.id) def delete(self): """Deletes the record. """ res = requests.delete(url=self.record_url, headers=HEADERS, verify=False) #self.write_response_html_to_file(res,"bob_delete.html") if res.status_code == 204: #No content. Can't render json: return {} return res.json() @classmethod def find_by(cls, payload, require=False): """ Searches the model in question by AND joining the query parameters. Implements a Railsy way of looking for a record using a method by the same name and passing in the query as a dict. as well. Only the first hit is returned, and there is no particular ordering specified in the server-side API method. Args: payload: `dict`. The attributes of a record to restrict the search to. require: `bool`. True means to raise a `pulsarpy.models.RecordNotFound` exception if no record is found. Returns: `dict`: The JSON serialization of the record, if any, found by the API call. `None`: If the API call didnt' return any results. Raises: `pulsarpy.models.RecordNotFound`: No records were found, and the `require` parameter is True. """ if not isinstance(payload, dict): raise ValueError("The 'payload' parameter must be provided a dictionary object.") url = os.path.join(cls.URL, "find_by") payload = {"find_by": payload} cls.debug_logger.debug("Searching Pulsar {} for {}".format(cls.__name__, json.dumps(payload, indent=4))) res = requests.post(url=url, json=payload, headers=HEADERS, verify=False) #cls.write_response_html_to_file(res,"bob.html") res.raise_for_status() res_json = res.json() if res_json: try: res_json = res_json[cls.MODEL_NAME] except KeyError: # Key won't be present if there isn't a serializer for it on the server. pass else: if require: raise RecordNotFound("Can't find any {} records with search criteria: '{}'.".format(cls.__name__, payload)) return res_json @classmethod @classmethod def index(cls): """Fetches all records. Returns: `dict`. The JSON formatted response. Raises: `requests.exceptions.HTTPError`: The status code is not ok. """ res = requests.get(cls.URL, headers=HEADERS, verify=False) res.raise_for_status() return res.json() def patch(self, payload, append_to_arrays=True): """ Patches current record and udpates the current instance's 'attrs' attribute to reflect the new changes. Args: payload - hash. This will be JSON-formatted prior to sending the request. Returns: `dict`. The JSON formatted response. Raises: `requests.exceptions.HTTPError`: The status code is not ok. """ if not isinstance(payload, dict): raise ValueError("The 'payload' parameter must be provided a dictionary object.") payload = self.__class__.set_id_in_fkeys(payload) if append_to_arrays: for key in payload: val = payload[key] if type(val) == list: val.extend(getattr(self, key)) payload[key] = list(set(val)) payload = self.check_boolean_fields(payload) payload = self.__class__.add_model_name_to_payload(payload) self.debug_logger.debug("PATCHING payload {}".format(json.dumps(payload, indent=4))) res = requests.patch(url=self.record_url, json=payload, headers=HEADERS, verify=False) self.write_response_html_to_file(res,"bob.html") res.raise_for_status() json_res = res.json() self.debug_logger.debug("Success") self.attrs = json_res return json_res @classmethod def set_id_in_fkeys(cls, payload): """ Looks for any keys in the payload that end with either _id or _ids, signaling a foreign key field. For each foreign key field, checks whether the value is using the name of the record or the actual primary ID of the record (which may include the model abbreviation, i.e. B-1). If the former case, the name is replaced with the record's primary ID. Args: payload: `dict`. The payload to POST or PATCH. Returns: `dict`. The payload. """ for key in payload: val = payload[key] if not val: continue if key.endswith("_id"): model = getattr(THIS_MODULE, cls.FKEY_MAP[key]) rec_id = model.replace_name_with_id(name=val) payload[key] = rec_id elif key.endswith("_ids"): model = getattr(THIS_MODULE, cls.FKEY_MAP[key]) rec_ids = [] for v in val: rec_id = model.replace_name_with_id(name=v) rec_ids.append(rec_id) payload[key] = rec_ids return payload @classmethod def prepost_hooks(cls, payload): return payload @classmethod def post(cls, payload): """Posts the data to the specified record. Args: payload: `dict`. This will be JSON-formatted prior to sending the request. Returns: `dict`. The JSON formatted response. Raises: `Requests.exceptions.HTTPError`: The status code is not ok. `RecordNotUnique`: The Rails server returned the exception ActiveRecord::RecordNotUnique. """ if not isinstance(payload, dict): raise ValueError("The 'payload' parameter must be provided a dictionary object.") payload = cls.set_id_in_fkeys(payload) payload = cls.check_boolean_fields(payload) payload = cls.add_model_name_to_payload(payload) # Run any pre-post hooks: payload = cls.prepost_hooks(payload) cls.debug_logger.debug("POSTING payload {}".format(json.dumps(payload, indent=4))) res = requests.post(url=cls.URL, json=(payload), headers=HEADERS, verify=False) cls.write_response_html_to_file(res,"bob.html") if not res.ok: cls.log_error(res.text) res_json = res.json() if "exception" in res_json: exc_type = res_json["exception"] if exc_type == "ActiveRecord::RecordNotUnique": raise RecordNotUnique() res.raise_for_status() res = res.json() cls.log_post(res) cls.debug_logger.debug("Success") return res @classmethod def log_error(cls, msg): """ Logs the provided error message to both the error logger and the debug logger logging instances. Args: msg: `str`. The error message to log. """ cls.error_logger.error(msg) cls.debug_logger.debug(msg) @staticmethod def write_response_html_to_file(response,filename): """ An aid in troubleshooting internal application errors, i.e. <Response [500]>, to be mainly beneficial when developing the server-side API. This method will write the response HTML for viewing the error details in the browesr. Args: response: `requests.models.Response` instance. filename: `str`. The output file name. """ fout = open(filename,'w') if not str(response.status_code).startswith("2"): Model.debug_logger.debug(response.text) fout.write(response.text) fout.close()
nathankw/pulsarpy
pulsarpy/models.py
Model.index
python
def index(cls): res = requests.get(cls.URL, headers=HEADERS, verify=False) res.raise_for_status() return res.json()
Fetches all records. Returns: `dict`. The JSON formatted response. Raises: `requests.exceptions.HTTPError`: The status code is not ok.
train
https://github.com/nathankw/pulsarpy/blob/359b040c0f2383b88c0b5548715fefd35f5f634c/pulsarpy/models.py#L500-L511
null
class Model(metaclass=Meta): """ The superclass of all model classes. A model subclass is defined for each Rails model. An instance of a model class represents a record of the given Rails model. Subclasses don't typically define their own init method, but if they do, they need to make a call to 'super' to run the init method defined here as well. Subclasses must be instantiated with the rec_id argument set to a record's ID. A GET will immediately be done and the record's attributes will be stored in the self.attrs `dict`. The record's attributes can be accessed as normal instance attributes (i.e. ``record.name) rather than explicitly indexing the attrs dictionary, thanks to the employment of ``__getattr__()``. Similarly, record attributes can be updated via normal assignment operations, i.e. (``record.name = "bob"``), thanks to employment of ``__setattr__()``. Required Environment Variables: 1) PULSAR_API_URL 2) PULSAR_TOKEN """ #: Most models have an attribute alled upstream_identifier that is used to store the value of the #: record in an "upstream" database that is submitted to, i.e. the ENCODE Portal. Not all models #: have this attribute since not all are used for submission to an upstream portal. UPSTREAM_ATTR = "upstream_identifier" MODEL_ABBR = "" # subclasses define #: Abstract attribute of type `dict` that each subclass should fulfull if it has any foreign keys. #: Each key is a foreign key name and the value is the class name of the model it refers to. FKEY_MAP = {} #: A prefix that can be added in front of record IDs, names, model-record ID. This is useful #: when its necessary to add emphasis that these records exist or came from Pulsar ( i.e. when #: submitting them to an upstream database. PULSAR_LIMS_PREFIX = "p" #: This class adds a file handler, such that all messages sent to it are logged to this #: file in addition to STDOUT. debug_logger = logging.getLogger(p.DEBUG_LOGGER_NAME) # Add debug file handler to debug_logger: Meta.add_file_handler(logger=debug_logger, level=logging.DEBUG, tag="debug") #: A ``logging`` instance with a file handler for logging terse error messages. #: The log file resides locally within the directory specified by the constant #: ``p.LOG_DIR``. Accepts messages >= ``logging.ERROR``. error_logger = logging.getLogger(p.ERROR_LOGGER_NAME) log_level = logging.ERROR error_logger.setLevel(log_level) Meta.add_file_handler(logger=error_logger, level=log_level, tag="error") #: A ``logging`` instance with a file handler for logging successful POST operations. #: The log file resides locally within the directory specified by the constant #: ``p.LOG_DIR``. Accepts messages >= ``logging.INFO``. post_logger = logging.getLogger(p.POST_LOGGER_NAME) log_level = logging.INFO post_logger.setLevel(log_level) Meta.add_file_handler(logger=post_logger, level=log_level, tag="posted") log_msg = "-----------------------------------------------------------------------------------" # Check if neccessary environment variables are set: if not p.URL: debug_logger.debug("Warning: Environment variable PULSAR_API_URL not set.") elif not p.API_TOKEN: debug_logger.debug("Warning: Environment variable PULSAR_TOKEN not set.") debug_logger.debug(log_msg) error_logger.error(log_msg) log_msg = "Connecting to {}".format(p.URL) error_logger.error(log_msg) debug_logger.debug(log_msg) #: Connection to Elasticsearch. Expects that the envrionment variables ES_URL, ES_USER, and #: ES_PW are set, which signifiy the Elasticsearch cluster URL, login username and login #: password, respectively. ES = pulsarpy.elasticsearch_utils.Connection() def __init__(self, uid=None, upstream=None): """ Find the record of the given model specified by self.MODEL_NAME. The record can be looked up in a few ways, depending on which argument is specified (uid or upstream). If both are specified, then the upstream argument will be ignored. Args: uid: The database identifier of the record to fetch, which can be specified either as the primary id (i.e. 8) or the model prefix plus the primary id (i.e. B-8). Could also be the record's name if it has a name attribute (not all models do) and if so will be converted to the record ID. upstream: If set, then the record will be searched on its upstream_identifier attribute. """ # self.attrs will store the actual record's attributes. Initialize value now to empty dict # since it is expected to be set already in self.__setattr__(). self.__dict__["attrs"] = {} # rec_id could be the record's name. Check for that scenario, and convert to record ID if # necessary. if uid: rec_id = self.__class__.replace_name_with_id(uid) rec_json = self._get(rec_id=rec_id) elif upstream: rec_json = self._get(upstream=upstream) else: raise ValueError("Either the 'uid' or 'upstream' parameter must be set.") # Convert None values to empty string for key in rec_json: if rec_json[key] == None: rec_json[key] = "" self.rec_id = rec_json["id"] self.__dict__["attrs"] = rec_json #avoid call to self.__setitem__() for this attr. def __getattr__(self, name): """ Treats database attributes for the record as Python attributes. An attribute is looked up in self.attrs. """ return self.attrs[name] def __setattr__(self, name, value): """ Sets the value of an attribute in self.attrs. """ if name not in self.attrs: return object.__setattr__(self, name, value) object.__setattr__(self, self.attrs[name], value) #self.__dict__["attrs"][name] = value #this works too def __getitem__(self, item): return self.attrs[item] def __setitem__(self, item, value): self.attrs[item] = value def _get(self, rec_id=None, upstream=None): """ Fetches a record by the record's ID or upstream_identifier. Raises: `pulsarpy.models.RecordNotFound`: A record could not be found. """ if rec_id: self.record_url = self.__class__.get_record_url(rec_id) self.debug_logger.debug("GET {} record with ID {}: {}".format(self.__class__.__name__, rec_id, self.record_url)) response = requests.get(url=self.record_url, headers=HEADERS, verify=False) if not response.ok and response.status_code == requests.codes.NOT_FOUND: raise RecordNotFound("Search for {} record with ID '{}' returned no results.".format(self.__class__.__name__, rec_id)) self.write_response_html_to_file(response,"get_bob.html") response.raise_for_status() return response.json() elif upstream: rec_json = self.__class__.find_by({"upstream_identifier": upstream}, require=True) self.record_url = self.__class__.get_record_url(rec_json["id"]) return rec_json @classmethod def get_record_url(self, rec_id): return os.path.join(self.URL, str(rec_id)) @classmethod def log_post(cls, res_json): msg = cls.__name__ + "\t" + str(res_json["id"]) + "\t" name = res_json.get("name") if name: msg += name cls.post_logger.info(msg) @classmethod def replace_name_with_id(cls, name): """ Used to replace a foreign key reference using a name with an ID. Works by searching the record in Pulsar and expects to find exactly one hit. First, will check if the foreign key reference is an integer value and if so, returns that as it is presumed to be the foreign key. Raises: `pulsarpy.elasticsearch_utils.MultipleHitsException`: Multiple hits were returned from the name search. `pulsarpy.models.RecordNotFound`: No results were produced from the name search. """ try: int(name) return name #Already a presumed ID. except ValueError: pass #Not an int, so maybe a combination of MODEL_ABBR and Primary Key, i.e. B-8. if name.split("-")[0] in Meta._MODEL_ABBREVS: return int(name.split("-", 1)[1]) try: result = cls.ES.get_record_by_name(cls.ES_INDEX_NAME, name) if result: return result["id"] except pulsarpy.elasticsearch_utils.MultipleHitsException as e: raise raise RecordNotFound("Name '{}' for model '{}' not found.".format(name, cls.__name__)) @classmethod def add_model_name_to_payload(cls, payload): """ Checks whether the model name in question is in the payload. If not, the entire payload is set as a value of a key by the name of the model. This method is useful when some server-side Rails API calls expect the parameters to include the parameterized model name. For example, server-side endpoints that handle the updating of a biosample record or the creation of a new biosmample record will expect the payload to be of the form:: { "biosample": { "name": "new biosample", "donor": 3, ... } } Args: payload: `dict`. The data to send in an HTTP request. Returns: `dict`. """ if not cls.MODEL_NAME in payload: payload = {cls.MODEL_NAME: payload} return payload @staticmethod def check_boolean_fields(payload): for key in payload: val = payload[key] if type(val) != str: continue val = val.lower() if val in ["yes", "true", "pass"]: val = True payload[key] = val elif val == ["no", "false", "fail"]: val = False payload[key] = val return payload def get_upstream(self): return self.attrs.get(Model.UPSTREAM_ATTR) def abbrev_id(self): """ This method is called when posting to the ENCODE Portal to grab an alias for the record being submitted. The alias here is composed of the record ID in Pulsar (i.e. B-1 for the Biosample with ID 1). However, the record ID is prefexed with a 'p' to designate that this record was submitted from Pulsar. This is used to generate a unique alias considering that we used to uses a different LIMS (Syapse) to submit records. Many of the models in Syapse used the same model prefix as is used in Pulsar, i.e. (B)Biosample and (L)Library. Thus, w/o the 'p' prefix, the same alias could be generated in Pulsar as a previous one used in Syapse. """ return self.PULSAR_LIMS_PREFIX + self.MODEL_ABBR + "-" + str(self.id) def delete(self): """Deletes the record. """ res = requests.delete(url=self.record_url, headers=HEADERS, verify=False) #self.write_response_html_to_file(res,"bob_delete.html") if res.status_code == 204: #No content. Can't render json: return {} return res.json() @classmethod def find_by(cls, payload, require=False): """ Searches the model in question by AND joining the query parameters. Implements a Railsy way of looking for a record using a method by the same name and passing in the query as a dict. as well. Only the first hit is returned, and there is no particular ordering specified in the server-side API method. Args: payload: `dict`. The attributes of a record to restrict the search to. require: `bool`. True means to raise a `pulsarpy.models.RecordNotFound` exception if no record is found. Returns: `dict`: The JSON serialization of the record, if any, found by the API call. `None`: If the API call didnt' return any results. Raises: `pulsarpy.models.RecordNotFound`: No records were found, and the `require` parameter is True. """ if not isinstance(payload, dict): raise ValueError("The 'payload' parameter must be provided a dictionary object.") url = os.path.join(cls.URL, "find_by") payload = {"find_by": payload} cls.debug_logger.debug("Searching Pulsar {} for {}".format(cls.__name__, json.dumps(payload, indent=4))) res = requests.post(url=url, json=payload, headers=HEADERS, verify=False) #cls.write_response_html_to_file(res,"bob.html") res.raise_for_status() res_json = res.json() if res_json: try: res_json = res_json[cls.MODEL_NAME] except KeyError: # Key won't be present if there isn't a serializer for it on the server. pass else: if require: raise RecordNotFound("Can't find any {} records with search criteria: '{}'.".format(cls.__name__, payload)) return res_json @classmethod def find_by_or(cls, payload): """ Searches the model in question by OR joining the query parameters. Implements a Railsy way of looking for a record using a method by the same name and passing in the query as a string (for the OR operator joining to be specified). Only the first hit is returned, and there is not particular ordering specified in the server-side API method. Args: payload: `dict`. The attributes of a record to search for by using OR operator joining for each query parameter. Returns: `dict`: The JSON serialization of the record, if any, found by the API call. `None`: If the API call didnt' return any results. """ if not isinstance(payload, dict): raise ValueError("The 'payload' parameter must be provided a dictionary object.") url = os.path.join(cls.URL, "find_by_or") payload = {"find_by_or": payload} cls.debug_logger.debug("Searching Pulsar {} for {}".format(cls.__name__, json.dumps(payload, indent=4))) res = requests.post(url=url, json=payload, headers=HEADERS, verify=False) cls.write_response_html_to_file(res,"bob.html") if res: try: res = res[cls.MODEL_NAME] except KeyError: # Key won't be present if there isn't a serializer for it on the server. pass return res @classmethod def patch(self, payload, append_to_arrays=True): """ Patches current record and udpates the current instance's 'attrs' attribute to reflect the new changes. Args: payload - hash. This will be JSON-formatted prior to sending the request. Returns: `dict`. The JSON formatted response. Raises: `requests.exceptions.HTTPError`: The status code is not ok. """ if not isinstance(payload, dict): raise ValueError("The 'payload' parameter must be provided a dictionary object.") payload = self.__class__.set_id_in_fkeys(payload) if append_to_arrays: for key in payload: val = payload[key] if type(val) == list: val.extend(getattr(self, key)) payload[key] = list(set(val)) payload = self.check_boolean_fields(payload) payload = self.__class__.add_model_name_to_payload(payload) self.debug_logger.debug("PATCHING payload {}".format(json.dumps(payload, indent=4))) res = requests.patch(url=self.record_url, json=payload, headers=HEADERS, verify=False) self.write_response_html_to_file(res,"bob.html") res.raise_for_status() json_res = res.json() self.debug_logger.debug("Success") self.attrs = json_res return json_res @classmethod def set_id_in_fkeys(cls, payload): """ Looks for any keys in the payload that end with either _id or _ids, signaling a foreign key field. For each foreign key field, checks whether the value is using the name of the record or the actual primary ID of the record (which may include the model abbreviation, i.e. B-1). If the former case, the name is replaced with the record's primary ID. Args: payload: `dict`. The payload to POST or PATCH. Returns: `dict`. The payload. """ for key in payload: val = payload[key] if not val: continue if key.endswith("_id"): model = getattr(THIS_MODULE, cls.FKEY_MAP[key]) rec_id = model.replace_name_with_id(name=val) payload[key] = rec_id elif key.endswith("_ids"): model = getattr(THIS_MODULE, cls.FKEY_MAP[key]) rec_ids = [] for v in val: rec_id = model.replace_name_with_id(name=v) rec_ids.append(rec_id) payload[key] = rec_ids return payload @classmethod def prepost_hooks(cls, payload): return payload @classmethod def post(cls, payload): """Posts the data to the specified record. Args: payload: `dict`. This will be JSON-formatted prior to sending the request. Returns: `dict`. The JSON formatted response. Raises: `Requests.exceptions.HTTPError`: The status code is not ok. `RecordNotUnique`: The Rails server returned the exception ActiveRecord::RecordNotUnique. """ if not isinstance(payload, dict): raise ValueError("The 'payload' parameter must be provided a dictionary object.") payload = cls.set_id_in_fkeys(payload) payload = cls.check_boolean_fields(payload) payload = cls.add_model_name_to_payload(payload) # Run any pre-post hooks: payload = cls.prepost_hooks(payload) cls.debug_logger.debug("POSTING payload {}".format(json.dumps(payload, indent=4))) res = requests.post(url=cls.URL, json=(payload), headers=HEADERS, verify=False) cls.write_response_html_to_file(res,"bob.html") if not res.ok: cls.log_error(res.text) res_json = res.json() if "exception" in res_json: exc_type = res_json["exception"] if exc_type == "ActiveRecord::RecordNotUnique": raise RecordNotUnique() res.raise_for_status() res = res.json() cls.log_post(res) cls.debug_logger.debug("Success") return res @classmethod def log_error(cls, msg): """ Logs the provided error message to both the error logger and the debug logger logging instances. Args: msg: `str`. The error message to log. """ cls.error_logger.error(msg) cls.debug_logger.debug(msg) @staticmethod def write_response_html_to_file(response,filename): """ An aid in troubleshooting internal application errors, i.e. <Response [500]>, to be mainly beneficial when developing the server-side API. This method will write the response HTML for viewing the error details in the browesr. Args: response: `requests.models.Response` instance. filename: `str`. The output file name. """ fout = open(filename,'w') if not str(response.status_code).startswith("2"): Model.debug_logger.debug(response.text) fout.write(response.text) fout.close()
nathankw/pulsarpy
pulsarpy/models.py
Model.patch
python
def patch(self, payload, append_to_arrays=True): if not isinstance(payload, dict): raise ValueError("The 'payload' parameter must be provided a dictionary object.") payload = self.__class__.set_id_in_fkeys(payload) if append_to_arrays: for key in payload: val = payload[key] if type(val) == list: val.extend(getattr(self, key)) payload[key] = list(set(val)) payload = self.check_boolean_fields(payload) payload = self.__class__.add_model_name_to_payload(payload) self.debug_logger.debug("PATCHING payload {}".format(json.dumps(payload, indent=4))) res = requests.patch(url=self.record_url, json=payload, headers=HEADERS, verify=False) self.write_response_html_to_file(res,"bob.html") res.raise_for_status() json_res = res.json() self.debug_logger.debug("Success") self.attrs = json_res return json_res
Patches current record and udpates the current instance's 'attrs' attribute to reflect the new changes. Args: payload - hash. This will be JSON-formatted prior to sending the request. Returns: `dict`. The JSON formatted response. Raises: `requests.exceptions.HTTPError`: The status code is not ok.
train
https://github.com/nathankw/pulsarpy/blob/359b040c0f2383b88c0b5548715fefd35f5f634c/pulsarpy/models.py#L513-L545
[ "def check_boolean_fields(payload):\n for key in payload:\n val = payload[key]\n if type(val) != str:\n continue\n val = val.lower()\n if val in [\"yes\", \"true\", \"pass\"]:\n val = True\n payload[key] = val\n elif val == [\"no\", \"false\", ...
class Model(metaclass=Meta): """ The superclass of all model classes. A model subclass is defined for each Rails model. An instance of a model class represents a record of the given Rails model. Subclasses don't typically define their own init method, but if they do, they need to make a call to 'super' to run the init method defined here as well. Subclasses must be instantiated with the rec_id argument set to a record's ID. A GET will immediately be done and the record's attributes will be stored in the self.attrs `dict`. The record's attributes can be accessed as normal instance attributes (i.e. ``record.name) rather than explicitly indexing the attrs dictionary, thanks to the employment of ``__getattr__()``. Similarly, record attributes can be updated via normal assignment operations, i.e. (``record.name = "bob"``), thanks to employment of ``__setattr__()``. Required Environment Variables: 1) PULSAR_API_URL 2) PULSAR_TOKEN """ #: Most models have an attribute alled upstream_identifier that is used to store the value of the #: record in an "upstream" database that is submitted to, i.e. the ENCODE Portal. Not all models #: have this attribute since not all are used for submission to an upstream portal. UPSTREAM_ATTR = "upstream_identifier" MODEL_ABBR = "" # subclasses define #: Abstract attribute of type `dict` that each subclass should fulfull if it has any foreign keys. #: Each key is a foreign key name and the value is the class name of the model it refers to. FKEY_MAP = {} #: A prefix that can be added in front of record IDs, names, model-record ID. This is useful #: when its necessary to add emphasis that these records exist or came from Pulsar ( i.e. when #: submitting them to an upstream database. PULSAR_LIMS_PREFIX = "p" #: This class adds a file handler, such that all messages sent to it are logged to this #: file in addition to STDOUT. debug_logger = logging.getLogger(p.DEBUG_LOGGER_NAME) # Add debug file handler to debug_logger: Meta.add_file_handler(logger=debug_logger, level=logging.DEBUG, tag="debug") #: A ``logging`` instance with a file handler for logging terse error messages. #: The log file resides locally within the directory specified by the constant #: ``p.LOG_DIR``. Accepts messages >= ``logging.ERROR``. error_logger = logging.getLogger(p.ERROR_LOGGER_NAME) log_level = logging.ERROR error_logger.setLevel(log_level) Meta.add_file_handler(logger=error_logger, level=log_level, tag="error") #: A ``logging`` instance with a file handler for logging successful POST operations. #: The log file resides locally within the directory specified by the constant #: ``p.LOG_DIR``. Accepts messages >= ``logging.INFO``. post_logger = logging.getLogger(p.POST_LOGGER_NAME) log_level = logging.INFO post_logger.setLevel(log_level) Meta.add_file_handler(logger=post_logger, level=log_level, tag="posted") log_msg = "-----------------------------------------------------------------------------------" # Check if neccessary environment variables are set: if not p.URL: debug_logger.debug("Warning: Environment variable PULSAR_API_URL not set.") elif not p.API_TOKEN: debug_logger.debug("Warning: Environment variable PULSAR_TOKEN not set.") debug_logger.debug(log_msg) error_logger.error(log_msg) log_msg = "Connecting to {}".format(p.URL) error_logger.error(log_msg) debug_logger.debug(log_msg) #: Connection to Elasticsearch. Expects that the envrionment variables ES_URL, ES_USER, and #: ES_PW are set, which signifiy the Elasticsearch cluster URL, login username and login #: password, respectively. ES = pulsarpy.elasticsearch_utils.Connection() def __init__(self, uid=None, upstream=None): """ Find the record of the given model specified by self.MODEL_NAME. The record can be looked up in a few ways, depending on which argument is specified (uid or upstream). If both are specified, then the upstream argument will be ignored. Args: uid: The database identifier of the record to fetch, which can be specified either as the primary id (i.e. 8) or the model prefix plus the primary id (i.e. B-8). Could also be the record's name if it has a name attribute (not all models do) and if so will be converted to the record ID. upstream: If set, then the record will be searched on its upstream_identifier attribute. """ # self.attrs will store the actual record's attributes. Initialize value now to empty dict # since it is expected to be set already in self.__setattr__(). self.__dict__["attrs"] = {} # rec_id could be the record's name. Check for that scenario, and convert to record ID if # necessary. if uid: rec_id = self.__class__.replace_name_with_id(uid) rec_json = self._get(rec_id=rec_id) elif upstream: rec_json = self._get(upstream=upstream) else: raise ValueError("Either the 'uid' or 'upstream' parameter must be set.") # Convert None values to empty string for key in rec_json: if rec_json[key] == None: rec_json[key] = "" self.rec_id = rec_json["id"] self.__dict__["attrs"] = rec_json #avoid call to self.__setitem__() for this attr. def __getattr__(self, name): """ Treats database attributes for the record as Python attributes. An attribute is looked up in self.attrs. """ return self.attrs[name] def __setattr__(self, name, value): """ Sets the value of an attribute in self.attrs. """ if name not in self.attrs: return object.__setattr__(self, name, value) object.__setattr__(self, self.attrs[name], value) #self.__dict__["attrs"][name] = value #this works too def __getitem__(self, item): return self.attrs[item] def __setitem__(self, item, value): self.attrs[item] = value def _get(self, rec_id=None, upstream=None): """ Fetches a record by the record's ID or upstream_identifier. Raises: `pulsarpy.models.RecordNotFound`: A record could not be found. """ if rec_id: self.record_url = self.__class__.get_record_url(rec_id) self.debug_logger.debug("GET {} record with ID {}: {}".format(self.__class__.__name__, rec_id, self.record_url)) response = requests.get(url=self.record_url, headers=HEADERS, verify=False) if not response.ok and response.status_code == requests.codes.NOT_FOUND: raise RecordNotFound("Search for {} record with ID '{}' returned no results.".format(self.__class__.__name__, rec_id)) self.write_response_html_to_file(response,"get_bob.html") response.raise_for_status() return response.json() elif upstream: rec_json = self.__class__.find_by({"upstream_identifier": upstream}, require=True) self.record_url = self.__class__.get_record_url(rec_json["id"]) return rec_json @classmethod def get_record_url(self, rec_id): return os.path.join(self.URL, str(rec_id)) @classmethod def log_post(cls, res_json): msg = cls.__name__ + "\t" + str(res_json["id"]) + "\t" name = res_json.get("name") if name: msg += name cls.post_logger.info(msg) @classmethod def replace_name_with_id(cls, name): """ Used to replace a foreign key reference using a name with an ID. Works by searching the record in Pulsar and expects to find exactly one hit. First, will check if the foreign key reference is an integer value and if so, returns that as it is presumed to be the foreign key. Raises: `pulsarpy.elasticsearch_utils.MultipleHitsException`: Multiple hits were returned from the name search. `pulsarpy.models.RecordNotFound`: No results were produced from the name search. """ try: int(name) return name #Already a presumed ID. except ValueError: pass #Not an int, so maybe a combination of MODEL_ABBR and Primary Key, i.e. B-8. if name.split("-")[0] in Meta._MODEL_ABBREVS: return int(name.split("-", 1)[1]) try: result = cls.ES.get_record_by_name(cls.ES_INDEX_NAME, name) if result: return result["id"] except pulsarpy.elasticsearch_utils.MultipleHitsException as e: raise raise RecordNotFound("Name '{}' for model '{}' not found.".format(name, cls.__name__)) @classmethod def add_model_name_to_payload(cls, payload): """ Checks whether the model name in question is in the payload. If not, the entire payload is set as a value of a key by the name of the model. This method is useful when some server-side Rails API calls expect the parameters to include the parameterized model name. For example, server-side endpoints that handle the updating of a biosample record or the creation of a new biosmample record will expect the payload to be of the form:: { "biosample": { "name": "new biosample", "donor": 3, ... } } Args: payload: `dict`. The data to send in an HTTP request. Returns: `dict`. """ if not cls.MODEL_NAME in payload: payload = {cls.MODEL_NAME: payload} return payload @staticmethod def check_boolean_fields(payload): for key in payload: val = payload[key] if type(val) != str: continue val = val.lower() if val in ["yes", "true", "pass"]: val = True payload[key] = val elif val == ["no", "false", "fail"]: val = False payload[key] = val return payload def get_upstream(self): return self.attrs.get(Model.UPSTREAM_ATTR) def abbrev_id(self): """ This method is called when posting to the ENCODE Portal to grab an alias for the record being submitted. The alias here is composed of the record ID in Pulsar (i.e. B-1 for the Biosample with ID 1). However, the record ID is prefexed with a 'p' to designate that this record was submitted from Pulsar. This is used to generate a unique alias considering that we used to uses a different LIMS (Syapse) to submit records. Many of the models in Syapse used the same model prefix as is used in Pulsar, i.e. (B)Biosample and (L)Library. Thus, w/o the 'p' prefix, the same alias could be generated in Pulsar as a previous one used in Syapse. """ return self.PULSAR_LIMS_PREFIX + self.MODEL_ABBR + "-" + str(self.id) def delete(self): """Deletes the record. """ res = requests.delete(url=self.record_url, headers=HEADERS, verify=False) #self.write_response_html_to_file(res,"bob_delete.html") if res.status_code == 204: #No content. Can't render json: return {} return res.json() @classmethod def find_by(cls, payload, require=False): """ Searches the model in question by AND joining the query parameters. Implements a Railsy way of looking for a record using a method by the same name and passing in the query as a dict. as well. Only the first hit is returned, and there is no particular ordering specified in the server-side API method. Args: payload: `dict`. The attributes of a record to restrict the search to. require: `bool`. True means to raise a `pulsarpy.models.RecordNotFound` exception if no record is found. Returns: `dict`: The JSON serialization of the record, if any, found by the API call. `None`: If the API call didnt' return any results. Raises: `pulsarpy.models.RecordNotFound`: No records were found, and the `require` parameter is True. """ if not isinstance(payload, dict): raise ValueError("The 'payload' parameter must be provided a dictionary object.") url = os.path.join(cls.URL, "find_by") payload = {"find_by": payload} cls.debug_logger.debug("Searching Pulsar {} for {}".format(cls.__name__, json.dumps(payload, indent=4))) res = requests.post(url=url, json=payload, headers=HEADERS, verify=False) #cls.write_response_html_to_file(res,"bob.html") res.raise_for_status() res_json = res.json() if res_json: try: res_json = res_json[cls.MODEL_NAME] except KeyError: # Key won't be present if there isn't a serializer for it on the server. pass else: if require: raise RecordNotFound("Can't find any {} records with search criteria: '{}'.".format(cls.__name__, payload)) return res_json @classmethod def find_by_or(cls, payload): """ Searches the model in question by OR joining the query parameters. Implements a Railsy way of looking for a record using a method by the same name and passing in the query as a string (for the OR operator joining to be specified). Only the first hit is returned, and there is not particular ordering specified in the server-side API method. Args: payload: `dict`. The attributes of a record to search for by using OR operator joining for each query parameter. Returns: `dict`: The JSON serialization of the record, if any, found by the API call. `None`: If the API call didnt' return any results. """ if not isinstance(payload, dict): raise ValueError("The 'payload' parameter must be provided a dictionary object.") url = os.path.join(cls.URL, "find_by_or") payload = {"find_by_or": payload} cls.debug_logger.debug("Searching Pulsar {} for {}".format(cls.__name__, json.dumps(payload, indent=4))) res = requests.post(url=url, json=payload, headers=HEADERS, verify=False) cls.write_response_html_to_file(res,"bob.html") if res: try: res = res[cls.MODEL_NAME] except KeyError: # Key won't be present if there isn't a serializer for it on the server. pass return res @classmethod def index(cls): """Fetches all records. Returns: `dict`. The JSON formatted response. Raises: `requests.exceptions.HTTPError`: The status code is not ok. """ res = requests.get(cls.URL, headers=HEADERS, verify=False) res.raise_for_status() return res.json() @classmethod def set_id_in_fkeys(cls, payload): """ Looks for any keys in the payload that end with either _id or _ids, signaling a foreign key field. For each foreign key field, checks whether the value is using the name of the record or the actual primary ID of the record (which may include the model abbreviation, i.e. B-1). If the former case, the name is replaced with the record's primary ID. Args: payload: `dict`. The payload to POST or PATCH. Returns: `dict`. The payload. """ for key in payload: val = payload[key] if not val: continue if key.endswith("_id"): model = getattr(THIS_MODULE, cls.FKEY_MAP[key]) rec_id = model.replace_name_with_id(name=val) payload[key] = rec_id elif key.endswith("_ids"): model = getattr(THIS_MODULE, cls.FKEY_MAP[key]) rec_ids = [] for v in val: rec_id = model.replace_name_with_id(name=v) rec_ids.append(rec_id) payload[key] = rec_ids return payload @classmethod def prepost_hooks(cls, payload): return payload @classmethod def post(cls, payload): """Posts the data to the specified record. Args: payload: `dict`. This will be JSON-formatted prior to sending the request. Returns: `dict`. The JSON formatted response. Raises: `Requests.exceptions.HTTPError`: The status code is not ok. `RecordNotUnique`: The Rails server returned the exception ActiveRecord::RecordNotUnique. """ if not isinstance(payload, dict): raise ValueError("The 'payload' parameter must be provided a dictionary object.") payload = cls.set_id_in_fkeys(payload) payload = cls.check_boolean_fields(payload) payload = cls.add_model_name_to_payload(payload) # Run any pre-post hooks: payload = cls.prepost_hooks(payload) cls.debug_logger.debug("POSTING payload {}".format(json.dumps(payload, indent=4))) res = requests.post(url=cls.URL, json=(payload), headers=HEADERS, verify=False) cls.write_response_html_to_file(res,"bob.html") if not res.ok: cls.log_error(res.text) res_json = res.json() if "exception" in res_json: exc_type = res_json["exception"] if exc_type == "ActiveRecord::RecordNotUnique": raise RecordNotUnique() res.raise_for_status() res = res.json() cls.log_post(res) cls.debug_logger.debug("Success") return res @classmethod def log_error(cls, msg): """ Logs the provided error message to both the error logger and the debug logger logging instances. Args: msg: `str`. The error message to log. """ cls.error_logger.error(msg) cls.debug_logger.debug(msg) @staticmethod def write_response_html_to_file(response,filename): """ An aid in troubleshooting internal application errors, i.e. <Response [500]>, to be mainly beneficial when developing the server-side API. This method will write the response HTML for viewing the error details in the browesr. Args: response: `requests.models.Response` instance. filename: `str`. The output file name. """ fout = open(filename,'w') if not str(response.status_code).startswith("2"): Model.debug_logger.debug(response.text) fout.write(response.text) fout.close()
nathankw/pulsarpy
pulsarpy/models.py
Model.set_id_in_fkeys
python
def set_id_in_fkeys(cls, payload): for key in payload: val = payload[key] if not val: continue if key.endswith("_id"): model = getattr(THIS_MODULE, cls.FKEY_MAP[key]) rec_id = model.replace_name_with_id(name=val) payload[key] = rec_id elif key.endswith("_ids"): model = getattr(THIS_MODULE, cls.FKEY_MAP[key]) rec_ids = [] for v in val: rec_id = model.replace_name_with_id(name=v) rec_ids.append(rec_id) payload[key] = rec_ids return payload
Looks for any keys in the payload that end with either _id or _ids, signaling a foreign key field. For each foreign key field, checks whether the value is using the name of the record or the actual primary ID of the record (which may include the model abbreviation, i.e. B-1). If the former case, the name is replaced with the record's primary ID. Args: payload: `dict`. The payload to POST or PATCH. Returns: `dict`. The payload.
train
https://github.com/nathankw/pulsarpy/blob/359b040c0f2383b88c0b5548715fefd35f5f634c/pulsarpy/models.py#L548-L577
null
class Model(metaclass=Meta): """ The superclass of all model classes. A model subclass is defined for each Rails model. An instance of a model class represents a record of the given Rails model. Subclasses don't typically define their own init method, but if they do, they need to make a call to 'super' to run the init method defined here as well. Subclasses must be instantiated with the rec_id argument set to a record's ID. A GET will immediately be done and the record's attributes will be stored in the self.attrs `dict`. The record's attributes can be accessed as normal instance attributes (i.e. ``record.name) rather than explicitly indexing the attrs dictionary, thanks to the employment of ``__getattr__()``. Similarly, record attributes can be updated via normal assignment operations, i.e. (``record.name = "bob"``), thanks to employment of ``__setattr__()``. Required Environment Variables: 1) PULSAR_API_URL 2) PULSAR_TOKEN """ #: Most models have an attribute alled upstream_identifier that is used to store the value of the #: record in an "upstream" database that is submitted to, i.e. the ENCODE Portal. Not all models #: have this attribute since not all are used for submission to an upstream portal. UPSTREAM_ATTR = "upstream_identifier" MODEL_ABBR = "" # subclasses define #: Abstract attribute of type `dict` that each subclass should fulfull if it has any foreign keys. #: Each key is a foreign key name and the value is the class name of the model it refers to. FKEY_MAP = {} #: A prefix that can be added in front of record IDs, names, model-record ID. This is useful #: when its necessary to add emphasis that these records exist or came from Pulsar ( i.e. when #: submitting them to an upstream database. PULSAR_LIMS_PREFIX = "p" #: This class adds a file handler, such that all messages sent to it are logged to this #: file in addition to STDOUT. debug_logger = logging.getLogger(p.DEBUG_LOGGER_NAME) # Add debug file handler to debug_logger: Meta.add_file_handler(logger=debug_logger, level=logging.DEBUG, tag="debug") #: A ``logging`` instance with a file handler for logging terse error messages. #: The log file resides locally within the directory specified by the constant #: ``p.LOG_DIR``. Accepts messages >= ``logging.ERROR``. error_logger = logging.getLogger(p.ERROR_LOGGER_NAME) log_level = logging.ERROR error_logger.setLevel(log_level) Meta.add_file_handler(logger=error_logger, level=log_level, tag="error") #: A ``logging`` instance with a file handler for logging successful POST operations. #: The log file resides locally within the directory specified by the constant #: ``p.LOG_DIR``. Accepts messages >= ``logging.INFO``. post_logger = logging.getLogger(p.POST_LOGGER_NAME) log_level = logging.INFO post_logger.setLevel(log_level) Meta.add_file_handler(logger=post_logger, level=log_level, tag="posted") log_msg = "-----------------------------------------------------------------------------------" # Check if neccessary environment variables are set: if not p.URL: debug_logger.debug("Warning: Environment variable PULSAR_API_URL not set.") elif not p.API_TOKEN: debug_logger.debug("Warning: Environment variable PULSAR_TOKEN not set.") debug_logger.debug(log_msg) error_logger.error(log_msg) log_msg = "Connecting to {}".format(p.URL) error_logger.error(log_msg) debug_logger.debug(log_msg) #: Connection to Elasticsearch. Expects that the envrionment variables ES_URL, ES_USER, and #: ES_PW are set, which signifiy the Elasticsearch cluster URL, login username and login #: password, respectively. ES = pulsarpy.elasticsearch_utils.Connection() def __init__(self, uid=None, upstream=None): """ Find the record of the given model specified by self.MODEL_NAME. The record can be looked up in a few ways, depending on which argument is specified (uid or upstream). If both are specified, then the upstream argument will be ignored. Args: uid: The database identifier of the record to fetch, which can be specified either as the primary id (i.e. 8) or the model prefix plus the primary id (i.e. B-8). Could also be the record's name if it has a name attribute (not all models do) and if so will be converted to the record ID. upstream: If set, then the record will be searched on its upstream_identifier attribute. """ # self.attrs will store the actual record's attributes. Initialize value now to empty dict # since it is expected to be set already in self.__setattr__(). self.__dict__["attrs"] = {} # rec_id could be the record's name. Check for that scenario, and convert to record ID if # necessary. if uid: rec_id = self.__class__.replace_name_with_id(uid) rec_json = self._get(rec_id=rec_id) elif upstream: rec_json = self._get(upstream=upstream) else: raise ValueError("Either the 'uid' or 'upstream' parameter must be set.") # Convert None values to empty string for key in rec_json: if rec_json[key] == None: rec_json[key] = "" self.rec_id = rec_json["id"] self.__dict__["attrs"] = rec_json #avoid call to self.__setitem__() for this attr. def __getattr__(self, name): """ Treats database attributes for the record as Python attributes. An attribute is looked up in self.attrs. """ return self.attrs[name] def __setattr__(self, name, value): """ Sets the value of an attribute in self.attrs. """ if name not in self.attrs: return object.__setattr__(self, name, value) object.__setattr__(self, self.attrs[name], value) #self.__dict__["attrs"][name] = value #this works too def __getitem__(self, item): return self.attrs[item] def __setitem__(self, item, value): self.attrs[item] = value def _get(self, rec_id=None, upstream=None): """ Fetches a record by the record's ID or upstream_identifier. Raises: `pulsarpy.models.RecordNotFound`: A record could not be found. """ if rec_id: self.record_url = self.__class__.get_record_url(rec_id) self.debug_logger.debug("GET {} record with ID {}: {}".format(self.__class__.__name__, rec_id, self.record_url)) response = requests.get(url=self.record_url, headers=HEADERS, verify=False) if not response.ok and response.status_code == requests.codes.NOT_FOUND: raise RecordNotFound("Search for {} record with ID '{}' returned no results.".format(self.__class__.__name__, rec_id)) self.write_response_html_to_file(response,"get_bob.html") response.raise_for_status() return response.json() elif upstream: rec_json = self.__class__.find_by({"upstream_identifier": upstream}, require=True) self.record_url = self.__class__.get_record_url(rec_json["id"]) return rec_json @classmethod def get_record_url(self, rec_id): return os.path.join(self.URL, str(rec_id)) @classmethod def log_post(cls, res_json): msg = cls.__name__ + "\t" + str(res_json["id"]) + "\t" name = res_json.get("name") if name: msg += name cls.post_logger.info(msg) @classmethod def replace_name_with_id(cls, name): """ Used to replace a foreign key reference using a name with an ID. Works by searching the record in Pulsar and expects to find exactly one hit. First, will check if the foreign key reference is an integer value and if so, returns that as it is presumed to be the foreign key. Raises: `pulsarpy.elasticsearch_utils.MultipleHitsException`: Multiple hits were returned from the name search. `pulsarpy.models.RecordNotFound`: No results were produced from the name search. """ try: int(name) return name #Already a presumed ID. except ValueError: pass #Not an int, so maybe a combination of MODEL_ABBR and Primary Key, i.e. B-8. if name.split("-")[0] in Meta._MODEL_ABBREVS: return int(name.split("-", 1)[1]) try: result = cls.ES.get_record_by_name(cls.ES_INDEX_NAME, name) if result: return result["id"] except pulsarpy.elasticsearch_utils.MultipleHitsException as e: raise raise RecordNotFound("Name '{}' for model '{}' not found.".format(name, cls.__name__)) @classmethod def add_model_name_to_payload(cls, payload): """ Checks whether the model name in question is in the payload. If not, the entire payload is set as a value of a key by the name of the model. This method is useful when some server-side Rails API calls expect the parameters to include the parameterized model name. For example, server-side endpoints that handle the updating of a biosample record or the creation of a new biosmample record will expect the payload to be of the form:: { "biosample": { "name": "new biosample", "donor": 3, ... } } Args: payload: `dict`. The data to send in an HTTP request. Returns: `dict`. """ if not cls.MODEL_NAME in payload: payload = {cls.MODEL_NAME: payload} return payload @staticmethod def check_boolean_fields(payload): for key in payload: val = payload[key] if type(val) != str: continue val = val.lower() if val in ["yes", "true", "pass"]: val = True payload[key] = val elif val == ["no", "false", "fail"]: val = False payload[key] = val return payload def get_upstream(self): return self.attrs.get(Model.UPSTREAM_ATTR) def abbrev_id(self): """ This method is called when posting to the ENCODE Portal to grab an alias for the record being submitted. The alias here is composed of the record ID in Pulsar (i.e. B-1 for the Biosample with ID 1). However, the record ID is prefexed with a 'p' to designate that this record was submitted from Pulsar. This is used to generate a unique alias considering that we used to uses a different LIMS (Syapse) to submit records. Many of the models in Syapse used the same model prefix as is used in Pulsar, i.e. (B)Biosample and (L)Library. Thus, w/o the 'p' prefix, the same alias could be generated in Pulsar as a previous one used in Syapse. """ return self.PULSAR_LIMS_PREFIX + self.MODEL_ABBR + "-" + str(self.id) def delete(self): """Deletes the record. """ res = requests.delete(url=self.record_url, headers=HEADERS, verify=False) #self.write_response_html_to_file(res,"bob_delete.html") if res.status_code == 204: #No content. Can't render json: return {} return res.json() @classmethod def find_by(cls, payload, require=False): """ Searches the model in question by AND joining the query parameters. Implements a Railsy way of looking for a record using a method by the same name and passing in the query as a dict. as well. Only the first hit is returned, and there is no particular ordering specified in the server-side API method. Args: payload: `dict`. The attributes of a record to restrict the search to. require: `bool`. True means to raise a `pulsarpy.models.RecordNotFound` exception if no record is found. Returns: `dict`: The JSON serialization of the record, if any, found by the API call. `None`: If the API call didnt' return any results. Raises: `pulsarpy.models.RecordNotFound`: No records were found, and the `require` parameter is True. """ if not isinstance(payload, dict): raise ValueError("The 'payload' parameter must be provided a dictionary object.") url = os.path.join(cls.URL, "find_by") payload = {"find_by": payload} cls.debug_logger.debug("Searching Pulsar {} for {}".format(cls.__name__, json.dumps(payload, indent=4))) res = requests.post(url=url, json=payload, headers=HEADERS, verify=False) #cls.write_response_html_to_file(res,"bob.html") res.raise_for_status() res_json = res.json() if res_json: try: res_json = res_json[cls.MODEL_NAME] except KeyError: # Key won't be present if there isn't a serializer for it on the server. pass else: if require: raise RecordNotFound("Can't find any {} records with search criteria: '{}'.".format(cls.__name__, payload)) return res_json @classmethod def find_by_or(cls, payload): """ Searches the model in question by OR joining the query parameters. Implements a Railsy way of looking for a record using a method by the same name and passing in the query as a string (for the OR operator joining to be specified). Only the first hit is returned, and there is not particular ordering specified in the server-side API method. Args: payload: `dict`. The attributes of a record to search for by using OR operator joining for each query parameter. Returns: `dict`: The JSON serialization of the record, if any, found by the API call. `None`: If the API call didnt' return any results. """ if not isinstance(payload, dict): raise ValueError("The 'payload' parameter must be provided a dictionary object.") url = os.path.join(cls.URL, "find_by_or") payload = {"find_by_or": payload} cls.debug_logger.debug("Searching Pulsar {} for {}".format(cls.__name__, json.dumps(payload, indent=4))) res = requests.post(url=url, json=payload, headers=HEADERS, verify=False) cls.write_response_html_to_file(res,"bob.html") if res: try: res = res[cls.MODEL_NAME] except KeyError: # Key won't be present if there isn't a serializer for it on the server. pass return res @classmethod def index(cls): """Fetches all records. Returns: `dict`. The JSON formatted response. Raises: `requests.exceptions.HTTPError`: The status code is not ok. """ res = requests.get(cls.URL, headers=HEADERS, verify=False) res.raise_for_status() return res.json() def patch(self, payload, append_to_arrays=True): """ Patches current record and udpates the current instance's 'attrs' attribute to reflect the new changes. Args: payload - hash. This will be JSON-formatted prior to sending the request. Returns: `dict`. The JSON formatted response. Raises: `requests.exceptions.HTTPError`: The status code is not ok. """ if not isinstance(payload, dict): raise ValueError("The 'payload' parameter must be provided a dictionary object.") payload = self.__class__.set_id_in_fkeys(payload) if append_to_arrays: for key in payload: val = payload[key] if type(val) == list: val.extend(getattr(self, key)) payload[key] = list(set(val)) payload = self.check_boolean_fields(payload) payload = self.__class__.add_model_name_to_payload(payload) self.debug_logger.debug("PATCHING payload {}".format(json.dumps(payload, indent=4))) res = requests.patch(url=self.record_url, json=payload, headers=HEADERS, verify=False) self.write_response_html_to_file(res,"bob.html") res.raise_for_status() json_res = res.json() self.debug_logger.debug("Success") self.attrs = json_res return json_res @classmethod @classmethod def prepost_hooks(cls, payload): return payload @classmethod def post(cls, payload): """Posts the data to the specified record. Args: payload: `dict`. This will be JSON-formatted prior to sending the request. Returns: `dict`. The JSON formatted response. Raises: `Requests.exceptions.HTTPError`: The status code is not ok. `RecordNotUnique`: The Rails server returned the exception ActiveRecord::RecordNotUnique. """ if not isinstance(payload, dict): raise ValueError("The 'payload' parameter must be provided a dictionary object.") payload = cls.set_id_in_fkeys(payload) payload = cls.check_boolean_fields(payload) payload = cls.add_model_name_to_payload(payload) # Run any pre-post hooks: payload = cls.prepost_hooks(payload) cls.debug_logger.debug("POSTING payload {}".format(json.dumps(payload, indent=4))) res = requests.post(url=cls.URL, json=(payload), headers=HEADERS, verify=False) cls.write_response_html_to_file(res,"bob.html") if not res.ok: cls.log_error(res.text) res_json = res.json() if "exception" in res_json: exc_type = res_json["exception"] if exc_type == "ActiveRecord::RecordNotUnique": raise RecordNotUnique() res.raise_for_status() res = res.json() cls.log_post(res) cls.debug_logger.debug("Success") return res @classmethod def log_error(cls, msg): """ Logs the provided error message to both the error logger and the debug logger logging instances. Args: msg: `str`. The error message to log. """ cls.error_logger.error(msg) cls.debug_logger.debug(msg) @staticmethod def write_response_html_to_file(response,filename): """ An aid in troubleshooting internal application errors, i.e. <Response [500]>, to be mainly beneficial when developing the server-side API. This method will write the response HTML for viewing the error details in the browesr. Args: response: `requests.models.Response` instance. filename: `str`. The output file name. """ fout = open(filename,'w') if not str(response.status_code).startswith("2"): Model.debug_logger.debug(response.text) fout.write(response.text) fout.close()
nathankw/pulsarpy
pulsarpy/models.py
Model.post
python
def post(cls, payload): if not isinstance(payload, dict): raise ValueError("The 'payload' parameter must be provided a dictionary object.") payload = cls.set_id_in_fkeys(payload) payload = cls.check_boolean_fields(payload) payload = cls.add_model_name_to_payload(payload) # Run any pre-post hooks: payload = cls.prepost_hooks(payload) cls.debug_logger.debug("POSTING payload {}".format(json.dumps(payload, indent=4))) res = requests.post(url=cls.URL, json=(payload), headers=HEADERS, verify=False) cls.write_response_html_to_file(res,"bob.html") if not res.ok: cls.log_error(res.text) res_json = res.json() if "exception" in res_json: exc_type = res_json["exception"] if exc_type == "ActiveRecord::RecordNotUnique": raise RecordNotUnique() res.raise_for_status() res = res.json() cls.log_post(res) cls.debug_logger.debug("Success") return res
Posts the data to the specified record. Args: payload: `dict`. This will be JSON-formatted prior to sending the request. Returns: `dict`. The JSON formatted response. Raises: `Requests.exceptions.HTTPError`: The status code is not ok. `RecordNotUnique`: The Rails server returned the exception ActiveRecord::RecordNotUnique.
train
https://github.com/nathankw/pulsarpy/blob/359b040c0f2383b88c0b5548715fefd35f5f634c/pulsarpy/models.py#L585-L619
[ "def log_post(cls, res_json):\n msg = cls.__name__ + \"\\t\" + str(res_json[\"id\"]) + \"\\t\"\n name = res_json.get(\"name\")\n if name:\n msg += name\n cls.post_logger.info(msg)\n", "def add_model_name_to_payload(cls, payload):\n \"\"\"\n Checks whether the model name in question is in ...
class Model(metaclass=Meta): """ The superclass of all model classes. A model subclass is defined for each Rails model. An instance of a model class represents a record of the given Rails model. Subclasses don't typically define their own init method, but if they do, they need to make a call to 'super' to run the init method defined here as well. Subclasses must be instantiated with the rec_id argument set to a record's ID. A GET will immediately be done and the record's attributes will be stored in the self.attrs `dict`. The record's attributes can be accessed as normal instance attributes (i.e. ``record.name) rather than explicitly indexing the attrs dictionary, thanks to the employment of ``__getattr__()``. Similarly, record attributes can be updated via normal assignment operations, i.e. (``record.name = "bob"``), thanks to employment of ``__setattr__()``. Required Environment Variables: 1) PULSAR_API_URL 2) PULSAR_TOKEN """ #: Most models have an attribute alled upstream_identifier that is used to store the value of the #: record in an "upstream" database that is submitted to, i.e. the ENCODE Portal. Not all models #: have this attribute since not all are used for submission to an upstream portal. UPSTREAM_ATTR = "upstream_identifier" MODEL_ABBR = "" # subclasses define #: Abstract attribute of type `dict` that each subclass should fulfull if it has any foreign keys. #: Each key is a foreign key name and the value is the class name of the model it refers to. FKEY_MAP = {} #: A prefix that can be added in front of record IDs, names, model-record ID. This is useful #: when its necessary to add emphasis that these records exist or came from Pulsar ( i.e. when #: submitting them to an upstream database. PULSAR_LIMS_PREFIX = "p" #: This class adds a file handler, such that all messages sent to it are logged to this #: file in addition to STDOUT. debug_logger = logging.getLogger(p.DEBUG_LOGGER_NAME) # Add debug file handler to debug_logger: Meta.add_file_handler(logger=debug_logger, level=logging.DEBUG, tag="debug") #: A ``logging`` instance with a file handler for logging terse error messages. #: The log file resides locally within the directory specified by the constant #: ``p.LOG_DIR``. Accepts messages >= ``logging.ERROR``. error_logger = logging.getLogger(p.ERROR_LOGGER_NAME) log_level = logging.ERROR error_logger.setLevel(log_level) Meta.add_file_handler(logger=error_logger, level=log_level, tag="error") #: A ``logging`` instance with a file handler for logging successful POST operations. #: The log file resides locally within the directory specified by the constant #: ``p.LOG_DIR``. Accepts messages >= ``logging.INFO``. post_logger = logging.getLogger(p.POST_LOGGER_NAME) log_level = logging.INFO post_logger.setLevel(log_level) Meta.add_file_handler(logger=post_logger, level=log_level, tag="posted") log_msg = "-----------------------------------------------------------------------------------" # Check if neccessary environment variables are set: if not p.URL: debug_logger.debug("Warning: Environment variable PULSAR_API_URL not set.") elif not p.API_TOKEN: debug_logger.debug("Warning: Environment variable PULSAR_TOKEN not set.") debug_logger.debug(log_msg) error_logger.error(log_msg) log_msg = "Connecting to {}".format(p.URL) error_logger.error(log_msg) debug_logger.debug(log_msg) #: Connection to Elasticsearch. Expects that the envrionment variables ES_URL, ES_USER, and #: ES_PW are set, which signifiy the Elasticsearch cluster URL, login username and login #: password, respectively. ES = pulsarpy.elasticsearch_utils.Connection() def __init__(self, uid=None, upstream=None): """ Find the record of the given model specified by self.MODEL_NAME. The record can be looked up in a few ways, depending on which argument is specified (uid or upstream). If both are specified, then the upstream argument will be ignored. Args: uid: The database identifier of the record to fetch, which can be specified either as the primary id (i.e. 8) or the model prefix plus the primary id (i.e. B-8). Could also be the record's name if it has a name attribute (not all models do) and if so will be converted to the record ID. upstream: If set, then the record will be searched on its upstream_identifier attribute. """ # self.attrs will store the actual record's attributes. Initialize value now to empty dict # since it is expected to be set already in self.__setattr__(). self.__dict__["attrs"] = {} # rec_id could be the record's name. Check for that scenario, and convert to record ID if # necessary. if uid: rec_id = self.__class__.replace_name_with_id(uid) rec_json = self._get(rec_id=rec_id) elif upstream: rec_json = self._get(upstream=upstream) else: raise ValueError("Either the 'uid' or 'upstream' parameter must be set.") # Convert None values to empty string for key in rec_json: if rec_json[key] == None: rec_json[key] = "" self.rec_id = rec_json["id"] self.__dict__["attrs"] = rec_json #avoid call to self.__setitem__() for this attr. def __getattr__(self, name): """ Treats database attributes for the record as Python attributes. An attribute is looked up in self.attrs. """ return self.attrs[name] def __setattr__(self, name, value): """ Sets the value of an attribute in self.attrs. """ if name not in self.attrs: return object.__setattr__(self, name, value) object.__setattr__(self, self.attrs[name], value) #self.__dict__["attrs"][name] = value #this works too def __getitem__(self, item): return self.attrs[item] def __setitem__(self, item, value): self.attrs[item] = value def _get(self, rec_id=None, upstream=None): """ Fetches a record by the record's ID or upstream_identifier. Raises: `pulsarpy.models.RecordNotFound`: A record could not be found. """ if rec_id: self.record_url = self.__class__.get_record_url(rec_id) self.debug_logger.debug("GET {} record with ID {}: {}".format(self.__class__.__name__, rec_id, self.record_url)) response = requests.get(url=self.record_url, headers=HEADERS, verify=False) if not response.ok and response.status_code == requests.codes.NOT_FOUND: raise RecordNotFound("Search for {} record with ID '{}' returned no results.".format(self.__class__.__name__, rec_id)) self.write_response_html_to_file(response,"get_bob.html") response.raise_for_status() return response.json() elif upstream: rec_json = self.__class__.find_by({"upstream_identifier": upstream}, require=True) self.record_url = self.__class__.get_record_url(rec_json["id"]) return rec_json @classmethod def get_record_url(self, rec_id): return os.path.join(self.URL, str(rec_id)) @classmethod def log_post(cls, res_json): msg = cls.__name__ + "\t" + str(res_json["id"]) + "\t" name = res_json.get("name") if name: msg += name cls.post_logger.info(msg) @classmethod def replace_name_with_id(cls, name): """ Used to replace a foreign key reference using a name with an ID. Works by searching the record in Pulsar and expects to find exactly one hit. First, will check if the foreign key reference is an integer value and if so, returns that as it is presumed to be the foreign key. Raises: `pulsarpy.elasticsearch_utils.MultipleHitsException`: Multiple hits were returned from the name search. `pulsarpy.models.RecordNotFound`: No results were produced from the name search. """ try: int(name) return name #Already a presumed ID. except ValueError: pass #Not an int, so maybe a combination of MODEL_ABBR and Primary Key, i.e. B-8. if name.split("-")[0] in Meta._MODEL_ABBREVS: return int(name.split("-", 1)[1]) try: result = cls.ES.get_record_by_name(cls.ES_INDEX_NAME, name) if result: return result["id"] except pulsarpy.elasticsearch_utils.MultipleHitsException as e: raise raise RecordNotFound("Name '{}' for model '{}' not found.".format(name, cls.__name__)) @classmethod def add_model_name_to_payload(cls, payload): """ Checks whether the model name in question is in the payload. If not, the entire payload is set as a value of a key by the name of the model. This method is useful when some server-side Rails API calls expect the parameters to include the parameterized model name. For example, server-side endpoints that handle the updating of a biosample record or the creation of a new biosmample record will expect the payload to be of the form:: { "biosample": { "name": "new biosample", "donor": 3, ... } } Args: payload: `dict`. The data to send in an HTTP request. Returns: `dict`. """ if not cls.MODEL_NAME in payload: payload = {cls.MODEL_NAME: payload} return payload @staticmethod def check_boolean_fields(payload): for key in payload: val = payload[key] if type(val) != str: continue val = val.lower() if val in ["yes", "true", "pass"]: val = True payload[key] = val elif val == ["no", "false", "fail"]: val = False payload[key] = val return payload def get_upstream(self): return self.attrs.get(Model.UPSTREAM_ATTR) def abbrev_id(self): """ This method is called when posting to the ENCODE Portal to grab an alias for the record being submitted. The alias here is composed of the record ID in Pulsar (i.e. B-1 for the Biosample with ID 1). However, the record ID is prefexed with a 'p' to designate that this record was submitted from Pulsar. This is used to generate a unique alias considering that we used to uses a different LIMS (Syapse) to submit records. Many of the models in Syapse used the same model prefix as is used in Pulsar, i.e. (B)Biosample and (L)Library. Thus, w/o the 'p' prefix, the same alias could be generated in Pulsar as a previous one used in Syapse. """ return self.PULSAR_LIMS_PREFIX + self.MODEL_ABBR + "-" + str(self.id) def delete(self): """Deletes the record. """ res = requests.delete(url=self.record_url, headers=HEADERS, verify=False) #self.write_response_html_to_file(res,"bob_delete.html") if res.status_code == 204: #No content. Can't render json: return {} return res.json() @classmethod def find_by(cls, payload, require=False): """ Searches the model in question by AND joining the query parameters. Implements a Railsy way of looking for a record using a method by the same name and passing in the query as a dict. as well. Only the first hit is returned, and there is no particular ordering specified in the server-side API method. Args: payload: `dict`. The attributes of a record to restrict the search to. require: `bool`. True means to raise a `pulsarpy.models.RecordNotFound` exception if no record is found. Returns: `dict`: The JSON serialization of the record, if any, found by the API call. `None`: If the API call didnt' return any results. Raises: `pulsarpy.models.RecordNotFound`: No records were found, and the `require` parameter is True. """ if not isinstance(payload, dict): raise ValueError("The 'payload' parameter must be provided a dictionary object.") url = os.path.join(cls.URL, "find_by") payload = {"find_by": payload} cls.debug_logger.debug("Searching Pulsar {} for {}".format(cls.__name__, json.dumps(payload, indent=4))) res = requests.post(url=url, json=payload, headers=HEADERS, verify=False) #cls.write_response_html_to_file(res,"bob.html") res.raise_for_status() res_json = res.json() if res_json: try: res_json = res_json[cls.MODEL_NAME] except KeyError: # Key won't be present if there isn't a serializer for it on the server. pass else: if require: raise RecordNotFound("Can't find any {} records with search criteria: '{}'.".format(cls.__name__, payload)) return res_json @classmethod def find_by_or(cls, payload): """ Searches the model in question by OR joining the query parameters. Implements a Railsy way of looking for a record using a method by the same name and passing in the query as a string (for the OR operator joining to be specified). Only the first hit is returned, and there is not particular ordering specified in the server-side API method. Args: payload: `dict`. The attributes of a record to search for by using OR operator joining for each query parameter. Returns: `dict`: The JSON serialization of the record, if any, found by the API call. `None`: If the API call didnt' return any results. """ if not isinstance(payload, dict): raise ValueError("The 'payload' parameter must be provided a dictionary object.") url = os.path.join(cls.URL, "find_by_or") payload = {"find_by_or": payload} cls.debug_logger.debug("Searching Pulsar {} for {}".format(cls.__name__, json.dumps(payload, indent=4))) res = requests.post(url=url, json=payload, headers=HEADERS, verify=False) cls.write_response_html_to_file(res,"bob.html") if res: try: res = res[cls.MODEL_NAME] except KeyError: # Key won't be present if there isn't a serializer for it on the server. pass return res @classmethod def index(cls): """Fetches all records. Returns: `dict`. The JSON formatted response. Raises: `requests.exceptions.HTTPError`: The status code is not ok. """ res = requests.get(cls.URL, headers=HEADERS, verify=False) res.raise_for_status() return res.json() def patch(self, payload, append_to_arrays=True): """ Patches current record and udpates the current instance's 'attrs' attribute to reflect the new changes. Args: payload - hash. This will be JSON-formatted prior to sending the request. Returns: `dict`. The JSON formatted response. Raises: `requests.exceptions.HTTPError`: The status code is not ok. """ if not isinstance(payload, dict): raise ValueError("The 'payload' parameter must be provided a dictionary object.") payload = self.__class__.set_id_in_fkeys(payload) if append_to_arrays: for key in payload: val = payload[key] if type(val) == list: val.extend(getattr(self, key)) payload[key] = list(set(val)) payload = self.check_boolean_fields(payload) payload = self.__class__.add_model_name_to_payload(payload) self.debug_logger.debug("PATCHING payload {}".format(json.dumps(payload, indent=4))) res = requests.patch(url=self.record_url, json=payload, headers=HEADERS, verify=False) self.write_response_html_to_file(res,"bob.html") res.raise_for_status() json_res = res.json() self.debug_logger.debug("Success") self.attrs = json_res return json_res @classmethod def set_id_in_fkeys(cls, payload): """ Looks for any keys in the payload that end with either _id or _ids, signaling a foreign key field. For each foreign key field, checks whether the value is using the name of the record or the actual primary ID of the record (which may include the model abbreviation, i.e. B-1). If the former case, the name is replaced with the record's primary ID. Args: payload: `dict`. The payload to POST or PATCH. Returns: `dict`. The payload. """ for key in payload: val = payload[key] if not val: continue if key.endswith("_id"): model = getattr(THIS_MODULE, cls.FKEY_MAP[key]) rec_id = model.replace_name_with_id(name=val) payload[key] = rec_id elif key.endswith("_ids"): model = getattr(THIS_MODULE, cls.FKEY_MAP[key]) rec_ids = [] for v in val: rec_id = model.replace_name_with_id(name=v) rec_ids.append(rec_id) payload[key] = rec_ids return payload @classmethod def prepost_hooks(cls, payload): return payload @classmethod @classmethod def log_error(cls, msg): """ Logs the provided error message to both the error logger and the debug logger logging instances. Args: msg: `str`. The error message to log. """ cls.error_logger.error(msg) cls.debug_logger.debug(msg) @staticmethod def write_response_html_to_file(response,filename): """ An aid in troubleshooting internal application errors, i.e. <Response [500]>, to be mainly beneficial when developing the server-side API. This method will write the response HTML for viewing the error details in the browesr. Args: response: `requests.models.Response` instance. filename: `str`. The output file name. """ fout = open(filename,'w') if not str(response.status_code).startswith("2"): Model.debug_logger.debug(response.text) fout.write(response.text) fout.close()
nathankw/pulsarpy
pulsarpy/models.py
Model.log_error
python
def log_error(cls, msg): cls.error_logger.error(msg) cls.debug_logger.debug(msg)
Logs the provided error message to both the error logger and the debug logger logging instances. Args: msg: `str`. The error message to log.
train
https://github.com/nathankw/pulsarpy/blob/359b040c0f2383b88c0b5548715fefd35f5f634c/pulsarpy/models.py#L622-L631
null
class Model(metaclass=Meta): """ The superclass of all model classes. A model subclass is defined for each Rails model. An instance of a model class represents a record of the given Rails model. Subclasses don't typically define their own init method, but if they do, they need to make a call to 'super' to run the init method defined here as well. Subclasses must be instantiated with the rec_id argument set to a record's ID. A GET will immediately be done and the record's attributes will be stored in the self.attrs `dict`. The record's attributes can be accessed as normal instance attributes (i.e. ``record.name) rather than explicitly indexing the attrs dictionary, thanks to the employment of ``__getattr__()``. Similarly, record attributes can be updated via normal assignment operations, i.e. (``record.name = "bob"``), thanks to employment of ``__setattr__()``. Required Environment Variables: 1) PULSAR_API_URL 2) PULSAR_TOKEN """ #: Most models have an attribute alled upstream_identifier that is used to store the value of the #: record in an "upstream" database that is submitted to, i.e. the ENCODE Portal. Not all models #: have this attribute since not all are used for submission to an upstream portal. UPSTREAM_ATTR = "upstream_identifier" MODEL_ABBR = "" # subclasses define #: Abstract attribute of type `dict` that each subclass should fulfull if it has any foreign keys. #: Each key is a foreign key name and the value is the class name of the model it refers to. FKEY_MAP = {} #: A prefix that can be added in front of record IDs, names, model-record ID. This is useful #: when its necessary to add emphasis that these records exist or came from Pulsar ( i.e. when #: submitting them to an upstream database. PULSAR_LIMS_PREFIX = "p" #: This class adds a file handler, such that all messages sent to it are logged to this #: file in addition to STDOUT. debug_logger = logging.getLogger(p.DEBUG_LOGGER_NAME) # Add debug file handler to debug_logger: Meta.add_file_handler(logger=debug_logger, level=logging.DEBUG, tag="debug") #: A ``logging`` instance with a file handler for logging terse error messages. #: The log file resides locally within the directory specified by the constant #: ``p.LOG_DIR``. Accepts messages >= ``logging.ERROR``. error_logger = logging.getLogger(p.ERROR_LOGGER_NAME) log_level = logging.ERROR error_logger.setLevel(log_level) Meta.add_file_handler(logger=error_logger, level=log_level, tag="error") #: A ``logging`` instance with a file handler for logging successful POST operations. #: The log file resides locally within the directory specified by the constant #: ``p.LOG_DIR``. Accepts messages >= ``logging.INFO``. post_logger = logging.getLogger(p.POST_LOGGER_NAME) log_level = logging.INFO post_logger.setLevel(log_level) Meta.add_file_handler(logger=post_logger, level=log_level, tag="posted") log_msg = "-----------------------------------------------------------------------------------" # Check if neccessary environment variables are set: if not p.URL: debug_logger.debug("Warning: Environment variable PULSAR_API_URL not set.") elif not p.API_TOKEN: debug_logger.debug("Warning: Environment variable PULSAR_TOKEN not set.") debug_logger.debug(log_msg) error_logger.error(log_msg) log_msg = "Connecting to {}".format(p.URL) error_logger.error(log_msg) debug_logger.debug(log_msg) #: Connection to Elasticsearch. Expects that the envrionment variables ES_URL, ES_USER, and #: ES_PW are set, which signifiy the Elasticsearch cluster URL, login username and login #: password, respectively. ES = pulsarpy.elasticsearch_utils.Connection() def __init__(self, uid=None, upstream=None): """ Find the record of the given model specified by self.MODEL_NAME. The record can be looked up in a few ways, depending on which argument is specified (uid or upstream). If both are specified, then the upstream argument will be ignored. Args: uid: The database identifier of the record to fetch, which can be specified either as the primary id (i.e. 8) or the model prefix plus the primary id (i.e. B-8). Could also be the record's name if it has a name attribute (not all models do) and if so will be converted to the record ID. upstream: If set, then the record will be searched on its upstream_identifier attribute. """ # self.attrs will store the actual record's attributes. Initialize value now to empty dict # since it is expected to be set already in self.__setattr__(). self.__dict__["attrs"] = {} # rec_id could be the record's name. Check for that scenario, and convert to record ID if # necessary. if uid: rec_id = self.__class__.replace_name_with_id(uid) rec_json = self._get(rec_id=rec_id) elif upstream: rec_json = self._get(upstream=upstream) else: raise ValueError("Either the 'uid' or 'upstream' parameter must be set.") # Convert None values to empty string for key in rec_json: if rec_json[key] == None: rec_json[key] = "" self.rec_id = rec_json["id"] self.__dict__["attrs"] = rec_json #avoid call to self.__setitem__() for this attr. def __getattr__(self, name): """ Treats database attributes for the record as Python attributes. An attribute is looked up in self.attrs. """ return self.attrs[name] def __setattr__(self, name, value): """ Sets the value of an attribute in self.attrs. """ if name not in self.attrs: return object.__setattr__(self, name, value) object.__setattr__(self, self.attrs[name], value) #self.__dict__["attrs"][name] = value #this works too def __getitem__(self, item): return self.attrs[item] def __setitem__(self, item, value): self.attrs[item] = value def _get(self, rec_id=None, upstream=None): """ Fetches a record by the record's ID or upstream_identifier. Raises: `pulsarpy.models.RecordNotFound`: A record could not be found. """ if rec_id: self.record_url = self.__class__.get_record_url(rec_id) self.debug_logger.debug("GET {} record with ID {}: {}".format(self.__class__.__name__, rec_id, self.record_url)) response = requests.get(url=self.record_url, headers=HEADERS, verify=False) if not response.ok and response.status_code == requests.codes.NOT_FOUND: raise RecordNotFound("Search for {} record with ID '{}' returned no results.".format(self.__class__.__name__, rec_id)) self.write_response_html_to_file(response,"get_bob.html") response.raise_for_status() return response.json() elif upstream: rec_json = self.__class__.find_by({"upstream_identifier": upstream}, require=True) self.record_url = self.__class__.get_record_url(rec_json["id"]) return rec_json @classmethod def get_record_url(self, rec_id): return os.path.join(self.URL, str(rec_id)) @classmethod def log_post(cls, res_json): msg = cls.__name__ + "\t" + str(res_json["id"]) + "\t" name = res_json.get("name") if name: msg += name cls.post_logger.info(msg) @classmethod def replace_name_with_id(cls, name): """ Used to replace a foreign key reference using a name with an ID. Works by searching the record in Pulsar and expects to find exactly one hit. First, will check if the foreign key reference is an integer value and if so, returns that as it is presumed to be the foreign key. Raises: `pulsarpy.elasticsearch_utils.MultipleHitsException`: Multiple hits were returned from the name search. `pulsarpy.models.RecordNotFound`: No results were produced from the name search. """ try: int(name) return name #Already a presumed ID. except ValueError: pass #Not an int, so maybe a combination of MODEL_ABBR and Primary Key, i.e. B-8. if name.split("-")[0] in Meta._MODEL_ABBREVS: return int(name.split("-", 1)[1]) try: result = cls.ES.get_record_by_name(cls.ES_INDEX_NAME, name) if result: return result["id"] except pulsarpy.elasticsearch_utils.MultipleHitsException as e: raise raise RecordNotFound("Name '{}' for model '{}' not found.".format(name, cls.__name__)) @classmethod def add_model_name_to_payload(cls, payload): """ Checks whether the model name in question is in the payload. If not, the entire payload is set as a value of a key by the name of the model. This method is useful when some server-side Rails API calls expect the parameters to include the parameterized model name. For example, server-side endpoints that handle the updating of a biosample record or the creation of a new biosmample record will expect the payload to be of the form:: { "biosample": { "name": "new biosample", "donor": 3, ... } } Args: payload: `dict`. The data to send in an HTTP request. Returns: `dict`. """ if not cls.MODEL_NAME in payload: payload = {cls.MODEL_NAME: payload} return payload @staticmethod def check_boolean_fields(payload): for key in payload: val = payload[key] if type(val) != str: continue val = val.lower() if val in ["yes", "true", "pass"]: val = True payload[key] = val elif val == ["no", "false", "fail"]: val = False payload[key] = val return payload def get_upstream(self): return self.attrs.get(Model.UPSTREAM_ATTR) def abbrev_id(self): """ This method is called when posting to the ENCODE Portal to grab an alias for the record being submitted. The alias here is composed of the record ID in Pulsar (i.e. B-1 for the Biosample with ID 1). However, the record ID is prefexed with a 'p' to designate that this record was submitted from Pulsar. This is used to generate a unique alias considering that we used to uses a different LIMS (Syapse) to submit records. Many of the models in Syapse used the same model prefix as is used in Pulsar, i.e. (B)Biosample and (L)Library. Thus, w/o the 'p' prefix, the same alias could be generated in Pulsar as a previous one used in Syapse. """ return self.PULSAR_LIMS_PREFIX + self.MODEL_ABBR + "-" + str(self.id) def delete(self): """Deletes the record. """ res = requests.delete(url=self.record_url, headers=HEADERS, verify=False) #self.write_response_html_to_file(res,"bob_delete.html") if res.status_code == 204: #No content. Can't render json: return {} return res.json() @classmethod def find_by(cls, payload, require=False): """ Searches the model in question by AND joining the query parameters. Implements a Railsy way of looking for a record using a method by the same name and passing in the query as a dict. as well. Only the first hit is returned, and there is no particular ordering specified in the server-side API method. Args: payload: `dict`. The attributes of a record to restrict the search to. require: `bool`. True means to raise a `pulsarpy.models.RecordNotFound` exception if no record is found. Returns: `dict`: The JSON serialization of the record, if any, found by the API call. `None`: If the API call didnt' return any results. Raises: `pulsarpy.models.RecordNotFound`: No records were found, and the `require` parameter is True. """ if not isinstance(payload, dict): raise ValueError("The 'payload' parameter must be provided a dictionary object.") url = os.path.join(cls.URL, "find_by") payload = {"find_by": payload} cls.debug_logger.debug("Searching Pulsar {} for {}".format(cls.__name__, json.dumps(payload, indent=4))) res = requests.post(url=url, json=payload, headers=HEADERS, verify=False) #cls.write_response_html_to_file(res,"bob.html") res.raise_for_status() res_json = res.json() if res_json: try: res_json = res_json[cls.MODEL_NAME] except KeyError: # Key won't be present if there isn't a serializer for it on the server. pass else: if require: raise RecordNotFound("Can't find any {} records with search criteria: '{}'.".format(cls.__name__, payload)) return res_json @classmethod def find_by_or(cls, payload): """ Searches the model in question by OR joining the query parameters. Implements a Railsy way of looking for a record using a method by the same name and passing in the query as a string (for the OR operator joining to be specified). Only the first hit is returned, and there is not particular ordering specified in the server-side API method. Args: payload: `dict`. The attributes of a record to search for by using OR operator joining for each query parameter. Returns: `dict`: The JSON serialization of the record, if any, found by the API call. `None`: If the API call didnt' return any results. """ if not isinstance(payload, dict): raise ValueError("The 'payload' parameter must be provided a dictionary object.") url = os.path.join(cls.URL, "find_by_or") payload = {"find_by_or": payload} cls.debug_logger.debug("Searching Pulsar {} for {}".format(cls.__name__, json.dumps(payload, indent=4))) res = requests.post(url=url, json=payload, headers=HEADERS, verify=False) cls.write_response_html_to_file(res,"bob.html") if res: try: res = res[cls.MODEL_NAME] except KeyError: # Key won't be present if there isn't a serializer for it on the server. pass return res @classmethod def index(cls): """Fetches all records. Returns: `dict`. The JSON formatted response. Raises: `requests.exceptions.HTTPError`: The status code is not ok. """ res = requests.get(cls.URL, headers=HEADERS, verify=False) res.raise_for_status() return res.json() def patch(self, payload, append_to_arrays=True): """ Patches current record and udpates the current instance's 'attrs' attribute to reflect the new changes. Args: payload - hash. This will be JSON-formatted prior to sending the request. Returns: `dict`. The JSON formatted response. Raises: `requests.exceptions.HTTPError`: The status code is not ok. """ if not isinstance(payload, dict): raise ValueError("The 'payload' parameter must be provided a dictionary object.") payload = self.__class__.set_id_in_fkeys(payload) if append_to_arrays: for key in payload: val = payload[key] if type(val) == list: val.extend(getattr(self, key)) payload[key] = list(set(val)) payload = self.check_boolean_fields(payload) payload = self.__class__.add_model_name_to_payload(payload) self.debug_logger.debug("PATCHING payload {}".format(json.dumps(payload, indent=4))) res = requests.patch(url=self.record_url, json=payload, headers=HEADERS, verify=False) self.write_response_html_to_file(res,"bob.html") res.raise_for_status() json_res = res.json() self.debug_logger.debug("Success") self.attrs = json_res return json_res @classmethod def set_id_in_fkeys(cls, payload): """ Looks for any keys in the payload that end with either _id or _ids, signaling a foreign key field. For each foreign key field, checks whether the value is using the name of the record or the actual primary ID of the record (which may include the model abbreviation, i.e. B-1). If the former case, the name is replaced with the record's primary ID. Args: payload: `dict`. The payload to POST or PATCH. Returns: `dict`. The payload. """ for key in payload: val = payload[key] if not val: continue if key.endswith("_id"): model = getattr(THIS_MODULE, cls.FKEY_MAP[key]) rec_id = model.replace_name_with_id(name=val) payload[key] = rec_id elif key.endswith("_ids"): model = getattr(THIS_MODULE, cls.FKEY_MAP[key]) rec_ids = [] for v in val: rec_id = model.replace_name_with_id(name=v) rec_ids.append(rec_id) payload[key] = rec_ids return payload @classmethod def prepost_hooks(cls, payload): return payload @classmethod def post(cls, payload): """Posts the data to the specified record. Args: payload: `dict`. This will be JSON-formatted prior to sending the request. Returns: `dict`. The JSON formatted response. Raises: `Requests.exceptions.HTTPError`: The status code is not ok. `RecordNotUnique`: The Rails server returned the exception ActiveRecord::RecordNotUnique. """ if not isinstance(payload, dict): raise ValueError("The 'payload' parameter must be provided a dictionary object.") payload = cls.set_id_in_fkeys(payload) payload = cls.check_boolean_fields(payload) payload = cls.add_model_name_to_payload(payload) # Run any pre-post hooks: payload = cls.prepost_hooks(payload) cls.debug_logger.debug("POSTING payload {}".format(json.dumps(payload, indent=4))) res = requests.post(url=cls.URL, json=(payload), headers=HEADERS, verify=False) cls.write_response_html_to_file(res,"bob.html") if not res.ok: cls.log_error(res.text) res_json = res.json() if "exception" in res_json: exc_type = res_json["exception"] if exc_type == "ActiveRecord::RecordNotUnique": raise RecordNotUnique() res.raise_for_status() res = res.json() cls.log_post(res) cls.debug_logger.debug("Success") return res @classmethod @staticmethod def write_response_html_to_file(response,filename): """ An aid in troubleshooting internal application errors, i.e. <Response [500]>, to be mainly beneficial when developing the server-side API. This method will write the response HTML for viewing the error details in the browesr. Args: response: `requests.models.Response` instance. filename: `str`. The output file name. """ fout = open(filename,'w') if not str(response.status_code).startswith("2"): Model.debug_logger.debug(response.text) fout.write(response.text) fout.close()
nathankw/pulsarpy
pulsarpy/models.py
Model.write_response_html_to_file
python
def write_response_html_to_file(response,filename): fout = open(filename,'w') if not str(response.status_code).startswith("2"): Model.debug_logger.debug(response.text) fout.write(response.text) fout.close()
An aid in troubleshooting internal application errors, i.e. <Response [500]>, to be mainly beneficial when developing the server-side API. This method will write the response HTML for viewing the error details in the browesr. Args: response: `requests.models.Response` instance. filename: `str`. The output file name.
train
https://github.com/nathankw/pulsarpy/blob/359b040c0f2383b88c0b5548715fefd35f5f634c/pulsarpy/models.py#L634-L648
null
class Model(metaclass=Meta): """ The superclass of all model classes. A model subclass is defined for each Rails model. An instance of a model class represents a record of the given Rails model. Subclasses don't typically define their own init method, but if they do, they need to make a call to 'super' to run the init method defined here as well. Subclasses must be instantiated with the rec_id argument set to a record's ID. A GET will immediately be done and the record's attributes will be stored in the self.attrs `dict`. The record's attributes can be accessed as normal instance attributes (i.e. ``record.name) rather than explicitly indexing the attrs dictionary, thanks to the employment of ``__getattr__()``. Similarly, record attributes can be updated via normal assignment operations, i.e. (``record.name = "bob"``), thanks to employment of ``__setattr__()``. Required Environment Variables: 1) PULSAR_API_URL 2) PULSAR_TOKEN """ #: Most models have an attribute alled upstream_identifier that is used to store the value of the #: record in an "upstream" database that is submitted to, i.e. the ENCODE Portal. Not all models #: have this attribute since not all are used for submission to an upstream portal. UPSTREAM_ATTR = "upstream_identifier" MODEL_ABBR = "" # subclasses define #: Abstract attribute of type `dict` that each subclass should fulfull if it has any foreign keys. #: Each key is a foreign key name and the value is the class name of the model it refers to. FKEY_MAP = {} #: A prefix that can be added in front of record IDs, names, model-record ID. This is useful #: when its necessary to add emphasis that these records exist or came from Pulsar ( i.e. when #: submitting them to an upstream database. PULSAR_LIMS_PREFIX = "p" #: This class adds a file handler, such that all messages sent to it are logged to this #: file in addition to STDOUT. debug_logger = logging.getLogger(p.DEBUG_LOGGER_NAME) # Add debug file handler to debug_logger: Meta.add_file_handler(logger=debug_logger, level=logging.DEBUG, tag="debug") #: A ``logging`` instance with a file handler for logging terse error messages. #: The log file resides locally within the directory specified by the constant #: ``p.LOG_DIR``. Accepts messages >= ``logging.ERROR``. error_logger = logging.getLogger(p.ERROR_LOGGER_NAME) log_level = logging.ERROR error_logger.setLevel(log_level) Meta.add_file_handler(logger=error_logger, level=log_level, tag="error") #: A ``logging`` instance with a file handler for logging successful POST operations. #: The log file resides locally within the directory specified by the constant #: ``p.LOG_DIR``. Accepts messages >= ``logging.INFO``. post_logger = logging.getLogger(p.POST_LOGGER_NAME) log_level = logging.INFO post_logger.setLevel(log_level) Meta.add_file_handler(logger=post_logger, level=log_level, tag="posted") log_msg = "-----------------------------------------------------------------------------------" # Check if neccessary environment variables are set: if not p.URL: debug_logger.debug("Warning: Environment variable PULSAR_API_URL not set.") elif not p.API_TOKEN: debug_logger.debug("Warning: Environment variable PULSAR_TOKEN not set.") debug_logger.debug(log_msg) error_logger.error(log_msg) log_msg = "Connecting to {}".format(p.URL) error_logger.error(log_msg) debug_logger.debug(log_msg) #: Connection to Elasticsearch. Expects that the envrionment variables ES_URL, ES_USER, and #: ES_PW are set, which signifiy the Elasticsearch cluster URL, login username and login #: password, respectively. ES = pulsarpy.elasticsearch_utils.Connection() def __init__(self, uid=None, upstream=None): """ Find the record of the given model specified by self.MODEL_NAME. The record can be looked up in a few ways, depending on which argument is specified (uid or upstream). If both are specified, then the upstream argument will be ignored. Args: uid: The database identifier of the record to fetch, which can be specified either as the primary id (i.e. 8) or the model prefix plus the primary id (i.e. B-8). Could also be the record's name if it has a name attribute (not all models do) and if so will be converted to the record ID. upstream: If set, then the record will be searched on its upstream_identifier attribute. """ # self.attrs will store the actual record's attributes. Initialize value now to empty dict # since it is expected to be set already in self.__setattr__(). self.__dict__["attrs"] = {} # rec_id could be the record's name. Check for that scenario, and convert to record ID if # necessary. if uid: rec_id = self.__class__.replace_name_with_id(uid) rec_json = self._get(rec_id=rec_id) elif upstream: rec_json = self._get(upstream=upstream) else: raise ValueError("Either the 'uid' or 'upstream' parameter must be set.") # Convert None values to empty string for key in rec_json: if rec_json[key] == None: rec_json[key] = "" self.rec_id = rec_json["id"] self.__dict__["attrs"] = rec_json #avoid call to self.__setitem__() for this attr. def __getattr__(self, name): """ Treats database attributes for the record as Python attributes. An attribute is looked up in self.attrs. """ return self.attrs[name] def __setattr__(self, name, value): """ Sets the value of an attribute in self.attrs. """ if name not in self.attrs: return object.__setattr__(self, name, value) object.__setattr__(self, self.attrs[name], value) #self.__dict__["attrs"][name] = value #this works too def __getitem__(self, item): return self.attrs[item] def __setitem__(self, item, value): self.attrs[item] = value def _get(self, rec_id=None, upstream=None): """ Fetches a record by the record's ID or upstream_identifier. Raises: `pulsarpy.models.RecordNotFound`: A record could not be found. """ if rec_id: self.record_url = self.__class__.get_record_url(rec_id) self.debug_logger.debug("GET {} record with ID {}: {}".format(self.__class__.__name__, rec_id, self.record_url)) response = requests.get(url=self.record_url, headers=HEADERS, verify=False) if not response.ok and response.status_code == requests.codes.NOT_FOUND: raise RecordNotFound("Search for {} record with ID '{}' returned no results.".format(self.__class__.__name__, rec_id)) self.write_response_html_to_file(response,"get_bob.html") response.raise_for_status() return response.json() elif upstream: rec_json = self.__class__.find_by({"upstream_identifier": upstream}, require=True) self.record_url = self.__class__.get_record_url(rec_json["id"]) return rec_json @classmethod def get_record_url(self, rec_id): return os.path.join(self.URL, str(rec_id)) @classmethod def log_post(cls, res_json): msg = cls.__name__ + "\t" + str(res_json["id"]) + "\t" name = res_json.get("name") if name: msg += name cls.post_logger.info(msg) @classmethod def replace_name_with_id(cls, name): """ Used to replace a foreign key reference using a name with an ID. Works by searching the record in Pulsar and expects to find exactly one hit. First, will check if the foreign key reference is an integer value and if so, returns that as it is presumed to be the foreign key. Raises: `pulsarpy.elasticsearch_utils.MultipleHitsException`: Multiple hits were returned from the name search. `pulsarpy.models.RecordNotFound`: No results were produced from the name search. """ try: int(name) return name #Already a presumed ID. except ValueError: pass #Not an int, so maybe a combination of MODEL_ABBR and Primary Key, i.e. B-8. if name.split("-")[0] in Meta._MODEL_ABBREVS: return int(name.split("-", 1)[1]) try: result = cls.ES.get_record_by_name(cls.ES_INDEX_NAME, name) if result: return result["id"] except pulsarpy.elasticsearch_utils.MultipleHitsException as e: raise raise RecordNotFound("Name '{}' for model '{}' not found.".format(name, cls.__name__)) @classmethod def add_model_name_to_payload(cls, payload): """ Checks whether the model name in question is in the payload. If not, the entire payload is set as a value of a key by the name of the model. This method is useful when some server-side Rails API calls expect the parameters to include the parameterized model name. For example, server-side endpoints that handle the updating of a biosample record or the creation of a new biosmample record will expect the payload to be of the form:: { "biosample": { "name": "new biosample", "donor": 3, ... } } Args: payload: `dict`. The data to send in an HTTP request. Returns: `dict`. """ if not cls.MODEL_NAME in payload: payload = {cls.MODEL_NAME: payload} return payload @staticmethod def check_boolean_fields(payload): for key in payload: val = payload[key] if type(val) != str: continue val = val.lower() if val in ["yes", "true", "pass"]: val = True payload[key] = val elif val == ["no", "false", "fail"]: val = False payload[key] = val return payload def get_upstream(self): return self.attrs.get(Model.UPSTREAM_ATTR) def abbrev_id(self): """ This method is called when posting to the ENCODE Portal to grab an alias for the record being submitted. The alias here is composed of the record ID in Pulsar (i.e. B-1 for the Biosample with ID 1). However, the record ID is prefexed with a 'p' to designate that this record was submitted from Pulsar. This is used to generate a unique alias considering that we used to uses a different LIMS (Syapse) to submit records. Many of the models in Syapse used the same model prefix as is used in Pulsar, i.e. (B)Biosample and (L)Library. Thus, w/o the 'p' prefix, the same alias could be generated in Pulsar as a previous one used in Syapse. """ return self.PULSAR_LIMS_PREFIX + self.MODEL_ABBR + "-" + str(self.id) def delete(self): """Deletes the record. """ res = requests.delete(url=self.record_url, headers=HEADERS, verify=False) #self.write_response_html_to_file(res,"bob_delete.html") if res.status_code == 204: #No content. Can't render json: return {} return res.json() @classmethod def find_by(cls, payload, require=False): """ Searches the model in question by AND joining the query parameters. Implements a Railsy way of looking for a record using a method by the same name and passing in the query as a dict. as well. Only the first hit is returned, and there is no particular ordering specified in the server-side API method. Args: payload: `dict`. The attributes of a record to restrict the search to. require: `bool`. True means to raise a `pulsarpy.models.RecordNotFound` exception if no record is found. Returns: `dict`: The JSON serialization of the record, if any, found by the API call. `None`: If the API call didnt' return any results. Raises: `pulsarpy.models.RecordNotFound`: No records were found, and the `require` parameter is True. """ if not isinstance(payload, dict): raise ValueError("The 'payload' parameter must be provided a dictionary object.") url = os.path.join(cls.URL, "find_by") payload = {"find_by": payload} cls.debug_logger.debug("Searching Pulsar {} for {}".format(cls.__name__, json.dumps(payload, indent=4))) res = requests.post(url=url, json=payload, headers=HEADERS, verify=False) #cls.write_response_html_to_file(res,"bob.html") res.raise_for_status() res_json = res.json() if res_json: try: res_json = res_json[cls.MODEL_NAME] except KeyError: # Key won't be present if there isn't a serializer for it on the server. pass else: if require: raise RecordNotFound("Can't find any {} records with search criteria: '{}'.".format(cls.__name__, payload)) return res_json @classmethod def find_by_or(cls, payload): """ Searches the model in question by OR joining the query parameters. Implements a Railsy way of looking for a record using a method by the same name and passing in the query as a string (for the OR operator joining to be specified). Only the first hit is returned, and there is not particular ordering specified in the server-side API method. Args: payload: `dict`. The attributes of a record to search for by using OR operator joining for each query parameter. Returns: `dict`: The JSON serialization of the record, if any, found by the API call. `None`: If the API call didnt' return any results. """ if not isinstance(payload, dict): raise ValueError("The 'payload' parameter must be provided a dictionary object.") url = os.path.join(cls.URL, "find_by_or") payload = {"find_by_or": payload} cls.debug_logger.debug("Searching Pulsar {} for {}".format(cls.__name__, json.dumps(payload, indent=4))) res = requests.post(url=url, json=payload, headers=HEADERS, verify=False) cls.write_response_html_to_file(res,"bob.html") if res: try: res = res[cls.MODEL_NAME] except KeyError: # Key won't be present if there isn't a serializer for it on the server. pass return res @classmethod def index(cls): """Fetches all records. Returns: `dict`. The JSON formatted response. Raises: `requests.exceptions.HTTPError`: The status code is not ok. """ res = requests.get(cls.URL, headers=HEADERS, verify=False) res.raise_for_status() return res.json() def patch(self, payload, append_to_arrays=True): """ Patches current record and udpates the current instance's 'attrs' attribute to reflect the new changes. Args: payload - hash. This will be JSON-formatted prior to sending the request. Returns: `dict`. The JSON formatted response. Raises: `requests.exceptions.HTTPError`: The status code is not ok. """ if not isinstance(payload, dict): raise ValueError("The 'payload' parameter must be provided a dictionary object.") payload = self.__class__.set_id_in_fkeys(payload) if append_to_arrays: for key in payload: val = payload[key] if type(val) == list: val.extend(getattr(self, key)) payload[key] = list(set(val)) payload = self.check_boolean_fields(payload) payload = self.__class__.add_model_name_to_payload(payload) self.debug_logger.debug("PATCHING payload {}".format(json.dumps(payload, indent=4))) res = requests.patch(url=self.record_url, json=payload, headers=HEADERS, verify=False) self.write_response_html_to_file(res,"bob.html") res.raise_for_status() json_res = res.json() self.debug_logger.debug("Success") self.attrs = json_res return json_res @classmethod def set_id_in_fkeys(cls, payload): """ Looks for any keys in the payload that end with either _id or _ids, signaling a foreign key field. For each foreign key field, checks whether the value is using the name of the record or the actual primary ID of the record (which may include the model abbreviation, i.e. B-1). If the former case, the name is replaced with the record's primary ID. Args: payload: `dict`. The payload to POST or PATCH. Returns: `dict`. The payload. """ for key in payload: val = payload[key] if not val: continue if key.endswith("_id"): model = getattr(THIS_MODULE, cls.FKEY_MAP[key]) rec_id = model.replace_name_with_id(name=val) payload[key] = rec_id elif key.endswith("_ids"): model = getattr(THIS_MODULE, cls.FKEY_MAP[key]) rec_ids = [] for v in val: rec_id = model.replace_name_with_id(name=v) rec_ids.append(rec_id) payload[key] = rec_ids return payload @classmethod def prepost_hooks(cls, payload): return payload @classmethod def post(cls, payload): """Posts the data to the specified record. Args: payload: `dict`. This will be JSON-formatted prior to sending the request. Returns: `dict`. The JSON formatted response. Raises: `Requests.exceptions.HTTPError`: The status code is not ok. `RecordNotUnique`: The Rails server returned the exception ActiveRecord::RecordNotUnique. """ if not isinstance(payload, dict): raise ValueError("The 'payload' parameter must be provided a dictionary object.") payload = cls.set_id_in_fkeys(payload) payload = cls.check_boolean_fields(payload) payload = cls.add_model_name_to_payload(payload) # Run any pre-post hooks: payload = cls.prepost_hooks(payload) cls.debug_logger.debug("POSTING payload {}".format(json.dumps(payload, indent=4))) res = requests.post(url=cls.URL, json=(payload), headers=HEADERS, verify=False) cls.write_response_html_to_file(res,"bob.html") if not res.ok: cls.log_error(res.text) res_json = res.json() if "exception" in res_json: exc_type = res_json["exception"] if exc_type == "ActiveRecord::RecordNotUnique": raise RecordNotUnique() res.raise_for_status() res = res.json() cls.log_post(res) cls.debug_logger.debug("Success") return res @classmethod def log_error(cls, msg): """ Logs the provided error message to both the error logger and the debug logger logging instances. Args: msg: `str`. The error message to log. """ cls.error_logger.error(msg) cls.debug_logger.debug(msg) @staticmethod
nathankw/pulsarpy
pulsarpy/models.py
Biosample.parent_ids
python
def parent_ids(self): action = os.path.join(self.record_url, "parent_ids") res = requests.get(url=action, headers=HEADERS, verify=False) res.raise_for_status() return res.json()["biosamples"]
Returns an array of parent Biosample IDs. If the current Biosample has a part_of relationship, the Biosampled referenced there will be returned. Otherwise, if the current Biosample was generated from a pool of Biosamples (pooled_from_biosample_ids), then those will be returned. Otherwise, the result will be an empty array.
train
https://github.com/nathankw/pulsarpy/blob/359b040c0f2383b88c0b5548715fefd35f5f634c/pulsarpy/models.py#L696-L706
null
class Biosample(Model): MODEL_ABBR = "B" FKEY_MAP = {} FKEY_MAP["batch_item_id"] = "BatchItem" FKEY_MAP["biosample_part_ids"] = "Biosample" FKEY_MAP["biosample_term_name_id"] = "BiosampleTermName" FKEY_MAP["biosample_type_id"] = "BiosampleType" FKEY_MAP["chipseq_experiment_id"] = "ChipseqExperiment" FKEY_MAP["crispr_modification_id"] = "CrisprModification" FKEY_MAP["donor_id"] = "Donor" FKEY_MAP["immunoblot_ids"] = "Donor" FKEY_MAP["owner_id"] = "Owner" FKEY_MAP["part_of_id"] = "Biosample" FKEY_MAP["pooled_from_ids"] = "Biosample" FKEY_MAP["transfected_by_id"] = "User" FKEY_MAP["vendor_id"] = "Vendor" FKEY_MAP["document_ids"] = "Document" FKEY_MAP["pooled_biosample_ids"] = "Biosample" FKEY_MAP["pooled_from_biosample_ids"] = "Biosample" FKEY_MAP["treatment_ids"] = "Treatment" def find_first_wt_parent(self, with_ip=False): """ Recursively looks at the part_of parent ancestry line (ignoring pooled_from parents) and returns a parent Biosample ID if its wild_type attribute is True. Args: with_ip: `bool`. True means to restrict the search to the first parental Wild Type that also has an Immunoblot linked to it, which may serve as a control between another immunoblot. For example, it could be useful to compare the target protein bands in Immunoblots between a Wild Type sample and a CRISPR eGFP-tagged gene in a descendent sample. Returns: `False`: There isn't a WT parent, or there is but not one with an Immunoblot linked to it (if the `with_ip` parameter is set to True). `int`: The ID of the WT parent. """ parent_id = self.part_of_id if not parent_id: return False parent = Biosample(parent_id) if parent.wild_type: if with_ip and parent.immunoblot_ids: return parent.id elif not with_ip: return parent.id return parent.find_first_wt_parent(with_ip=with_ip) def get_latest_library(self): """ Returns the associated library having the largest ID (the most recent one created). It's possible for a Biosample in Pulsar to have more than one Library, but this is rare. """ max_id = max(self.library_ids) return Library(max_id) def get_latest_seqresult(self): # Use latest Library library = self.get_latest_library() library = Library(library_id) sreq_ids = library.sequencing_request_ids # Use latest SequencingRequest sreq = SequencingRequest(max(sreq_ids)) srun_ids = sreq.sequencing_run_ids # Use latest SequencingRun srun = SequencingRun(max(srun_ids)) sres = srun.library_sequencing_result(library.id) return sres
nathankw/pulsarpy
pulsarpy/models.py
Biosample.find_first_wt_parent
python
def find_first_wt_parent(self, with_ip=False): parent_id = self.part_of_id if not parent_id: return False parent = Biosample(parent_id) if parent.wild_type: if with_ip and parent.immunoblot_ids: return parent.id elif not with_ip: return parent.id return parent.find_first_wt_parent(with_ip=with_ip)
Recursively looks at the part_of parent ancestry line (ignoring pooled_from parents) and returns a parent Biosample ID if its wild_type attribute is True. Args: with_ip: `bool`. True means to restrict the search to the first parental Wild Type that also has an Immunoblot linked to it, which may serve as a control between another immunoblot. For example, it could be useful to compare the target protein bands in Immunoblots between a Wild Type sample and a CRISPR eGFP-tagged gene in a descendent sample. Returns: `False`: There isn't a WT parent, or there is but not one with an Immunoblot linked to it (if the `with_ip` parameter is set to True). `int`: The ID of the WT parent.
train
https://github.com/nathankw/pulsarpy/blob/359b040c0f2383b88c0b5548715fefd35f5f634c/pulsarpy/models.py#L708-L734
[ "def find_first_wt_parent(self, with_ip=False):\n \"\"\"\n Recursively looks at the part_of parent ancestry line (ignoring pooled_from parents) and returns\n a parent Biosample ID if its wild_type attribute is True. \n\n Args:\n with_ip: `bool`. True means to restrict the search to the first pare...
class Biosample(Model): MODEL_ABBR = "B" FKEY_MAP = {} FKEY_MAP["batch_item_id"] = "BatchItem" FKEY_MAP["biosample_part_ids"] = "Biosample" FKEY_MAP["biosample_term_name_id"] = "BiosampleTermName" FKEY_MAP["biosample_type_id"] = "BiosampleType" FKEY_MAP["chipseq_experiment_id"] = "ChipseqExperiment" FKEY_MAP["crispr_modification_id"] = "CrisprModification" FKEY_MAP["donor_id"] = "Donor" FKEY_MAP["immunoblot_ids"] = "Donor" FKEY_MAP["owner_id"] = "Owner" FKEY_MAP["part_of_id"] = "Biosample" FKEY_MAP["pooled_from_ids"] = "Biosample" FKEY_MAP["transfected_by_id"] = "User" FKEY_MAP["vendor_id"] = "Vendor" FKEY_MAP["document_ids"] = "Document" FKEY_MAP["pooled_biosample_ids"] = "Biosample" FKEY_MAP["pooled_from_biosample_ids"] = "Biosample" FKEY_MAP["treatment_ids"] = "Treatment" def parent_ids(self): """ Returns an array of parent Biosample IDs. If the current Biosample has a part_of relationship, the Biosampled referenced there will be returned. Otherwise, if the current Biosample was generated from a pool of Biosamples (pooled_from_biosample_ids), then those will be returned. Otherwise, the result will be an empty array. """ action = os.path.join(self.record_url, "parent_ids") res = requests.get(url=action, headers=HEADERS, verify=False) res.raise_for_status() return res.json()["biosamples"] def get_latest_library(self): """ Returns the associated library having the largest ID (the most recent one created). It's possible for a Biosample in Pulsar to have more than one Library, but this is rare. """ max_id = max(self.library_ids) return Library(max_id) def get_latest_seqresult(self): # Use latest Library library = self.get_latest_library() library = Library(library_id) sreq_ids = library.sequencing_request_ids # Use latest SequencingRequest sreq = SequencingRequest(max(sreq_ids)) srun_ids = sreq.sequencing_run_ids # Use latest SequencingRun srun = SequencingRun(max(srun_ids)) sres = srun.library_sequencing_result(library.id) return sres
nathankw/pulsarpy
pulsarpy/models.py
Document.upload
python
def upload(cls, path, document_type, is_protocol, description=""): file_name = os.path.basename(path) mime_type = mimetypes.guess_type(file_name)[0] data = base64.b64encode(open(path, 'rb').read()) temp_uri = str(data, "utf-8") #href = "data:{mime_type};base64,{temp_uri}".format(mime_type=mime_type, temp_uri=temp_uri) payload = {} payload["content_type"] = mime_type payload["data"] = temp_uri payload["description"] = description payload["document_type_id"] = DocumentType(document_type).id payload["name"] = file_name payload["is_protocol"] = is_protocol cls.post(payload)
Args: path: `str`. The path to the document to upload. document_type: `str`. DocumentType identified by the value of its name attribute. is_protocol: `bool`. description: `str`.
train
https://github.com/nathankw/pulsarpy/blob/359b040c0f2383b88c0b5548715fefd35f5f634c/pulsarpy/models.py#L838-L858
null
class Document(Model): MODEL_ABBR = "DOC" FKEY_MAP = {} FKEY_MAP["document_type_id"] = "DocumentType" def download(self): # The sever is Base64 encoding the payload, so we'll need to base64 decode it. url = self.record_url + "/download" res = requests.get(url=url, headers=HEADERS, verify=False) res.raise_for_status() data = base64.b64decode(res.json()["data"]) return data @classmethod
nathankw/pulsarpy
pulsarpy/models.py
Library.post
python
def post(cls, payload): slpk_attr_name = "sequencing_library_prep_kit_id" paired_bc_id_attr_name = "paired_barcode_id" seq_reg = re.compile("^[ACGTN]+$") if paired_bc_id_attr_name in payload: try: index1, index2 = payload[paired_bc_id_attr_name].upper().split("-") except ValueError: # Not in GATTTCCA-GGCGTCGA format so let it be. return Model.post(cls=cls, payload=payload) if not seq_reg.match(index1) or not seq_reg.match(index2): # Not in GATTTCCA-GGCGTCGA format so let it be. return Model.post(cls=cls, payload=payload) if not slpk_attr_name in payload: raise Exception("You need to include the " + slpk + " attribute name.") slpk_id = SequencingLibraryPrepKit.replace_name_with_id(payload[slpk_attr_name]) payload[slpk_attr_name] = slpk_id index1_id = Barcode.find_by(payload={slpk_attr_name: slpk_id, "index_number": 1, "sequence": index1}, require=True)["id"] index2_id = Barcode.find_by(payload={slpk_attr_name: slpk_id, "index_number": 2, "sequence": index2}, require=True)["id"] # Ensure that PairedBarcode for this index combo already exists: pbc_payload = {"index1_id": index1_id, "index2_id": index2_id, slpk_attr_name: slpk_id} pbc_exists = PairedBarcode.find_by(payload=pbc_payload) if not pbc_exists: pbc_exists = PairedBarcode.post(payload=pbc_payload) pbc_id = pbc_exists["id"] payload[paired_bc_id_attr_name] = pbc_id return super().post(payload=payload)
A wrapper over Model.post() that handles the case where a Library has a PairedBarcode and the user may have supplied the PairedBarcode in the form of index1-index2, i.e. GATTTCCA-GGCGTCGA. This isn't the PairedBarcode's record name or a record ID, thus Model.post() won't be able to figure out the PairedBarcode's ID to substitute in the payload (via a call to cls.replace_name_with_id()). Thus, this wrapper will attempt to replace a PairedBarcode sequence in the payload with a PairedBarcode ID, then pass the payload off to Model.post().
train
https://github.com/nathankw/pulsarpy/blob/359b040c0f2383b88c0b5548715fefd35f5f634c/pulsarpy/models.py#L969-L1005
[ "def post(cls, payload):\n \"\"\"Posts the data to the specified record.\n\n Args:\n payload: `dict`. This will be JSON-formatted prior to sending the request.\n\n Returns:\n `dict`. The JSON formatted response.\n\n Raises:\n `Requests.exceptions.HTTPError`: The status code is not o...
class Library(Model): MODEL_ABBR = "L" FKEY_MAP = {} # belongs_to/ has_one FKEY_MAP["barcode_id"] = "Barcode" FKEY_MAP["biosample_id"] = "Biosample" FKEY_MAP["concentration_unit_id"] = "Unit" FKEY_MAP["from_prototype_id"] = "Library" FKEY_MAP["library_fragmentation_method_id"] = "LibraryFragmentationMethod" FKEY_MAP["nucleic_acid_term_id"] = "NucleicAcidTerm" FKEY_MAP["paired_barcode_id"] = "PairedBarcode" FKEY_MAP["sequencing_library_prep_kit_id"] = "SequencingLibraryPrepKit" FKEY_MAP["sequencing_request_ids"] = "SequencingRequest" FKEY_MAP["single_cell_sorting_id"] = "SingleCellSorting" FKEY_MAP["user_id"] = "User" FKEY_MAP["vendor_id"] = "Vendor" FKEY_MAP["well_id"] = "Well" # has_many FKEY_MAP["document_ids"] = "Document" @classmethod def post(cls, payload): """ A wrapper over Model.post() that handles the case where a Library has a PairedBarcode and the user may have supplied the PairedBarcode in the form of index1-index2, i.e. GATTTCCA-GGCGTCGA. This isn't the PairedBarcode's record name or a record ID, thus Model.post() won't be able to figure out the PairedBarcode's ID to substitute in the payload (via a call to cls.replace_name_with_id()). Thus, this wrapper will attempt to replace a PairedBarcode sequence in the payload with a PairedBarcode ID, then pass the payload off to Model.post(). """ slpk_attr_name = "sequencing_library_prep_kit_id" paired_bc_id_attr_name = "paired_barcode_id" seq_reg = re.compile("^[ACGTN]+$") if paired_bc_id_attr_name in payload: try: index1, index2 = payload[paired_bc_id_attr_name].upper().split("-") except ValueError: # Not in GATTTCCA-GGCGTCGA format so let it be. return Model.post(cls=cls, payload=payload) if not seq_reg.match(index1) or not seq_reg.match(index2): # Not in GATTTCCA-GGCGTCGA format so let it be. return Model.post(cls=cls, payload=payload) if not slpk_attr_name in payload: raise Exception("You need to include the " + slpk + " attribute name.") slpk_id = SequencingLibraryPrepKit.replace_name_with_id(payload[slpk_attr_name]) payload[slpk_attr_name] = slpk_id index1_id = Barcode.find_by(payload={slpk_attr_name: slpk_id, "index_number": 1, "sequence": index1}, require=True)["id"] index2_id = Barcode.find_by(payload={slpk_attr_name: slpk_id, "index_number": 2, "sequence": index2}, require=True)["id"] # Ensure that PairedBarcode for this index combo already exists: pbc_payload = {"index1_id": index1_id, "index2_id": index2_id, slpk_attr_name: slpk_id} pbc_exists = PairedBarcode.find_by(payload=pbc_payload) if not pbc_exists: pbc_exists = PairedBarcode.post(payload=pbc_payload) pbc_id = pbc_exists["id"] payload[paired_bc_id_attr_name] = pbc_id return super().post(payload=payload) def get_barcode_sequence(self): if self.barcode_id: return Barcode(self.barcode_id).sequence elif self.paired_barcode_id: return PairedBarcode(self.paired_barcode_id).sequence() return
nathankw/pulsarpy
pulsarpy/models.py
SequencingRequest.get_library_barcode_sequence_hash
python
def get_library_barcode_sequence_hash(self, inverse=False): action = os.path.join(self.record_url, "get_library_barcode_sequence_hash") res = requests.get(url=action, headers=HEADERS, verify=False) res.raise_for_status() res_json = res.json() # Convert library ID from string to int new_res = {} for lib_id in res_json: new_res[int(lib_id)] = res_json[lib_id] res_json = new_res if inverse: rev = {} for lib_id in res_json: rev[res_json[lib_id]] = lib_id res_json = rev return res_json
Calls the SequencingRequest's get_library_barcode_sequence_hash server-side endpoint to create a hash of the form {LibraryID -> barcode_sequence} for all Libraries on the SequencingRequest. Args: inverse: `bool`. True means to inverse the key and value pairs such that the barcode sequence serves as the key. Returns: `dict`.
train
https://github.com/nathankw/pulsarpy/blob/359b040c0f2383b88c0b5548715fefd35f5f634c/pulsarpy/models.py#L1047-L1074
null
class SequencingRequest(Model): MODEL_ABBR = "SREQ" FKEY_MAP = {} FKEY_MAP["concentration_unit_id"] = "Unit" FKEY_MAP["library_ids"] = "Library" FKEY_MAP["sequencing_platform_id"] = "SequencingPlatform" FKEY_MAP["sequencing_center_id"] = "SequencingCenter" FKEY_MAP["submitted_by_id"] = "User"
nathankw/pulsarpy
pulsarpy/models.py
SequencingRun.library_sequencing_results
python
def library_sequencing_results(self): sres_ids = self.sequencing_result_ids res = {} for i in sres_ids: sres = SequencingResult(i) res[sres.library_id] = sres return res
Generates a dict. where each key is a Library ID on the SequencingRequest and each value is the associated SequencingResult. Libraries that aren't yet with a SequencingResult are not inlcuded in the dict.
train
https://github.com/nathankw/pulsarpy/blob/359b040c0f2383b88c0b5548715fefd35f5f634c/pulsarpy/models.py#L1098-L1109
null
class SequencingRun(Model): MODEL_ABBR = "SRUN" FKEY_MAP = {} FKEY_MAP["data_storage_id"] = "DataStorage" FKEY_MAP["sequencing_request_id"] = "SequencingRequest" FKEY_MAP["submitted_by_id"] = "User" def library_sequencing_result(self, library_id): """ Fetches a SequencingResult record for a given Library ID. """ action = os.path.join(self.record_url, "library_sequencing_result") res = requests.get(url=action, json={"library_id": library_id}, headers=HEADERS, verify=False) res.raise_for_status() return res.json()
nathankw/pulsarpy
pulsarpy/models.py
User.unarchive_user
python
def unarchive_user(self, user_id): url = self.record_url + "/unarchive" res = requests.patch(url=url, json={"user_id": user_id}, headers=HEADERS, verify=False) self.write_response_html_to_file(res,"bob.html") res.raise_for_status()
Unarchives the user with the specified user ID. Args: user_id: `int`. The ID of the user to unarchive. Returns: `NoneType`: None.
train
https://github.com/nathankw/pulsarpy/blob/359b040c0f2383b88c0b5548715fefd35f5f634c/pulsarpy/models.py#L1179-L1191
[ "def write_response_html_to_file(response,filename):\n \"\"\"\n An aid in troubleshooting internal application errors, i.e. <Response [500]>, to be mainly\n beneficial when developing the server-side API. This method will write the response HTML\n for viewing the error details in the browesr.\n\n Ar...
class User(Model): def archive_user(self, user_id): """Archives the user with the specified user ID. Args: user_id: `int`. The ID of the user to archive. Returns: `NoneType`: None. """ url = self.record_url + "/archive" res = requests.patch(url=url, json={"user_id": user_id}, headers=HEADERS, verify=False) self.write_response_html_to_file(res,"bob.html") res.raise_for_status() def generate_api_key(self): """ Generates an API key for the user, replacing any existing one. Returns: `str`: The new API key. """ url = self.record_url + "/generate_api_key" res = requests.patch(url=url, headers=HEADERS, verify=False) self.write_response_html_to_file(res,"bob.html") res.raise_for_status() return res.json()["token"] def remove_api_key(self): """ Removes the user's existing API key, if present, and sets the current instance's 'api_key' attribute to the empty string. Returns: `NoneType`: None. """ url = self.record_url + "/remove_api_key" res = requests.patch(url=url, headers=HEADERS, verify=False) res.raise_for_status() self.api_key = ""
nathankw/pulsarpy
pulsarpy/models.py
User.remove_api_key
python
def remove_api_key(self): url = self.record_url + "/remove_api_key" res = requests.patch(url=url, headers=HEADERS, verify=False) res.raise_for_status() self.api_key = ""
Removes the user's existing API key, if present, and sets the current instance's 'api_key' attribute to the empty string. Returns: `NoneType`: None.
train
https://github.com/nathankw/pulsarpy/blob/359b040c0f2383b88c0b5548715fefd35f5f634c/pulsarpy/models.py#L1206-L1217
null
class User(Model): def archive_user(self, user_id): """Archives the user with the specified user ID. Args: user_id: `int`. The ID of the user to archive. Returns: `NoneType`: None. """ url = self.record_url + "/archive" res = requests.patch(url=url, json={"user_id": user_id}, headers=HEADERS, verify=False) self.write_response_html_to_file(res,"bob.html") res.raise_for_status() def unarchive_user(self, user_id): """Unarchives the user with the specified user ID. Args: user_id: `int`. The ID of the user to unarchive. Returns: `NoneType`: None. """ url = self.record_url + "/unarchive" res = requests.patch(url=url, json={"user_id": user_id}, headers=HEADERS, verify=False) self.write_response_html_to_file(res,"bob.html") res.raise_for_status() def generate_api_key(self): """ Generates an API key for the user, replacing any existing one. Returns: `str`: The new API key. """ url = self.record_url + "/generate_api_key" res = requests.patch(url=url, headers=HEADERS, verify=False) self.write_response_html_to_file(res,"bob.html") res.raise_for_status() return res.json()["token"]
nathankw/pulsarpy
pulsarpy/utils.py
send_mail
python
def send_mail(form, from_name): form["from"] = "{} <mailgun@{}>".format(from_name, pulsarpy.MAIL_DOMAIN), if not pulsarpy.MAIL_SERVER_URL: raise Exception("MAILGUN_DOMAIN environment variable not set.") if not pulsarpy.MAIL_AUTH[1]: raise Exception("MAILGUN_API_KEY environment varible not set.") res = requests.post(pulsarpy.MAIL_SERVER_URL, data=form, auth=pulsarpy.MAIL_AUTH) res.raise_for_status() return res
Sends a mail using the configured mail server for Pulsar. See mailgun documentation at https://documentation.mailgun.com/en/latest/user_manual.html#sending-via-api for specifics. Args: form: `dict`. The mail form fields, i.e. 'to', 'from', ... Returns: `requests.models.Response` instance. Raises: `requests.exceptions.HTTPError`: The status code is not ok. `Exception`: The environment variable MAILGUN_DOMAIN or MAILGUN_API_KEY isn't set. Example:: payload = { "from"="{} <mailgun@{}>".format(from_name, pulsarpy.MAIL_DOMAIN), "subject": "mailgun test", "text": "howdy there", "to": "nathankw@stanford.edu", } send_mail(payload)
train
https://github.com/nathankw/pulsarpy/blob/359b040c0f2383b88c0b5548715fefd35f5f634c/pulsarpy/utils.py#L15-L48
null
# -*- coding: utf-8 -*- ###Author #Nathaniel Watson #2017-09-18 #nathankw@stanford.edu ### import requests import pulsarpy SREQ_STATUSES = ["not started", "started", "trouble-shooting", "failed", "finished"] def send_mail(form, from_name): """ Sends a mail using the configured mail server for Pulsar. See mailgun documentation at https://documentation.mailgun.com/en/latest/user_manual.html#sending-via-api for specifics. Args: form: `dict`. The mail form fields, i.e. 'to', 'from', ... Returns: `requests.models.Response` instance. Raises: `requests.exceptions.HTTPError`: The status code is not ok. `Exception`: The environment variable MAILGUN_DOMAIN or MAILGUN_API_KEY isn't set. Example:: payload = { "from"="{} <mailgun@{}>".format(from_name, pulsarpy.MAIL_DOMAIN), "subject": "mailgun test", "text": "howdy there", "to": "nathankw@stanford.edu", } send_mail(payload) """ form["from"] = "{} <mailgun@{}>".format(from_name, pulsarpy.MAIL_DOMAIN), if not pulsarpy.MAIL_SERVER_URL: raise Exception("MAILGUN_DOMAIN environment variable not set.") if not pulsarpy.MAIL_AUTH[1]: raise Exception("MAILGUN_API_KEY environment varible not set.") res = requests.post(pulsarpy.MAIL_SERVER_URL, data=form, auth=pulsarpy.MAIL_AUTH) res.raise_for_status() return res def fahrenheit_to_celsius(temp): return (temp - 32) * (5.0/9) def kelvin_to_celsius(temp): return -273.15 + temp def get_exp_of_biosample(biosample_rec): """ Determines whether the biosample is part of a ChipseqExperiment or SingleCellSorting Experiment, and if so, returns the associated experiment as a models.Model instance that is one of those two classes. The biosample is determined to be part of a ChipseqExperiment if the Biosample.chipseq_experiment_id attribute is set, meaning that the biosample can be associated to the ChipseqExperiment as a replicate via any of of the following ChipseqExperiment attributes: ChipseqExperiment.replicates ChipseqExperiment.control_replicates The biosample will be determined to be part of a SingleCellSorting experiment if the Biosample.sorting_biosample_single_cell_sorting attribute is set, meaning that it is the SingleCellSorting.sorting_biosample. Args: biosample_rec: `dict`. A Biosample record as returned by instantiating `models.Biosample`. Raises: `Exception`: An experiment is not associated to this biosample. """ chip_exp_id = biosample_rec.chipseq_experiment_id ssc_id = biosample_rec.sorting_biosample_single_cell_sorting_id if chip_exp_id: return {"type": "chipseq_experiment", "record": models.ChipseqExperiment(chip_exp_id)} elif ssc_id: return {"type": "single_cell_sorting", "record": models.SingleCellSorting(ssc_id)} raise Exception("Biosample {} is not on an experiment.".format(biosample_rec["id"])) def sreqs_by_status(status): """ Returns an array of all SequencingRequest objects whose status attribute is set to the specified state. Status must be one of {}. """.format(SREQ_STATUSES) pass
nathankw/pulsarpy
pulsarpy/utils.py
get_exp_of_biosample
python
def get_exp_of_biosample(biosample_rec): chip_exp_id = biosample_rec.chipseq_experiment_id ssc_id = biosample_rec.sorting_biosample_single_cell_sorting_id if chip_exp_id: return {"type": "chipseq_experiment", "record": models.ChipseqExperiment(chip_exp_id)} elif ssc_id: return {"type": "single_cell_sorting", "record": models.SingleCellSorting(ssc_id)} raise Exception("Biosample {} is not on an experiment.".format(biosample_rec["id"]))
Determines whether the biosample is part of a ChipseqExperiment or SingleCellSorting Experiment, and if so, returns the associated experiment as a models.Model instance that is one of those two classes. The biosample is determined to be part of a ChipseqExperiment if the Biosample.chipseq_experiment_id attribute is set, meaning that the biosample can be associated to the ChipseqExperiment as a replicate via any of of the following ChipseqExperiment attributes: ChipseqExperiment.replicates ChipseqExperiment.control_replicates The biosample will be determined to be part of a SingleCellSorting experiment if the Biosample.sorting_biosample_single_cell_sorting attribute is set, meaning that it is the SingleCellSorting.sorting_biosample. Args: biosample_rec: `dict`. A Biosample record as returned by instantiating `models.Biosample`. Raises: `Exception`: An experiment is not associated to this biosample.
train
https://github.com/nathankw/pulsarpy/blob/359b040c0f2383b88c0b5548715fefd35f5f634c/pulsarpy/utils.py#L57-L84
null
# -*- coding: utf-8 -*- ###Author #Nathaniel Watson #2017-09-18 #nathankw@stanford.edu ### import requests import pulsarpy SREQ_STATUSES = ["not started", "started", "trouble-shooting", "failed", "finished"] def send_mail(form, from_name): """ Sends a mail using the configured mail server for Pulsar. See mailgun documentation at https://documentation.mailgun.com/en/latest/user_manual.html#sending-via-api for specifics. Args: form: `dict`. The mail form fields, i.e. 'to', 'from', ... Returns: `requests.models.Response` instance. Raises: `requests.exceptions.HTTPError`: The status code is not ok. `Exception`: The environment variable MAILGUN_DOMAIN or MAILGUN_API_KEY isn't set. Example:: payload = { "from"="{} <mailgun@{}>".format(from_name, pulsarpy.MAIL_DOMAIN), "subject": "mailgun test", "text": "howdy there", "to": "nathankw@stanford.edu", } send_mail(payload) """ form["from"] = "{} <mailgun@{}>".format(from_name, pulsarpy.MAIL_DOMAIN), if not pulsarpy.MAIL_SERVER_URL: raise Exception("MAILGUN_DOMAIN environment variable not set.") if not pulsarpy.MAIL_AUTH[1]: raise Exception("MAILGUN_API_KEY environment varible not set.") res = requests.post(pulsarpy.MAIL_SERVER_URL, data=form, auth=pulsarpy.MAIL_AUTH) res.raise_for_status() return res def fahrenheit_to_celsius(temp): return (temp - 32) * (5.0/9) def kelvin_to_celsius(temp): return -273.15 + temp def sreqs_by_status(status): """ Returns an array of all SequencingRequest objects whose status attribute is set to the specified state. Status must be one of {}. """.format(SREQ_STATUSES) pass
Roastero/freshroastsr700
freshroastsr700/__init__.py
freshroastsr700.fan_speed
python
def fan_speed(self, value): if value not in range(1, 10): raise exceptions.RoasterValueError self._fan_speed.value = value
Verifies the value is between 1 and 9 inclusively.
train
https://github.com/Roastero/freshroastsr700/blob/49cf4961444c0f56d051d5ac5088ace480b54f02/freshroastsr700/__init__.py#L238-L243
null
class freshroastsr700(object): """A class to interface with a freshroastsr700 coffee roaster. Args: update_data_func (func): A function to call when this object receives new data from the hardware. Defaults to None. state_transition_func (func): A function to call when time_remaining counts down to 0 and the device is either in roasting or cooling state. Defaults to None. thermostat (bool): thermostat mode. if set to True, turns on thermostat mode. In thermostat mode, freshroastsr700 takes control of heat_setting and does software PID control to hit the demanded target_temp. Defaults to False. ext_sw_heater_drive (bool): enable direct control over the internal heat_controller object. Defaults to False. When set to True, the thermostat field is IGNORED, and assumed to be False. Direct control over the software heater_level means that the freshroastsr700's PID controller cannot control the heater. Since thermostat and ext_sw_heater_drive cannot be allowed to both be True, this arg is given precedence over the thermostat arg. Note that (thermostat=False, ext_sw_heater_drive=False), (thermostat=True, ext_sw_heater_drive=False), (thermostat=False, ext_sw_heater_drive=True), are all acceptable arg combinations. Only the (thermostat=True, ext_sw_heater_drive=True), cominbation is not allowed, and this software will set thermostat=False in that case. kp (float): Kp value to use for PID control. Defaults to 0.06. ki (float): Ki value to use for PID control. Defaults to 0.0075. kd (float): Kd value to use for PID control. Defaults to 0.01. heater_segments (int): the pseudo-control range for the internal heat_controller object. Defaults to 8. """ def __init__(self, update_data_func=None, state_transition_func=None, thermostat=False, kp=0.06, ki=0.0075, kd=0.01, heater_segments=8, ext_sw_heater_drive=False): """Create variables used to send in packets to the roaster. The update data function is called when a packet is opened. The state transistion function is used by the timer thread to know what to do next. See wiki for more information on packet structure and fields.""" # constants for protocol decoding self.LOOKING_FOR_HEADER_1 = 0 self.LOOKING_FOR_HEADER_2 = 1 self.PACKET_DATA = 2 self.LOOKING_FOR_FOOTER_2 = 3 # constants for connection state monitoring self.CS_NOT_CONNECTED = -2 self.CS_ATTEMPTING_CONNECT = -1 self.CS_CONNECTING = 0 self.CS_CONNECTED = 1 # constants for connection attempt type self.CA_NONE = 0 self.CA_AUTO = 1 self.CA_SINGLE_SHOT = 2 self._create_update_data_system(update_data_func) self._create_state_transition_system(state_transition_func) self._header = sharedctypes.Array('c', b'\xAA\xAA') self._temp_unit = sharedctypes.Array('c', b'\x61\x74') self._flags = sharedctypes.Array('c', b'\x63') self._current_state = sharedctypes.Array('c', b'\x02\x01') self._footer = b'\xAA\xFA' self._fan_speed = sharedctypes.Value('i', 1) self._heat_setting = sharedctypes.Value('i', 0) self._target_temp = sharedctypes.Value('i', 150) self._current_temp = sharedctypes.Value('i', 150) self._time_remaining = sharedctypes.Value('i', 0) self._total_time = sharedctypes.Value('i', 0) self._disconnect = sharedctypes.Value('i', 0) self._teardown = sharedctypes.Value('i', 0) # for SW PWM heater setting self._heater_level = sharedctypes.Value('i', 0) # the following vars are not process-safe, do not access them # from the comm or timer threads, nor from the callbacks. self._ext_sw_heater_drive = ext_sw_heater_drive if not self._ext_sw_heater_drive: self._thermostat = thermostat else: self._thermostat = False self._pid_kp = kp self._pid_ki = ki self._pid_kd = kd self._heater_bangbang_segments = heater_segments # initialize to 'not connected' self._connected = sharedctypes.Value('i', 0) self._connect_state = sharedctypes.Value('i', self.CS_NOT_CONNECTED) # initialize to 'not trying to connect' self._attempting_connect = sharedctypes.Value('i', self.CA_NONE) # create comm process self.comm_process = mp.Process( target=self._comm, args=( self._thermostat, self._pid_kp, self._pid_ki, self._pid_kd, self._heater_bangbang_segments, self._ext_sw_heater_drive, self.update_data_event,)) self.comm_process.daemon = True self.comm_process.start() # create timer process that counts down time_remaining self.time_process = mp.Process( target=self._timer, args=( self.state_transition_event,)) self.time_process.daemon = True self.time_process.start() def _create_update_data_system( self, update_data_func, setFunc=True, createThread=False): # these callbacks cannot be called from another process in Windows. # Therefore, spawn a thread belonging to the calling process # instead. # the comm and timer processes will set events that the threads # will listen for to initiate the callbacks # only create the mp.Event once - # to mimic create_state_transition_system, for future-proofing # (in this case, currently, this is only called at __init__() time) if not hasattr(self, 'update_data_event'): self.update_data_event = mp.Event() # only create the thread.Event once - this is used to exit # the callback thread if not hasattr(self, 'update_data_callback_kill_event'): self.update_data_callback_kill_event = mp.Event() # destroy an existing thread if we had created one previously if(hasattr(self, 'update_data_thread') and self.update_data_thread is not None): # let's tear this down. To kill it, two events must be set... # in the right sequence! self.update_data_callback_kill_event.set() self.update_data_event.set() self.update_data_thread.join() if setFunc: self.update_data_func = update_data_func if self.update_data_func is not None: if createThread: self.update_data_callback_kill_event.clear() self.update_data_thread = threading.Thread( name='sr700_update_data', target=self.update_data_run, args=(self.update_data_event,), daemon=True ) else: self.update_data_thread = None def _create_state_transition_system( self, state_transition_func, setFunc=True, createThread=False): # these callbacks cannot be called from another process in Windows. # Therefore, spawn a thread belonging to the calling process # instead. # the comm and timer processes will set events that the threads # will listen for to initiate the callbacks # only create the mp.Event once - this fn can get called more # than once, by __init__() and by set_state_transition_func() if not hasattr(self, 'state_transition_event'): self.state_transition_event = mp.Event() # only create the thread.Event once - this is used to exit # the callback thread if not hasattr(self, 'state_transition_callback_kill_event'): self.state_transition_callback_kill_event = mp.Event() # destroy an existing thread if we had created one previously if(hasattr(self, 'state_transition_thread') and self.state_transition_thread is not None): # let's tear this down. To kill it, two events must be set... # in the right sequence! self.state_transition_callback_kill_event.set() self.state_transition_event.set() self.state_transition_thread.join() if setFunc: self.state_transition_func = state_transition_func if self.state_transition_func is not None: if createThread: self.state_transition_callback_kill_event.clear() self.state_transition_thread = threading.Thread( name='sr700_state_transition', target=self.state_transition_run, args=(self.state_transition_event,), daemon=True ) else: self.state_transition_thread = None @property def fan_speed(self): """Get/Set fan speed. Can be 1 to 9 inclusive. Args: Setter: fan_speed (int): fan speed Returns: Getter: (int): fan speed """ return self._fan_speed.value @fan_speed.setter @property def heat_setting(self): """Get/Set heat setting, 0 to 3 inclusive. 0=off, 3=high. Do not set when running freshroastsr700 in thermostat mode. Args: Setter: heat_setting (int): heat setting Returns: Getter: (int): heat setting """ return self._heat_setting.value @heat_setting.setter def heat_setting(self, value): """Verifies that the heat setting is between 0 and 3.""" if value not in range(0, 4): raise exceptions.RoasterValueError self._heat_setting.value = value @property def target_temp(self): """Get/Set the target temperature for this package's built-in software PID controler. Only used when freshroastsr700 is instantiated with thermostat=True. Args: Setter: value (int): a target temperature in degF between 150 and 551. Returns: Getter: (int) target temperature in degF between 150 and 551 """ return self._target_temp.value @target_temp.setter def target_temp(self, value): if value not in range(150, 551): raise exceptions.RoasterValueError self._target_temp.value = value @property def current_temp(self): """Current temperature of the roast chamber as reported by hardware. Returns: (int) current temperature, in degrees Fahrenheit """ return self._current_temp.value @current_temp.setter def current_temp(self, value): if value not in range(150, 551): raise exceptions.RoasterValueError self._current_temp.value = value @property def time_remaining(self): """The amount of time, in seconds, remaining until a call to the state_transition_func is made. can be set to an arbitrary value up to 600 seconds at any time. When a new value is set, freshroastsr700 will count down from this new value down to 0. time_remaining is decremented to 0 only when in a roasting or cooling state. In other states, the value is not touched. Args: Setter: time_remaining (int): tiem remaining in seconds Returns: Getter: time_remaining(int): time remaining, in seconds """ return self._time_remaining.value @time_remaining.setter def time_remaining(self, value): self._time_remaining.value = value @property def total_time(self): """The total time this instance has been in roasting or cooling state sicne the latest roast began. Returns: total_time (int): time, in seconds """ return self._total_time.value @total_time.setter def total_time(self, value): self._total_time.value = value @property def heater_level(self): """A getter method for _heater_level. When thermostat=True, value is driven by built-in PID controller. When ext_sw_heater_drive=True, value is driven by calls to heater_level(). Min will always be zero, max will be heater_segments (optional instantiation parameter, defaults to 8).""" return self._heater_level.value @heater_level.setter def heater_level(self, value): """Verifies that the heater_level is between 0 and heater_segments. Can only be called when freshroastsr700 object is initialized with ext_sw_heater_drive=True. Will throw RoasterValueError otherwise.""" if self._ext_sw_heater_drive: if value not in range(0, self._heater_bangbang_segments+1): raise exceptions.RoasterValueError self._heater_level.value = value else: raise exceptions.RoasterValueError @property def connected(self): """A getter method for _connected. Indicates that the this software is currently communicating with FreshRoast SR700 hardware.""" return self._connected.value @property def connect_state(self): """A getter method for _connect_state. Indicates the current connection state this software is in for FreshRoast SR700 hardware. Returns: freshroastsr700.CS_NOT_CONNECTED the software is not currenting communicating with hardware, neither was it instructed to do so. A previously failed connection attempt will also result in this state. freshroastsr700.CS_ATTEMPTING_CONNECT A call to auto_connect() or connect() was made, and the software is currently attempting to connect to hardware. freshroastsr700.CS_CONNECTED The hardware was found, and the software is communicating with the hardware. """ return self._connect_state.value def set_state_transition_func(self, func): """THIS FUNCTION MUST BE CALLED BEFORE CALLING freshroastsr700.auto_connect(). Set, or re-set, the state transition function callback. The supplied function will be called from a separate thread within freshroastsr700, triggered by a separate, internal child process. This function will fail if the freshroastsr700 device is already connected to hardware, because by that time, the timer process and thread have already been spawned. Args: state_transition_func (func): the function to call for every state transition. A state transition occurs whenever the freshroastsr700's time_remaining value counts down to 0. Returns: nothing """ if self._connected.value: logging.error("freshroastsr700.set_state_transition_func must be " "called before freshroastsr700.auto_connect()." " Not registering func.") return False # no connection yet. so OK to set func pointer self._create_state_transition_system(func) return True def update_data_run(self, event_to_wait_on): """This is the thread that listens to an event from the comm process to execute the update_data_func callback in the context of the main process. """ # with the daemon=Turue setting, this thread should # quit 'automatically' while event_to_wait_on.wait(): event_to_wait_on.clear() if self.update_data_callback_kill_event.is_set(): return self.update_data_func() def state_transition_run(self, event_to_wait_on): """This is the thread that listens to an event from the timer process to execute the state_transition_func callback in the context of the main process. """ # with the daemon=Turue setting, this thread should # quit 'automatically' while event_to_wait_on.wait(): event_to_wait_on.clear() if self.state_transition_callback_kill_event.is_set(): return self.state_transition_func() def _connect(self): """Do not call this directly - call auto_connect() or connect(), which will call _connect() for you. Connects to the roaster and creates communication thread. Raises a RoasterLokkupError exception if the hardware is not found. """ # the following call raises a RoasterLookupException when the device # is not found. It is port = utils.find_device('1A86:5523') # on some systems, after the device port is added to the device list, # it can take up to 20 seconds after USB insertion for # the port to become available... (!) # let's put a safety timeout in here as a precaution wait_timeout = time.time() + 40.0 # should be PLENTY of time! # let's update the _connect_state while we're at it... self._connect_state.value = self.CS_CONNECTING connect_success = False while time.time() < wait_timeout: try: self._ser = serial.Serial( port=port, baudrate=9600, bytesize=8, parity='N', stopbits=1.5, timeout=0.25, xonxoff=False, rtscts=False, dsrdtr=False) connect_success = True break except serial.SerialException: time.sleep(0.5) if not connect_success: # timeout on attempts raise exceptions.RoasterLookupError self._initialize() def _initialize(self): """Sends the initialization packet to the roaster.""" self._header.value = b'\xAA\x55' self._current_state.value = b'\x00\x00' s = self._generate_packet() self._ser.write(s) self._header.value = b'\xAA\xAA' self._current_state.value = b'\x02\x01' return self._read_existing_recipe() def _write_to_device(self): success = False try: packet = self._generate_packet() logging.debug('WR: ' + str(binascii.hexlify(packet))) self._ser.write(packet) success = True except serial.serialutil.SerialException: logging.error('caught serial exception writing') return success def _read_from_device(self): r = [] footer_reached = False while len(r) < 14 and footer_reached is False: r.append(self._ser.read(1)) if len(r) >= 2 and b''.join(r)[-2:] == self._footer: footer_reached = True logging.debug('RD: ' + str(binascii.hexlify(b''.join(r)))) return b''.join(r) def _read_existing_recipe(self): existing_recipe = [] end_of_recipe = False while not end_of_recipe: bytes_waiting = self._ser.in_waiting if bytes_waiting < 14: # still need to write to device every .25sec it seems time.sleep(0.25) self._write_to_device() else: while (bytes_waiting // 14) > 0: r = self._read_from_device() bytes_waiting = self._ser.in_waiting if len(r) < 14: logging.warn('short packet length') else: existing_recipe.append(r) if r[4:5] == b'\xAF' or r[4:5] == b'\x00': end_of_recipe = True continue return existing_recipe def connect(self): """Attempt to connect to hardware immediately. Will not retry. Check freshroastsr700.connected or freshroastsr700.connect_state to verify result. Raises: freshroastsr700.exeptions.RoasterLookupError No hardware connected to the computer. """ self._start_connect(self.CA_SINGLE_SHOT) while(self._connect_state.value == self.CS_ATTEMPTING_CONNECT or self._connect_state.value == self.CS_CONNECTING): time.sleep(0.1) if self.CS_CONNECTED != self._connect_state.value: raise exceptions.RoasterLookupError def auto_connect(self): """Starts a thread that will automatically connect to the roaster when it is plugged in.""" self._start_connect(self.CA_AUTO) def _start_connect(self, connect_type): """Starts the connection process, as called (internally) from the user context, either from auto_connect() or connect(). Never call this from the _comm() process context. """ if self._connect_state.value != self.CS_NOT_CONNECTED: # already done or in process, assume success return self._connected.value = 0 self._connect_state.value = self.CS_ATTEMPTING_CONNECT # tell comm process to attempt connection self._attempting_connect.value = connect_type # EXTREMELY IMPORTANT - for this to work at all in Windows, # where the above processes are spawned (vs forked in Unix), # the thread objects (as sattributes of this object) must be # assigned to this object AFTER we have spawned the processes. # That way, multiprocessing can pickle the freshroastsr700 # successfully. (It can't pickle thread-related stuff.) if self.update_data_func is not None: # Need to launch the thread that will listen to the event self._create_update_data_system( None, setFunc=False, createThread=True) self.update_data_thread.start() if self.state_transition_func is not None: # Need to launch the thread that will listen to the event self._create_state_transition_system( None, setFunc=False, createThread=True) self.state_transition_thread.start() def _auto_connect(self): """Attempts to connect to the roaster every quarter of a second.""" while not self._teardown.value: try: self._connect() return True except exceptions.RoasterLookupError: time.sleep(.25) return False def disconnect(self): """Stops the communication loop to the roaster. Note that this will not actually stop the roaster itself.""" self._disconnect.value = 1 def terminate(self): """Stops the communication loop to the roaster and closes down all communication processes. Note that this will not actually stop the roaster itself. You will need to instantiate a new freshroastsr700 object after calling this function, in order to re-start communications with the hardware. """ self.disconnect() self._teardown.value = 1 def _comm(self, thermostat=False, kp=0.06, ki=0.0075, kd=0.01, heater_segments=8, ext_sw_heater_drive=False, update_data_event=None): """Do not call this directly - call auto_connect(), which will spawn comm() for you. This is the main communications loop to the roaster. whenever a valid packet is received from the device, if an update_data_event is available, it will be signalled. Args: thermostat (bool): thermostat mode. if set to True, turns on thermostat mode. In thermostat mode, freshroastsr700 takes control of heat_setting and does software PID control to hit the demanded target_temp. ext_sw_heater_drive (bool): enable direct control over the internal heat_controller object. Defaults to False. When set to True, the thermostat field is IGNORED, and assumed to be False. Direct control over the software heater_level means that the PID controller cannot control the heater. Since thermostat and ext_sw_heater_drive cannot be allowed to both be True, this arg is given precedence over the thermostat arg. kp (float): Kp value to use for PID control. Defaults to 0.06. ki (float): Ki value to use for PID control. Defaults to 0.0075. kd (float): Kd value to use for PID control. Defaults to 0.01. heater_segments (int): the pseudo-control range for the internal heat_controller object. Defaults to 8. update_data_event (multiprocessing.Event): If set, allows the comm_process to signal to the parent process that new device data is available. Returns: nothing """ # since this process is started with daemon=True, it should exit # when the owning process terminates. Therefore, safe to loop forever. while not self._teardown.value: # waiting for command to attempt connect # print( "waiting for command to attempt connect") while self._attempting_connect.value == self.CA_NONE: time.sleep(0.25) if self._teardown.value: break # if we're tearing down, bail now. if self._teardown.value: break # we got the command to attempt to connect # change state to 'attempting_connect' self._connect_state.value = self.CS_ATTEMPTING_CONNECT # attempt connection if self.CA_AUTO == self._attempting_connect.value: # this call will block until a connection is achieved # it will also set _connect_state to CS_CONNECTING # if appropriate if self._auto_connect(): # when we unblock, it is an indication of a successful # connection self._connected.value = 1 self._connect_state.value = self.CS_CONNECTED else: # failure, normally due to a timeout self._connected.value = 0 self._connect_state.value = self.CS_NOT_CONNECTED # we failed to connect - start over from the top # reset flag self._attempting_connect.value = self.CA_NONE continue elif self.CA_SINGLE_SHOT == self._attempting_connect.value: # try once, now, if failure, start teh big loop over try: self._connect() self._connected.value = 1 self._connect_state.value = self.CS_CONNECTED except exceptions.RoasterLookupError: self._connected.value = 0 self._connect_state.value = self.CS_NOT_CONNECTED if self._connect_state.value != self.CS_CONNECTED: # we failed to connect - start over from the top # reset flag self._attempting_connect.value = self.CA_NONE continue else: # shouldn't be here # reset flag self._attempting_connect.value = self.CA_NONE continue # We are connected! # print( "We are connected!") # reset flag right away self._attempting_connect.value = self.CA_NONE # Initialize PID controller if thermostat function was specified at # init time pidc = None heater = None if(thermostat): pidc = pid.PID(kp, ki, kd, Output_max=heater_segments, Output_min=0 ) if thermostat or ext_sw_heater_drive: heater = heat_controller(number_of_segments=heater_segments) read_state = self.LOOKING_FOR_HEADER_1 r = [] write_errors = 0 read_errors = 0 while not self._disconnect.value: start = datetime.datetime.now() # write to device if not self._write_to_device(): logging.error('comm - _write_to_device() failed!') write_errors += 1 if write_errors > 3: # it's time to consider the device as being "gone" logging.error('comm - 3 successive write ' 'failures, disconnecting.') self._disconnect.value = 1 continue else: # reset write_errors write_errors = 0 # read from device try: while self._ser.in_waiting: _byte = self._ser.read(1) read_state, r, err = ( self._process_reponse_byte( read_state, _byte, r, update_data_event)) except IOError: # typically happens when device is suddenly unplugged logging.error('comm - read from device failed!') read_errors += 1 if write_errors > 3: # it's time to consider the device as being "gone" logging.error('comm - 3 successive read ' 'failures, disconnecting.') self._disconnect.value = 1 continue else: read_errors = 0 # next, drive SW heater when using # thermostat mode (PID controller calcs) # or in external sw heater drive mode, # when roasting. if thermostat or ext_sw_heater_drive: if 'roasting' == self.get_roaster_state(): if heater.about_to_rollover(): # it's time to use the PID controller value # and set new output level on heater! if ext_sw_heater_drive: # read user-supplied value heater.heat_level = self._heater_level.value else: # thermostat output = pidc.update( self.current_temp, self.target_temp) heater.heat_level = output # make this number visible to other processes... self._heater_level.value = heater.heat_level # read bang-bang heater output array element & apply it if heater.generate_bangbang_output(): # ON self.heat_setting = 3 else: # OFF self.heat_setting = 0 else: # for all other states, heat_level = OFF heater.heat_level = 0 # make this number visible to other processes... self._heater_level.value = heater.heat_level self.heat_setting = 0 # calculate sleep time to stick to 0.25sec period comp_time = datetime.datetime.now() - start sleep_duration = 0.25 - comp_time.total_seconds() if sleep_duration > 0: time.sleep(sleep_duration) self._ser.close() # reset disconnect flag self._disconnect.value = 0 # reset connection values self._connected.value = 0 self._connect_state.value = self.CS_NOT_CONNECTED # print("We are disconnected.") def _process_reponse_byte(self, read_state, _byte, r, update_data_event): err = False if self.LOOKING_FOR_HEADER_1 == read_state: if b'\xAA' == _byte: read_state = self.LOOKING_FOR_HEADER_2 elif self.LOOKING_FOR_HEADER_2 == read_state: if b'\xAA' == _byte: read_state = self.PACKET_DATA # reset packet array now... r = [] else: read_state = self.LOOKING_FOR_HEADER_1 elif self.PACKET_DATA == read_state: if b'\xAA' == _byte: # this could be the start of an end of packet marker read_state = self.LOOKING_FOR_FOOTER_2 else: r.append(_byte) # SR700 FW bug - if current temp is 250 degF (0xFA), # the FW does not transmit the footer at all. # fake the footer here. if(len(r) == 10 and b'\xFA' == _byte): # we will 'fake' a footer to make this decoder work # as intended read_state, r, _ = ( self._process_reponse_byte( read_state, b'\xAA', r, update_data_event)) read_state, r, err = ( self._process_reponse_byte( read_state, b'\xFA', r, update_data_event)) elif self.LOOKING_FOR_FOOTER_2 == read_state: if b'\xFA' == _byte: # OK we have a full packet - PROCESS PACKET err = self._process_response_data(r, update_data_event) read_state = self.LOOKING_FOR_HEADER_1 else: # the last byte was not the beginning of the footer r.append(b'\xAA') read_state = self.PACKET_DATA read_state, r, err = self._process_reponse_byte( read_state, _byte, r, update_data_event) else: # error state, shouldn't happen... logging.error('_process_reponse_byte - invalid read_state %d' % read_state) read_state = self.LOOKING_FOR_HEADER_1 err = True return read_state, r, err def _process_response_data(self, r, update_data_event): err = False if len(r) != 10: logging.warn('read packet data len not 10, got: %d' % len(r)) logging.warn('RD: ' + str(binascii.hexlify(b''.join(r)))) err = True else: temp = struct.unpack(">H", b''.join(r[8:10]))[0] if(temp == 65280): self.current_temp = 150 elif(temp > 550 or temp < 150): logging.warn('temperature out of range: reinitializing...') self._initialize() err = True return else: self.current_temp = temp if(update_data_event is not None): update_data_event.set() return err def _timer(self, state_transition_event=None): """Timer loop used to keep track of the time while roasting or cooling. If the time remaining reaches zero, the roaster will call the supplied state transistion function or the roaster will be set to the idle state.""" while not self._teardown.value: state = self.get_roaster_state() if(state == 'roasting' or state == 'cooling'): time.sleep(1) self.total_time += 1 if(self.time_remaining > 0): self.time_remaining -= 1 else: if(state_transition_event is not None): state_transition_event.set() else: self.idle() else: time.sleep(0.01) def get_roaster_state(self): """Returns a string based upon the current state of the roaster. Will raise an exception if the state is unknown. Returns: 'idle' if idle, 'sleeping' if sleeping, 'cooling' if cooling, 'roasting' if roasting, 'connecting' if in hardware connection phase, 'unknown' otherwise """ value = self._current_state.value if(value == b'\x02\x01'): return 'idle' elif(value == b'\x04\x04'): return 'cooling' elif(value == b'\x08\x01'): return 'sleeping' # handle null bytes as empty strings elif(value == b'\x00\x00' or value == b''): return 'connecting' elif(value == b'\x04\x02'): return 'roasting' else: return 'unknown' def _generate_packet(self): """Generates a packet based upon the current class variables. Note that current temperature is not sent, as the original application sent zeros to the roaster for the current temperature.""" roaster_time = utils.seconds_to_float(self._time_remaining.value) packet = ( self._header.value + self._temp_unit.value + self._flags.value + self._current_state.value + struct.pack(">B", self._fan_speed.value) + struct.pack(">B", int(round(roaster_time * 10.0))) + struct.pack(">B", self._heat_setting.value) + b'\x00\x00' + self._footer) return packet def idle(self): """Sets the current state of the roaster to idle.""" self._current_state.value = b'\x02\x01' def roast(self): """Sets the current state of the roaster to roast and begins roasting.""" self._current_state.value = b'\x04\x02' def cool(self): """Sets the current state of the roaster to cool. The roaster expects that cool will be run after roast, and will not work as expected if ran before.""" self._current_state.value = b'\x04\x04' def sleep(self): """Sets the current state of the roaster to sleep. Different than idle in that this will set double dashes on the roaster display rather than digits.""" self._current_state.value = b'\x08\x01'
Roastero/freshroastsr700
freshroastsr700/__init__.py
freshroastsr700.heat_setting
python
def heat_setting(self, value): if value not in range(0, 4): raise exceptions.RoasterValueError self._heat_setting.value = value
Verifies that the heat setting is between 0 and 3.
train
https://github.com/Roastero/freshroastsr700/blob/49cf4961444c0f56d051d5ac5088ace480b54f02/freshroastsr700/__init__.py#L259-L264
null
class freshroastsr700(object): """A class to interface with a freshroastsr700 coffee roaster. Args: update_data_func (func): A function to call when this object receives new data from the hardware. Defaults to None. state_transition_func (func): A function to call when time_remaining counts down to 0 and the device is either in roasting or cooling state. Defaults to None. thermostat (bool): thermostat mode. if set to True, turns on thermostat mode. In thermostat mode, freshroastsr700 takes control of heat_setting and does software PID control to hit the demanded target_temp. Defaults to False. ext_sw_heater_drive (bool): enable direct control over the internal heat_controller object. Defaults to False. When set to True, the thermostat field is IGNORED, and assumed to be False. Direct control over the software heater_level means that the freshroastsr700's PID controller cannot control the heater. Since thermostat and ext_sw_heater_drive cannot be allowed to both be True, this arg is given precedence over the thermostat arg. Note that (thermostat=False, ext_sw_heater_drive=False), (thermostat=True, ext_sw_heater_drive=False), (thermostat=False, ext_sw_heater_drive=True), are all acceptable arg combinations. Only the (thermostat=True, ext_sw_heater_drive=True), cominbation is not allowed, and this software will set thermostat=False in that case. kp (float): Kp value to use for PID control. Defaults to 0.06. ki (float): Ki value to use for PID control. Defaults to 0.0075. kd (float): Kd value to use for PID control. Defaults to 0.01. heater_segments (int): the pseudo-control range for the internal heat_controller object. Defaults to 8. """ def __init__(self, update_data_func=None, state_transition_func=None, thermostat=False, kp=0.06, ki=0.0075, kd=0.01, heater_segments=8, ext_sw_heater_drive=False): """Create variables used to send in packets to the roaster. The update data function is called when a packet is opened. The state transistion function is used by the timer thread to know what to do next. See wiki for more information on packet structure and fields.""" # constants for protocol decoding self.LOOKING_FOR_HEADER_1 = 0 self.LOOKING_FOR_HEADER_2 = 1 self.PACKET_DATA = 2 self.LOOKING_FOR_FOOTER_2 = 3 # constants for connection state monitoring self.CS_NOT_CONNECTED = -2 self.CS_ATTEMPTING_CONNECT = -1 self.CS_CONNECTING = 0 self.CS_CONNECTED = 1 # constants for connection attempt type self.CA_NONE = 0 self.CA_AUTO = 1 self.CA_SINGLE_SHOT = 2 self._create_update_data_system(update_data_func) self._create_state_transition_system(state_transition_func) self._header = sharedctypes.Array('c', b'\xAA\xAA') self._temp_unit = sharedctypes.Array('c', b'\x61\x74') self._flags = sharedctypes.Array('c', b'\x63') self._current_state = sharedctypes.Array('c', b'\x02\x01') self._footer = b'\xAA\xFA' self._fan_speed = sharedctypes.Value('i', 1) self._heat_setting = sharedctypes.Value('i', 0) self._target_temp = sharedctypes.Value('i', 150) self._current_temp = sharedctypes.Value('i', 150) self._time_remaining = sharedctypes.Value('i', 0) self._total_time = sharedctypes.Value('i', 0) self._disconnect = sharedctypes.Value('i', 0) self._teardown = sharedctypes.Value('i', 0) # for SW PWM heater setting self._heater_level = sharedctypes.Value('i', 0) # the following vars are not process-safe, do not access them # from the comm or timer threads, nor from the callbacks. self._ext_sw_heater_drive = ext_sw_heater_drive if not self._ext_sw_heater_drive: self._thermostat = thermostat else: self._thermostat = False self._pid_kp = kp self._pid_ki = ki self._pid_kd = kd self._heater_bangbang_segments = heater_segments # initialize to 'not connected' self._connected = sharedctypes.Value('i', 0) self._connect_state = sharedctypes.Value('i', self.CS_NOT_CONNECTED) # initialize to 'not trying to connect' self._attempting_connect = sharedctypes.Value('i', self.CA_NONE) # create comm process self.comm_process = mp.Process( target=self._comm, args=( self._thermostat, self._pid_kp, self._pid_ki, self._pid_kd, self._heater_bangbang_segments, self._ext_sw_heater_drive, self.update_data_event,)) self.comm_process.daemon = True self.comm_process.start() # create timer process that counts down time_remaining self.time_process = mp.Process( target=self._timer, args=( self.state_transition_event,)) self.time_process.daemon = True self.time_process.start() def _create_update_data_system( self, update_data_func, setFunc=True, createThread=False): # these callbacks cannot be called from another process in Windows. # Therefore, spawn a thread belonging to the calling process # instead. # the comm and timer processes will set events that the threads # will listen for to initiate the callbacks # only create the mp.Event once - # to mimic create_state_transition_system, for future-proofing # (in this case, currently, this is only called at __init__() time) if not hasattr(self, 'update_data_event'): self.update_data_event = mp.Event() # only create the thread.Event once - this is used to exit # the callback thread if not hasattr(self, 'update_data_callback_kill_event'): self.update_data_callback_kill_event = mp.Event() # destroy an existing thread if we had created one previously if(hasattr(self, 'update_data_thread') and self.update_data_thread is not None): # let's tear this down. To kill it, two events must be set... # in the right sequence! self.update_data_callback_kill_event.set() self.update_data_event.set() self.update_data_thread.join() if setFunc: self.update_data_func = update_data_func if self.update_data_func is not None: if createThread: self.update_data_callback_kill_event.clear() self.update_data_thread = threading.Thread( name='sr700_update_data', target=self.update_data_run, args=(self.update_data_event,), daemon=True ) else: self.update_data_thread = None def _create_state_transition_system( self, state_transition_func, setFunc=True, createThread=False): # these callbacks cannot be called from another process in Windows. # Therefore, spawn a thread belonging to the calling process # instead. # the comm and timer processes will set events that the threads # will listen for to initiate the callbacks # only create the mp.Event once - this fn can get called more # than once, by __init__() and by set_state_transition_func() if not hasattr(self, 'state_transition_event'): self.state_transition_event = mp.Event() # only create the thread.Event once - this is used to exit # the callback thread if not hasattr(self, 'state_transition_callback_kill_event'): self.state_transition_callback_kill_event = mp.Event() # destroy an existing thread if we had created one previously if(hasattr(self, 'state_transition_thread') and self.state_transition_thread is not None): # let's tear this down. To kill it, two events must be set... # in the right sequence! self.state_transition_callback_kill_event.set() self.state_transition_event.set() self.state_transition_thread.join() if setFunc: self.state_transition_func = state_transition_func if self.state_transition_func is not None: if createThread: self.state_transition_callback_kill_event.clear() self.state_transition_thread = threading.Thread( name='sr700_state_transition', target=self.state_transition_run, args=(self.state_transition_event,), daemon=True ) else: self.state_transition_thread = None @property def fan_speed(self): """Get/Set fan speed. Can be 1 to 9 inclusive. Args: Setter: fan_speed (int): fan speed Returns: Getter: (int): fan speed """ return self._fan_speed.value @fan_speed.setter def fan_speed(self, value): """Verifies the value is between 1 and 9 inclusively.""" if value not in range(1, 10): raise exceptions.RoasterValueError self._fan_speed.value = value @property def heat_setting(self): """Get/Set heat setting, 0 to 3 inclusive. 0=off, 3=high. Do not set when running freshroastsr700 in thermostat mode. Args: Setter: heat_setting (int): heat setting Returns: Getter: (int): heat setting """ return self._heat_setting.value @heat_setting.setter @property def target_temp(self): """Get/Set the target temperature for this package's built-in software PID controler. Only used when freshroastsr700 is instantiated with thermostat=True. Args: Setter: value (int): a target temperature in degF between 150 and 551. Returns: Getter: (int) target temperature in degF between 150 and 551 """ return self._target_temp.value @target_temp.setter def target_temp(self, value): if value not in range(150, 551): raise exceptions.RoasterValueError self._target_temp.value = value @property def current_temp(self): """Current temperature of the roast chamber as reported by hardware. Returns: (int) current temperature, in degrees Fahrenheit """ return self._current_temp.value @current_temp.setter def current_temp(self, value): if value not in range(150, 551): raise exceptions.RoasterValueError self._current_temp.value = value @property def time_remaining(self): """The amount of time, in seconds, remaining until a call to the state_transition_func is made. can be set to an arbitrary value up to 600 seconds at any time. When a new value is set, freshroastsr700 will count down from this new value down to 0. time_remaining is decremented to 0 only when in a roasting or cooling state. In other states, the value is not touched. Args: Setter: time_remaining (int): tiem remaining in seconds Returns: Getter: time_remaining(int): time remaining, in seconds """ return self._time_remaining.value @time_remaining.setter def time_remaining(self, value): self._time_remaining.value = value @property def total_time(self): """The total time this instance has been in roasting or cooling state sicne the latest roast began. Returns: total_time (int): time, in seconds """ return self._total_time.value @total_time.setter def total_time(self, value): self._total_time.value = value @property def heater_level(self): """A getter method for _heater_level. When thermostat=True, value is driven by built-in PID controller. When ext_sw_heater_drive=True, value is driven by calls to heater_level(). Min will always be zero, max will be heater_segments (optional instantiation parameter, defaults to 8).""" return self._heater_level.value @heater_level.setter def heater_level(self, value): """Verifies that the heater_level is between 0 and heater_segments. Can only be called when freshroastsr700 object is initialized with ext_sw_heater_drive=True. Will throw RoasterValueError otherwise.""" if self._ext_sw_heater_drive: if value not in range(0, self._heater_bangbang_segments+1): raise exceptions.RoasterValueError self._heater_level.value = value else: raise exceptions.RoasterValueError @property def connected(self): """A getter method for _connected. Indicates that the this software is currently communicating with FreshRoast SR700 hardware.""" return self._connected.value @property def connect_state(self): """A getter method for _connect_state. Indicates the current connection state this software is in for FreshRoast SR700 hardware. Returns: freshroastsr700.CS_NOT_CONNECTED the software is not currenting communicating with hardware, neither was it instructed to do so. A previously failed connection attempt will also result in this state. freshroastsr700.CS_ATTEMPTING_CONNECT A call to auto_connect() or connect() was made, and the software is currently attempting to connect to hardware. freshroastsr700.CS_CONNECTED The hardware was found, and the software is communicating with the hardware. """ return self._connect_state.value def set_state_transition_func(self, func): """THIS FUNCTION MUST BE CALLED BEFORE CALLING freshroastsr700.auto_connect(). Set, or re-set, the state transition function callback. The supplied function will be called from a separate thread within freshroastsr700, triggered by a separate, internal child process. This function will fail if the freshroastsr700 device is already connected to hardware, because by that time, the timer process and thread have already been spawned. Args: state_transition_func (func): the function to call for every state transition. A state transition occurs whenever the freshroastsr700's time_remaining value counts down to 0. Returns: nothing """ if self._connected.value: logging.error("freshroastsr700.set_state_transition_func must be " "called before freshroastsr700.auto_connect()." " Not registering func.") return False # no connection yet. so OK to set func pointer self._create_state_transition_system(func) return True def update_data_run(self, event_to_wait_on): """This is the thread that listens to an event from the comm process to execute the update_data_func callback in the context of the main process. """ # with the daemon=Turue setting, this thread should # quit 'automatically' while event_to_wait_on.wait(): event_to_wait_on.clear() if self.update_data_callback_kill_event.is_set(): return self.update_data_func() def state_transition_run(self, event_to_wait_on): """This is the thread that listens to an event from the timer process to execute the state_transition_func callback in the context of the main process. """ # with the daemon=Turue setting, this thread should # quit 'automatically' while event_to_wait_on.wait(): event_to_wait_on.clear() if self.state_transition_callback_kill_event.is_set(): return self.state_transition_func() def _connect(self): """Do not call this directly - call auto_connect() or connect(), which will call _connect() for you. Connects to the roaster and creates communication thread. Raises a RoasterLokkupError exception if the hardware is not found. """ # the following call raises a RoasterLookupException when the device # is not found. It is port = utils.find_device('1A86:5523') # on some systems, after the device port is added to the device list, # it can take up to 20 seconds after USB insertion for # the port to become available... (!) # let's put a safety timeout in here as a precaution wait_timeout = time.time() + 40.0 # should be PLENTY of time! # let's update the _connect_state while we're at it... self._connect_state.value = self.CS_CONNECTING connect_success = False while time.time() < wait_timeout: try: self._ser = serial.Serial( port=port, baudrate=9600, bytesize=8, parity='N', stopbits=1.5, timeout=0.25, xonxoff=False, rtscts=False, dsrdtr=False) connect_success = True break except serial.SerialException: time.sleep(0.5) if not connect_success: # timeout on attempts raise exceptions.RoasterLookupError self._initialize() def _initialize(self): """Sends the initialization packet to the roaster.""" self._header.value = b'\xAA\x55' self._current_state.value = b'\x00\x00' s = self._generate_packet() self._ser.write(s) self._header.value = b'\xAA\xAA' self._current_state.value = b'\x02\x01' return self._read_existing_recipe() def _write_to_device(self): success = False try: packet = self._generate_packet() logging.debug('WR: ' + str(binascii.hexlify(packet))) self._ser.write(packet) success = True except serial.serialutil.SerialException: logging.error('caught serial exception writing') return success def _read_from_device(self): r = [] footer_reached = False while len(r) < 14 and footer_reached is False: r.append(self._ser.read(1)) if len(r) >= 2 and b''.join(r)[-2:] == self._footer: footer_reached = True logging.debug('RD: ' + str(binascii.hexlify(b''.join(r)))) return b''.join(r) def _read_existing_recipe(self): existing_recipe = [] end_of_recipe = False while not end_of_recipe: bytes_waiting = self._ser.in_waiting if bytes_waiting < 14: # still need to write to device every .25sec it seems time.sleep(0.25) self._write_to_device() else: while (bytes_waiting // 14) > 0: r = self._read_from_device() bytes_waiting = self._ser.in_waiting if len(r) < 14: logging.warn('short packet length') else: existing_recipe.append(r) if r[4:5] == b'\xAF' or r[4:5] == b'\x00': end_of_recipe = True continue return existing_recipe def connect(self): """Attempt to connect to hardware immediately. Will not retry. Check freshroastsr700.connected or freshroastsr700.connect_state to verify result. Raises: freshroastsr700.exeptions.RoasterLookupError No hardware connected to the computer. """ self._start_connect(self.CA_SINGLE_SHOT) while(self._connect_state.value == self.CS_ATTEMPTING_CONNECT or self._connect_state.value == self.CS_CONNECTING): time.sleep(0.1) if self.CS_CONNECTED != self._connect_state.value: raise exceptions.RoasterLookupError def auto_connect(self): """Starts a thread that will automatically connect to the roaster when it is plugged in.""" self._start_connect(self.CA_AUTO) def _start_connect(self, connect_type): """Starts the connection process, as called (internally) from the user context, either from auto_connect() or connect(). Never call this from the _comm() process context. """ if self._connect_state.value != self.CS_NOT_CONNECTED: # already done or in process, assume success return self._connected.value = 0 self._connect_state.value = self.CS_ATTEMPTING_CONNECT # tell comm process to attempt connection self._attempting_connect.value = connect_type # EXTREMELY IMPORTANT - for this to work at all in Windows, # where the above processes are spawned (vs forked in Unix), # the thread objects (as sattributes of this object) must be # assigned to this object AFTER we have spawned the processes. # That way, multiprocessing can pickle the freshroastsr700 # successfully. (It can't pickle thread-related stuff.) if self.update_data_func is not None: # Need to launch the thread that will listen to the event self._create_update_data_system( None, setFunc=False, createThread=True) self.update_data_thread.start() if self.state_transition_func is not None: # Need to launch the thread that will listen to the event self._create_state_transition_system( None, setFunc=False, createThread=True) self.state_transition_thread.start() def _auto_connect(self): """Attempts to connect to the roaster every quarter of a second.""" while not self._teardown.value: try: self._connect() return True except exceptions.RoasterLookupError: time.sleep(.25) return False def disconnect(self): """Stops the communication loop to the roaster. Note that this will not actually stop the roaster itself.""" self._disconnect.value = 1 def terminate(self): """Stops the communication loop to the roaster and closes down all communication processes. Note that this will not actually stop the roaster itself. You will need to instantiate a new freshroastsr700 object after calling this function, in order to re-start communications with the hardware. """ self.disconnect() self._teardown.value = 1 def _comm(self, thermostat=False, kp=0.06, ki=0.0075, kd=0.01, heater_segments=8, ext_sw_heater_drive=False, update_data_event=None): """Do not call this directly - call auto_connect(), which will spawn comm() for you. This is the main communications loop to the roaster. whenever a valid packet is received from the device, if an update_data_event is available, it will be signalled. Args: thermostat (bool): thermostat mode. if set to True, turns on thermostat mode. In thermostat mode, freshroastsr700 takes control of heat_setting and does software PID control to hit the demanded target_temp. ext_sw_heater_drive (bool): enable direct control over the internal heat_controller object. Defaults to False. When set to True, the thermostat field is IGNORED, and assumed to be False. Direct control over the software heater_level means that the PID controller cannot control the heater. Since thermostat and ext_sw_heater_drive cannot be allowed to both be True, this arg is given precedence over the thermostat arg. kp (float): Kp value to use for PID control. Defaults to 0.06. ki (float): Ki value to use for PID control. Defaults to 0.0075. kd (float): Kd value to use for PID control. Defaults to 0.01. heater_segments (int): the pseudo-control range for the internal heat_controller object. Defaults to 8. update_data_event (multiprocessing.Event): If set, allows the comm_process to signal to the parent process that new device data is available. Returns: nothing """ # since this process is started with daemon=True, it should exit # when the owning process terminates. Therefore, safe to loop forever. while not self._teardown.value: # waiting for command to attempt connect # print( "waiting for command to attempt connect") while self._attempting_connect.value == self.CA_NONE: time.sleep(0.25) if self._teardown.value: break # if we're tearing down, bail now. if self._teardown.value: break # we got the command to attempt to connect # change state to 'attempting_connect' self._connect_state.value = self.CS_ATTEMPTING_CONNECT # attempt connection if self.CA_AUTO == self._attempting_connect.value: # this call will block until a connection is achieved # it will also set _connect_state to CS_CONNECTING # if appropriate if self._auto_connect(): # when we unblock, it is an indication of a successful # connection self._connected.value = 1 self._connect_state.value = self.CS_CONNECTED else: # failure, normally due to a timeout self._connected.value = 0 self._connect_state.value = self.CS_NOT_CONNECTED # we failed to connect - start over from the top # reset flag self._attempting_connect.value = self.CA_NONE continue elif self.CA_SINGLE_SHOT == self._attempting_connect.value: # try once, now, if failure, start teh big loop over try: self._connect() self._connected.value = 1 self._connect_state.value = self.CS_CONNECTED except exceptions.RoasterLookupError: self._connected.value = 0 self._connect_state.value = self.CS_NOT_CONNECTED if self._connect_state.value != self.CS_CONNECTED: # we failed to connect - start over from the top # reset flag self._attempting_connect.value = self.CA_NONE continue else: # shouldn't be here # reset flag self._attempting_connect.value = self.CA_NONE continue # We are connected! # print( "We are connected!") # reset flag right away self._attempting_connect.value = self.CA_NONE # Initialize PID controller if thermostat function was specified at # init time pidc = None heater = None if(thermostat): pidc = pid.PID(kp, ki, kd, Output_max=heater_segments, Output_min=0 ) if thermostat or ext_sw_heater_drive: heater = heat_controller(number_of_segments=heater_segments) read_state = self.LOOKING_FOR_HEADER_1 r = [] write_errors = 0 read_errors = 0 while not self._disconnect.value: start = datetime.datetime.now() # write to device if not self._write_to_device(): logging.error('comm - _write_to_device() failed!') write_errors += 1 if write_errors > 3: # it's time to consider the device as being "gone" logging.error('comm - 3 successive write ' 'failures, disconnecting.') self._disconnect.value = 1 continue else: # reset write_errors write_errors = 0 # read from device try: while self._ser.in_waiting: _byte = self._ser.read(1) read_state, r, err = ( self._process_reponse_byte( read_state, _byte, r, update_data_event)) except IOError: # typically happens when device is suddenly unplugged logging.error('comm - read from device failed!') read_errors += 1 if write_errors > 3: # it's time to consider the device as being "gone" logging.error('comm - 3 successive read ' 'failures, disconnecting.') self._disconnect.value = 1 continue else: read_errors = 0 # next, drive SW heater when using # thermostat mode (PID controller calcs) # or in external sw heater drive mode, # when roasting. if thermostat or ext_sw_heater_drive: if 'roasting' == self.get_roaster_state(): if heater.about_to_rollover(): # it's time to use the PID controller value # and set new output level on heater! if ext_sw_heater_drive: # read user-supplied value heater.heat_level = self._heater_level.value else: # thermostat output = pidc.update( self.current_temp, self.target_temp) heater.heat_level = output # make this number visible to other processes... self._heater_level.value = heater.heat_level # read bang-bang heater output array element & apply it if heater.generate_bangbang_output(): # ON self.heat_setting = 3 else: # OFF self.heat_setting = 0 else: # for all other states, heat_level = OFF heater.heat_level = 0 # make this number visible to other processes... self._heater_level.value = heater.heat_level self.heat_setting = 0 # calculate sleep time to stick to 0.25sec period comp_time = datetime.datetime.now() - start sleep_duration = 0.25 - comp_time.total_seconds() if sleep_duration > 0: time.sleep(sleep_duration) self._ser.close() # reset disconnect flag self._disconnect.value = 0 # reset connection values self._connected.value = 0 self._connect_state.value = self.CS_NOT_CONNECTED # print("We are disconnected.") def _process_reponse_byte(self, read_state, _byte, r, update_data_event): err = False if self.LOOKING_FOR_HEADER_1 == read_state: if b'\xAA' == _byte: read_state = self.LOOKING_FOR_HEADER_2 elif self.LOOKING_FOR_HEADER_2 == read_state: if b'\xAA' == _byte: read_state = self.PACKET_DATA # reset packet array now... r = [] else: read_state = self.LOOKING_FOR_HEADER_1 elif self.PACKET_DATA == read_state: if b'\xAA' == _byte: # this could be the start of an end of packet marker read_state = self.LOOKING_FOR_FOOTER_2 else: r.append(_byte) # SR700 FW bug - if current temp is 250 degF (0xFA), # the FW does not transmit the footer at all. # fake the footer here. if(len(r) == 10 and b'\xFA' == _byte): # we will 'fake' a footer to make this decoder work # as intended read_state, r, _ = ( self._process_reponse_byte( read_state, b'\xAA', r, update_data_event)) read_state, r, err = ( self._process_reponse_byte( read_state, b'\xFA', r, update_data_event)) elif self.LOOKING_FOR_FOOTER_2 == read_state: if b'\xFA' == _byte: # OK we have a full packet - PROCESS PACKET err = self._process_response_data(r, update_data_event) read_state = self.LOOKING_FOR_HEADER_1 else: # the last byte was not the beginning of the footer r.append(b'\xAA') read_state = self.PACKET_DATA read_state, r, err = self._process_reponse_byte( read_state, _byte, r, update_data_event) else: # error state, shouldn't happen... logging.error('_process_reponse_byte - invalid read_state %d' % read_state) read_state = self.LOOKING_FOR_HEADER_1 err = True return read_state, r, err def _process_response_data(self, r, update_data_event): err = False if len(r) != 10: logging.warn('read packet data len not 10, got: %d' % len(r)) logging.warn('RD: ' + str(binascii.hexlify(b''.join(r)))) err = True else: temp = struct.unpack(">H", b''.join(r[8:10]))[0] if(temp == 65280): self.current_temp = 150 elif(temp > 550 or temp < 150): logging.warn('temperature out of range: reinitializing...') self._initialize() err = True return else: self.current_temp = temp if(update_data_event is not None): update_data_event.set() return err def _timer(self, state_transition_event=None): """Timer loop used to keep track of the time while roasting or cooling. If the time remaining reaches zero, the roaster will call the supplied state transistion function or the roaster will be set to the idle state.""" while not self._teardown.value: state = self.get_roaster_state() if(state == 'roasting' or state == 'cooling'): time.sleep(1) self.total_time += 1 if(self.time_remaining > 0): self.time_remaining -= 1 else: if(state_transition_event is not None): state_transition_event.set() else: self.idle() else: time.sleep(0.01) def get_roaster_state(self): """Returns a string based upon the current state of the roaster. Will raise an exception if the state is unknown. Returns: 'idle' if idle, 'sleeping' if sleeping, 'cooling' if cooling, 'roasting' if roasting, 'connecting' if in hardware connection phase, 'unknown' otherwise """ value = self._current_state.value if(value == b'\x02\x01'): return 'idle' elif(value == b'\x04\x04'): return 'cooling' elif(value == b'\x08\x01'): return 'sleeping' # handle null bytes as empty strings elif(value == b'\x00\x00' or value == b''): return 'connecting' elif(value == b'\x04\x02'): return 'roasting' else: return 'unknown' def _generate_packet(self): """Generates a packet based upon the current class variables. Note that current temperature is not sent, as the original application sent zeros to the roaster for the current temperature.""" roaster_time = utils.seconds_to_float(self._time_remaining.value) packet = ( self._header.value + self._temp_unit.value + self._flags.value + self._current_state.value + struct.pack(">B", self._fan_speed.value) + struct.pack(">B", int(round(roaster_time * 10.0))) + struct.pack(">B", self._heat_setting.value) + b'\x00\x00' + self._footer) return packet def idle(self): """Sets the current state of the roaster to idle.""" self._current_state.value = b'\x02\x01' def roast(self): """Sets the current state of the roaster to roast and begins roasting.""" self._current_state.value = b'\x04\x02' def cool(self): """Sets the current state of the roaster to cool. The roaster expects that cool will be run after roast, and will not work as expected if ran before.""" self._current_state.value = b'\x04\x04' def sleep(self): """Sets the current state of the roaster to sleep. Different than idle in that this will set double dashes on the roaster display rather than digits.""" self._current_state.value = b'\x08\x01'
Roastero/freshroastsr700
freshroastsr700/__init__.py
freshroastsr700.heater_level
python
def heater_level(self, value): if self._ext_sw_heater_drive: if value not in range(0, self._heater_bangbang_segments+1): raise exceptions.RoasterValueError self._heater_level.value = value else: raise exceptions.RoasterValueError
Verifies that the heater_level is between 0 and heater_segments. Can only be called when freshroastsr700 object is initialized with ext_sw_heater_drive=True. Will throw RoasterValueError otherwise.
train
https://github.com/Roastero/freshroastsr700/blob/49cf4961444c0f56d051d5ac5088ace480b54f02/freshroastsr700/__init__.py#L352-L362
null
class freshroastsr700(object): """A class to interface with a freshroastsr700 coffee roaster. Args: update_data_func (func): A function to call when this object receives new data from the hardware. Defaults to None. state_transition_func (func): A function to call when time_remaining counts down to 0 and the device is either in roasting or cooling state. Defaults to None. thermostat (bool): thermostat mode. if set to True, turns on thermostat mode. In thermostat mode, freshroastsr700 takes control of heat_setting and does software PID control to hit the demanded target_temp. Defaults to False. ext_sw_heater_drive (bool): enable direct control over the internal heat_controller object. Defaults to False. When set to True, the thermostat field is IGNORED, and assumed to be False. Direct control over the software heater_level means that the freshroastsr700's PID controller cannot control the heater. Since thermostat and ext_sw_heater_drive cannot be allowed to both be True, this arg is given precedence over the thermostat arg. Note that (thermostat=False, ext_sw_heater_drive=False), (thermostat=True, ext_sw_heater_drive=False), (thermostat=False, ext_sw_heater_drive=True), are all acceptable arg combinations. Only the (thermostat=True, ext_sw_heater_drive=True), cominbation is not allowed, and this software will set thermostat=False in that case. kp (float): Kp value to use for PID control. Defaults to 0.06. ki (float): Ki value to use for PID control. Defaults to 0.0075. kd (float): Kd value to use for PID control. Defaults to 0.01. heater_segments (int): the pseudo-control range for the internal heat_controller object. Defaults to 8. """ def __init__(self, update_data_func=None, state_transition_func=None, thermostat=False, kp=0.06, ki=0.0075, kd=0.01, heater_segments=8, ext_sw_heater_drive=False): """Create variables used to send in packets to the roaster. The update data function is called when a packet is opened. The state transistion function is used by the timer thread to know what to do next. See wiki for more information on packet structure and fields.""" # constants for protocol decoding self.LOOKING_FOR_HEADER_1 = 0 self.LOOKING_FOR_HEADER_2 = 1 self.PACKET_DATA = 2 self.LOOKING_FOR_FOOTER_2 = 3 # constants for connection state monitoring self.CS_NOT_CONNECTED = -2 self.CS_ATTEMPTING_CONNECT = -1 self.CS_CONNECTING = 0 self.CS_CONNECTED = 1 # constants for connection attempt type self.CA_NONE = 0 self.CA_AUTO = 1 self.CA_SINGLE_SHOT = 2 self._create_update_data_system(update_data_func) self._create_state_transition_system(state_transition_func) self._header = sharedctypes.Array('c', b'\xAA\xAA') self._temp_unit = sharedctypes.Array('c', b'\x61\x74') self._flags = sharedctypes.Array('c', b'\x63') self._current_state = sharedctypes.Array('c', b'\x02\x01') self._footer = b'\xAA\xFA' self._fan_speed = sharedctypes.Value('i', 1) self._heat_setting = sharedctypes.Value('i', 0) self._target_temp = sharedctypes.Value('i', 150) self._current_temp = sharedctypes.Value('i', 150) self._time_remaining = sharedctypes.Value('i', 0) self._total_time = sharedctypes.Value('i', 0) self._disconnect = sharedctypes.Value('i', 0) self._teardown = sharedctypes.Value('i', 0) # for SW PWM heater setting self._heater_level = sharedctypes.Value('i', 0) # the following vars are not process-safe, do not access them # from the comm or timer threads, nor from the callbacks. self._ext_sw_heater_drive = ext_sw_heater_drive if not self._ext_sw_heater_drive: self._thermostat = thermostat else: self._thermostat = False self._pid_kp = kp self._pid_ki = ki self._pid_kd = kd self._heater_bangbang_segments = heater_segments # initialize to 'not connected' self._connected = sharedctypes.Value('i', 0) self._connect_state = sharedctypes.Value('i', self.CS_NOT_CONNECTED) # initialize to 'not trying to connect' self._attempting_connect = sharedctypes.Value('i', self.CA_NONE) # create comm process self.comm_process = mp.Process( target=self._comm, args=( self._thermostat, self._pid_kp, self._pid_ki, self._pid_kd, self._heater_bangbang_segments, self._ext_sw_heater_drive, self.update_data_event,)) self.comm_process.daemon = True self.comm_process.start() # create timer process that counts down time_remaining self.time_process = mp.Process( target=self._timer, args=( self.state_transition_event,)) self.time_process.daemon = True self.time_process.start() def _create_update_data_system( self, update_data_func, setFunc=True, createThread=False): # these callbacks cannot be called from another process in Windows. # Therefore, spawn a thread belonging to the calling process # instead. # the comm and timer processes will set events that the threads # will listen for to initiate the callbacks # only create the mp.Event once - # to mimic create_state_transition_system, for future-proofing # (in this case, currently, this is only called at __init__() time) if not hasattr(self, 'update_data_event'): self.update_data_event = mp.Event() # only create the thread.Event once - this is used to exit # the callback thread if not hasattr(self, 'update_data_callback_kill_event'): self.update_data_callback_kill_event = mp.Event() # destroy an existing thread if we had created one previously if(hasattr(self, 'update_data_thread') and self.update_data_thread is not None): # let's tear this down. To kill it, two events must be set... # in the right sequence! self.update_data_callback_kill_event.set() self.update_data_event.set() self.update_data_thread.join() if setFunc: self.update_data_func = update_data_func if self.update_data_func is not None: if createThread: self.update_data_callback_kill_event.clear() self.update_data_thread = threading.Thread( name='sr700_update_data', target=self.update_data_run, args=(self.update_data_event,), daemon=True ) else: self.update_data_thread = None def _create_state_transition_system( self, state_transition_func, setFunc=True, createThread=False): # these callbacks cannot be called from another process in Windows. # Therefore, spawn a thread belonging to the calling process # instead. # the comm and timer processes will set events that the threads # will listen for to initiate the callbacks # only create the mp.Event once - this fn can get called more # than once, by __init__() and by set_state_transition_func() if not hasattr(self, 'state_transition_event'): self.state_transition_event = mp.Event() # only create the thread.Event once - this is used to exit # the callback thread if not hasattr(self, 'state_transition_callback_kill_event'): self.state_transition_callback_kill_event = mp.Event() # destroy an existing thread if we had created one previously if(hasattr(self, 'state_transition_thread') and self.state_transition_thread is not None): # let's tear this down. To kill it, two events must be set... # in the right sequence! self.state_transition_callback_kill_event.set() self.state_transition_event.set() self.state_transition_thread.join() if setFunc: self.state_transition_func = state_transition_func if self.state_transition_func is not None: if createThread: self.state_transition_callback_kill_event.clear() self.state_transition_thread = threading.Thread( name='sr700_state_transition', target=self.state_transition_run, args=(self.state_transition_event,), daemon=True ) else: self.state_transition_thread = None @property def fan_speed(self): """Get/Set fan speed. Can be 1 to 9 inclusive. Args: Setter: fan_speed (int): fan speed Returns: Getter: (int): fan speed """ return self._fan_speed.value @fan_speed.setter def fan_speed(self, value): """Verifies the value is between 1 and 9 inclusively.""" if value not in range(1, 10): raise exceptions.RoasterValueError self._fan_speed.value = value @property def heat_setting(self): """Get/Set heat setting, 0 to 3 inclusive. 0=off, 3=high. Do not set when running freshroastsr700 in thermostat mode. Args: Setter: heat_setting (int): heat setting Returns: Getter: (int): heat setting """ return self._heat_setting.value @heat_setting.setter def heat_setting(self, value): """Verifies that the heat setting is between 0 and 3.""" if value not in range(0, 4): raise exceptions.RoasterValueError self._heat_setting.value = value @property def target_temp(self): """Get/Set the target temperature for this package's built-in software PID controler. Only used when freshroastsr700 is instantiated with thermostat=True. Args: Setter: value (int): a target temperature in degF between 150 and 551. Returns: Getter: (int) target temperature in degF between 150 and 551 """ return self._target_temp.value @target_temp.setter def target_temp(self, value): if value not in range(150, 551): raise exceptions.RoasterValueError self._target_temp.value = value @property def current_temp(self): """Current temperature of the roast chamber as reported by hardware. Returns: (int) current temperature, in degrees Fahrenheit """ return self._current_temp.value @current_temp.setter def current_temp(self, value): if value not in range(150, 551): raise exceptions.RoasterValueError self._current_temp.value = value @property def time_remaining(self): """The amount of time, in seconds, remaining until a call to the state_transition_func is made. can be set to an arbitrary value up to 600 seconds at any time. When a new value is set, freshroastsr700 will count down from this new value down to 0. time_remaining is decremented to 0 only when in a roasting or cooling state. In other states, the value is not touched. Args: Setter: time_remaining (int): tiem remaining in seconds Returns: Getter: time_remaining(int): time remaining, in seconds """ return self._time_remaining.value @time_remaining.setter def time_remaining(self, value): self._time_remaining.value = value @property def total_time(self): """The total time this instance has been in roasting or cooling state sicne the latest roast began. Returns: total_time (int): time, in seconds """ return self._total_time.value @total_time.setter def total_time(self, value): self._total_time.value = value @property def heater_level(self): """A getter method for _heater_level. When thermostat=True, value is driven by built-in PID controller. When ext_sw_heater_drive=True, value is driven by calls to heater_level(). Min will always be zero, max will be heater_segments (optional instantiation parameter, defaults to 8).""" return self._heater_level.value @heater_level.setter @property def connected(self): """A getter method for _connected. Indicates that the this software is currently communicating with FreshRoast SR700 hardware.""" return self._connected.value @property def connect_state(self): """A getter method for _connect_state. Indicates the current connection state this software is in for FreshRoast SR700 hardware. Returns: freshroastsr700.CS_NOT_CONNECTED the software is not currenting communicating with hardware, neither was it instructed to do so. A previously failed connection attempt will also result in this state. freshroastsr700.CS_ATTEMPTING_CONNECT A call to auto_connect() or connect() was made, and the software is currently attempting to connect to hardware. freshroastsr700.CS_CONNECTED The hardware was found, and the software is communicating with the hardware. """ return self._connect_state.value def set_state_transition_func(self, func): """THIS FUNCTION MUST BE CALLED BEFORE CALLING freshroastsr700.auto_connect(). Set, or re-set, the state transition function callback. The supplied function will be called from a separate thread within freshroastsr700, triggered by a separate, internal child process. This function will fail if the freshroastsr700 device is already connected to hardware, because by that time, the timer process and thread have already been spawned. Args: state_transition_func (func): the function to call for every state transition. A state transition occurs whenever the freshroastsr700's time_remaining value counts down to 0. Returns: nothing """ if self._connected.value: logging.error("freshroastsr700.set_state_transition_func must be " "called before freshroastsr700.auto_connect()." " Not registering func.") return False # no connection yet. so OK to set func pointer self._create_state_transition_system(func) return True def update_data_run(self, event_to_wait_on): """This is the thread that listens to an event from the comm process to execute the update_data_func callback in the context of the main process. """ # with the daemon=Turue setting, this thread should # quit 'automatically' while event_to_wait_on.wait(): event_to_wait_on.clear() if self.update_data_callback_kill_event.is_set(): return self.update_data_func() def state_transition_run(self, event_to_wait_on): """This is the thread that listens to an event from the timer process to execute the state_transition_func callback in the context of the main process. """ # with the daemon=Turue setting, this thread should # quit 'automatically' while event_to_wait_on.wait(): event_to_wait_on.clear() if self.state_transition_callback_kill_event.is_set(): return self.state_transition_func() def _connect(self): """Do not call this directly - call auto_connect() or connect(), which will call _connect() for you. Connects to the roaster and creates communication thread. Raises a RoasterLokkupError exception if the hardware is not found. """ # the following call raises a RoasterLookupException when the device # is not found. It is port = utils.find_device('1A86:5523') # on some systems, after the device port is added to the device list, # it can take up to 20 seconds after USB insertion for # the port to become available... (!) # let's put a safety timeout in here as a precaution wait_timeout = time.time() + 40.0 # should be PLENTY of time! # let's update the _connect_state while we're at it... self._connect_state.value = self.CS_CONNECTING connect_success = False while time.time() < wait_timeout: try: self._ser = serial.Serial( port=port, baudrate=9600, bytesize=8, parity='N', stopbits=1.5, timeout=0.25, xonxoff=False, rtscts=False, dsrdtr=False) connect_success = True break except serial.SerialException: time.sleep(0.5) if not connect_success: # timeout on attempts raise exceptions.RoasterLookupError self._initialize() def _initialize(self): """Sends the initialization packet to the roaster.""" self._header.value = b'\xAA\x55' self._current_state.value = b'\x00\x00' s = self._generate_packet() self._ser.write(s) self._header.value = b'\xAA\xAA' self._current_state.value = b'\x02\x01' return self._read_existing_recipe() def _write_to_device(self): success = False try: packet = self._generate_packet() logging.debug('WR: ' + str(binascii.hexlify(packet))) self._ser.write(packet) success = True except serial.serialutil.SerialException: logging.error('caught serial exception writing') return success def _read_from_device(self): r = [] footer_reached = False while len(r) < 14 and footer_reached is False: r.append(self._ser.read(1)) if len(r) >= 2 and b''.join(r)[-2:] == self._footer: footer_reached = True logging.debug('RD: ' + str(binascii.hexlify(b''.join(r)))) return b''.join(r) def _read_existing_recipe(self): existing_recipe = [] end_of_recipe = False while not end_of_recipe: bytes_waiting = self._ser.in_waiting if bytes_waiting < 14: # still need to write to device every .25sec it seems time.sleep(0.25) self._write_to_device() else: while (bytes_waiting // 14) > 0: r = self._read_from_device() bytes_waiting = self._ser.in_waiting if len(r) < 14: logging.warn('short packet length') else: existing_recipe.append(r) if r[4:5] == b'\xAF' or r[4:5] == b'\x00': end_of_recipe = True continue return existing_recipe def connect(self): """Attempt to connect to hardware immediately. Will not retry. Check freshroastsr700.connected or freshroastsr700.connect_state to verify result. Raises: freshroastsr700.exeptions.RoasterLookupError No hardware connected to the computer. """ self._start_connect(self.CA_SINGLE_SHOT) while(self._connect_state.value == self.CS_ATTEMPTING_CONNECT or self._connect_state.value == self.CS_CONNECTING): time.sleep(0.1) if self.CS_CONNECTED != self._connect_state.value: raise exceptions.RoasterLookupError def auto_connect(self): """Starts a thread that will automatically connect to the roaster when it is plugged in.""" self._start_connect(self.CA_AUTO) def _start_connect(self, connect_type): """Starts the connection process, as called (internally) from the user context, either from auto_connect() or connect(). Never call this from the _comm() process context. """ if self._connect_state.value != self.CS_NOT_CONNECTED: # already done or in process, assume success return self._connected.value = 0 self._connect_state.value = self.CS_ATTEMPTING_CONNECT # tell comm process to attempt connection self._attempting_connect.value = connect_type # EXTREMELY IMPORTANT - for this to work at all in Windows, # where the above processes are spawned (vs forked in Unix), # the thread objects (as sattributes of this object) must be # assigned to this object AFTER we have spawned the processes. # That way, multiprocessing can pickle the freshroastsr700 # successfully. (It can't pickle thread-related stuff.) if self.update_data_func is not None: # Need to launch the thread that will listen to the event self._create_update_data_system( None, setFunc=False, createThread=True) self.update_data_thread.start() if self.state_transition_func is not None: # Need to launch the thread that will listen to the event self._create_state_transition_system( None, setFunc=False, createThread=True) self.state_transition_thread.start() def _auto_connect(self): """Attempts to connect to the roaster every quarter of a second.""" while not self._teardown.value: try: self._connect() return True except exceptions.RoasterLookupError: time.sleep(.25) return False def disconnect(self): """Stops the communication loop to the roaster. Note that this will not actually stop the roaster itself.""" self._disconnect.value = 1 def terminate(self): """Stops the communication loop to the roaster and closes down all communication processes. Note that this will not actually stop the roaster itself. You will need to instantiate a new freshroastsr700 object after calling this function, in order to re-start communications with the hardware. """ self.disconnect() self._teardown.value = 1 def _comm(self, thermostat=False, kp=0.06, ki=0.0075, kd=0.01, heater_segments=8, ext_sw_heater_drive=False, update_data_event=None): """Do not call this directly - call auto_connect(), which will spawn comm() for you. This is the main communications loop to the roaster. whenever a valid packet is received from the device, if an update_data_event is available, it will be signalled. Args: thermostat (bool): thermostat mode. if set to True, turns on thermostat mode. In thermostat mode, freshroastsr700 takes control of heat_setting and does software PID control to hit the demanded target_temp. ext_sw_heater_drive (bool): enable direct control over the internal heat_controller object. Defaults to False. When set to True, the thermostat field is IGNORED, and assumed to be False. Direct control over the software heater_level means that the PID controller cannot control the heater. Since thermostat and ext_sw_heater_drive cannot be allowed to both be True, this arg is given precedence over the thermostat arg. kp (float): Kp value to use for PID control. Defaults to 0.06. ki (float): Ki value to use for PID control. Defaults to 0.0075. kd (float): Kd value to use for PID control. Defaults to 0.01. heater_segments (int): the pseudo-control range for the internal heat_controller object. Defaults to 8. update_data_event (multiprocessing.Event): If set, allows the comm_process to signal to the parent process that new device data is available. Returns: nothing """ # since this process is started with daemon=True, it should exit # when the owning process terminates. Therefore, safe to loop forever. while not self._teardown.value: # waiting for command to attempt connect # print( "waiting for command to attempt connect") while self._attempting_connect.value == self.CA_NONE: time.sleep(0.25) if self._teardown.value: break # if we're tearing down, bail now. if self._teardown.value: break # we got the command to attempt to connect # change state to 'attempting_connect' self._connect_state.value = self.CS_ATTEMPTING_CONNECT # attempt connection if self.CA_AUTO == self._attempting_connect.value: # this call will block until a connection is achieved # it will also set _connect_state to CS_CONNECTING # if appropriate if self._auto_connect(): # when we unblock, it is an indication of a successful # connection self._connected.value = 1 self._connect_state.value = self.CS_CONNECTED else: # failure, normally due to a timeout self._connected.value = 0 self._connect_state.value = self.CS_NOT_CONNECTED # we failed to connect - start over from the top # reset flag self._attempting_connect.value = self.CA_NONE continue elif self.CA_SINGLE_SHOT == self._attempting_connect.value: # try once, now, if failure, start teh big loop over try: self._connect() self._connected.value = 1 self._connect_state.value = self.CS_CONNECTED except exceptions.RoasterLookupError: self._connected.value = 0 self._connect_state.value = self.CS_NOT_CONNECTED if self._connect_state.value != self.CS_CONNECTED: # we failed to connect - start over from the top # reset flag self._attempting_connect.value = self.CA_NONE continue else: # shouldn't be here # reset flag self._attempting_connect.value = self.CA_NONE continue # We are connected! # print( "We are connected!") # reset flag right away self._attempting_connect.value = self.CA_NONE # Initialize PID controller if thermostat function was specified at # init time pidc = None heater = None if(thermostat): pidc = pid.PID(kp, ki, kd, Output_max=heater_segments, Output_min=0 ) if thermostat or ext_sw_heater_drive: heater = heat_controller(number_of_segments=heater_segments) read_state = self.LOOKING_FOR_HEADER_1 r = [] write_errors = 0 read_errors = 0 while not self._disconnect.value: start = datetime.datetime.now() # write to device if not self._write_to_device(): logging.error('comm - _write_to_device() failed!') write_errors += 1 if write_errors > 3: # it's time to consider the device as being "gone" logging.error('comm - 3 successive write ' 'failures, disconnecting.') self._disconnect.value = 1 continue else: # reset write_errors write_errors = 0 # read from device try: while self._ser.in_waiting: _byte = self._ser.read(1) read_state, r, err = ( self._process_reponse_byte( read_state, _byte, r, update_data_event)) except IOError: # typically happens when device is suddenly unplugged logging.error('comm - read from device failed!') read_errors += 1 if write_errors > 3: # it's time to consider the device as being "gone" logging.error('comm - 3 successive read ' 'failures, disconnecting.') self._disconnect.value = 1 continue else: read_errors = 0 # next, drive SW heater when using # thermostat mode (PID controller calcs) # or in external sw heater drive mode, # when roasting. if thermostat or ext_sw_heater_drive: if 'roasting' == self.get_roaster_state(): if heater.about_to_rollover(): # it's time to use the PID controller value # and set new output level on heater! if ext_sw_heater_drive: # read user-supplied value heater.heat_level = self._heater_level.value else: # thermostat output = pidc.update( self.current_temp, self.target_temp) heater.heat_level = output # make this number visible to other processes... self._heater_level.value = heater.heat_level # read bang-bang heater output array element & apply it if heater.generate_bangbang_output(): # ON self.heat_setting = 3 else: # OFF self.heat_setting = 0 else: # for all other states, heat_level = OFF heater.heat_level = 0 # make this number visible to other processes... self._heater_level.value = heater.heat_level self.heat_setting = 0 # calculate sleep time to stick to 0.25sec period comp_time = datetime.datetime.now() - start sleep_duration = 0.25 - comp_time.total_seconds() if sleep_duration > 0: time.sleep(sleep_duration) self._ser.close() # reset disconnect flag self._disconnect.value = 0 # reset connection values self._connected.value = 0 self._connect_state.value = self.CS_NOT_CONNECTED # print("We are disconnected.") def _process_reponse_byte(self, read_state, _byte, r, update_data_event): err = False if self.LOOKING_FOR_HEADER_1 == read_state: if b'\xAA' == _byte: read_state = self.LOOKING_FOR_HEADER_2 elif self.LOOKING_FOR_HEADER_2 == read_state: if b'\xAA' == _byte: read_state = self.PACKET_DATA # reset packet array now... r = [] else: read_state = self.LOOKING_FOR_HEADER_1 elif self.PACKET_DATA == read_state: if b'\xAA' == _byte: # this could be the start of an end of packet marker read_state = self.LOOKING_FOR_FOOTER_2 else: r.append(_byte) # SR700 FW bug - if current temp is 250 degF (0xFA), # the FW does not transmit the footer at all. # fake the footer here. if(len(r) == 10 and b'\xFA' == _byte): # we will 'fake' a footer to make this decoder work # as intended read_state, r, _ = ( self._process_reponse_byte( read_state, b'\xAA', r, update_data_event)) read_state, r, err = ( self._process_reponse_byte( read_state, b'\xFA', r, update_data_event)) elif self.LOOKING_FOR_FOOTER_2 == read_state: if b'\xFA' == _byte: # OK we have a full packet - PROCESS PACKET err = self._process_response_data(r, update_data_event) read_state = self.LOOKING_FOR_HEADER_1 else: # the last byte was not the beginning of the footer r.append(b'\xAA') read_state = self.PACKET_DATA read_state, r, err = self._process_reponse_byte( read_state, _byte, r, update_data_event) else: # error state, shouldn't happen... logging.error('_process_reponse_byte - invalid read_state %d' % read_state) read_state = self.LOOKING_FOR_HEADER_1 err = True return read_state, r, err def _process_response_data(self, r, update_data_event): err = False if len(r) != 10: logging.warn('read packet data len not 10, got: %d' % len(r)) logging.warn('RD: ' + str(binascii.hexlify(b''.join(r)))) err = True else: temp = struct.unpack(">H", b''.join(r[8:10]))[0] if(temp == 65280): self.current_temp = 150 elif(temp > 550 or temp < 150): logging.warn('temperature out of range: reinitializing...') self._initialize() err = True return else: self.current_temp = temp if(update_data_event is not None): update_data_event.set() return err def _timer(self, state_transition_event=None): """Timer loop used to keep track of the time while roasting or cooling. If the time remaining reaches zero, the roaster will call the supplied state transistion function or the roaster will be set to the idle state.""" while not self._teardown.value: state = self.get_roaster_state() if(state == 'roasting' or state == 'cooling'): time.sleep(1) self.total_time += 1 if(self.time_remaining > 0): self.time_remaining -= 1 else: if(state_transition_event is not None): state_transition_event.set() else: self.idle() else: time.sleep(0.01) def get_roaster_state(self): """Returns a string based upon the current state of the roaster. Will raise an exception if the state is unknown. Returns: 'idle' if idle, 'sleeping' if sleeping, 'cooling' if cooling, 'roasting' if roasting, 'connecting' if in hardware connection phase, 'unknown' otherwise """ value = self._current_state.value if(value == b'\x02\x01'): return 'idle' elif(value == b'\x04\x04'): return 'cooling' elif(value == b'\x08\x01'): return 'sleeping' # handle null bytes as empty strings elif(value == b'\x00\x00' or value == b''): return 'connecting' elif(value == b'\x04\x02'): return 'roasting' else: return 'unknown' def _generate_packet(self): """Generates a packet based upon the current class variables. Note that current temperature is not sent, as the original application sent zeros to the roaster for the current temperature.""" roaster_time = utils.seconds_to_float(self._time_remaining.value) packet = ( self._header.value + self._temp_unit.value + self._flags.value + self._current_state.value + struct.pack(">B", self._fan_speed.value) + struct.pack(">B", int(round(roaster_time * 10.0))) + struct.pack(">B", self._heat_setting.value) + b'\x00\x00' + self._footer) return packet def idle(self): """Sets the current state of the roaster to idle.""" self._current_state.value = b'\x02\x01' def roast(self): """Sets the current state of the roaster to roast and begins roasting.""" self._current_state.value = b'\x04\x02' def cool(self): """Sets the current state of the roaster to cool. The roaster expects that cool will be run after roast, and will not work as expected if ran before.""" self._current_state.value = b'\x04\x04' def sleep(self): """Sets the current state of the roaster to sleep. Different than idle in that this will set double dashes on the roaster display rather than digits.""" self._current_state.value = b'\x08\x01'
Roastero/freshroastsr700
freshroastsr700/__init__.py
freshroastsr700.set_state_transition_func
python
def set_state_transition_func(self, func): if self._connected.value: logging.error("freshroastsr700.set_state_transition_func must be " "called before freshroastsr700.auto_connect()." " Not registering func.") return False # no connection yet. so OK to set func pointer self._create_state_transition_system(func) return True
THIS FUNCTION MUST BE CALLED BEFORE CALLING freshroastsr700.auto_connect(). Set, or re-set, the state transition function callback. The supplied function will be called from a separate thread within freshroastsr700, triggered by a separate, internal child process. This function will fail if the freshroastsr700 device is already connected to hardware, because by that time, the timer process and thread have already been spawned. Args: state_transition_func (func): the function to call for every state transition. A state transition occurs whenever the freshroastsr700's time_remaining value counts down to 0. Returns: nothing
train
https://github.com/Roastero/freshroastsr700/blob/49cf4961444c0f56d051d5ac5088ace480b54f02/freshroastsr700/__init__.py#L391-L417
[ "def _create_state_transition_system(\n self, state_transition_func, setFunc=True, createThread=False):\n # these callbacks cannot be called from another process in Windows.\n # Therefore, spawn a thread belonging to the calling process\n # instead.\n # the comm and timer processes will set event...
class freshroastsr700(object): """A class to interface with a freshroastsr700 coffee roaster. Args: update_data_func (func): A function to call when this object receives new data from the hardware. Defaults to None. state_transition_func (func): A function to call when time_remaining counts down to 0 and the device is either in roasting or cooling state. Defaults to None. thermostat (bool): thermostat mode. if set to True, turns on thermostat mode. In thermostat mode, freshroastsr700 takes control of heat_setting and does software PID control to hit the demanded target_temp. Defaults to False. ext_sw_heater_drive (bool): enable direct control over the internal heat_controller object. Defaults to False. When set to True, the thermostat field is IGNORED, and assumed to be False. Direct control over the software heater_level means that the freshroastsr700's PID controller cannot control the heater. Since thermostat and ext_sw_heater_drive cannot be allowed to both be True, this arg is given precedence over the thermostat arg. Note that (thermostat=False, ext_sw_heater_drive=False), (thermostat=True, ext_sw_heater_drive=False), (thermostat=False, ext_sw_heater_drive=True), are all acceptable arg combinations. Only the (thermostat=True, ext_sw_heater_drive=True), cominbation is not allowed, and this software will set thermostat=False in that case. kp (float): Kp value to use for PID control. Defaults to 0.06. ki (float): Ki value to use for PID control. Defaults to 0.0075. kd (float): Kd value to use for PID control. Defaults to 0.01. heater_segments (int): the pseudo-control range for the internal heat_controller object. Defaults to 8. """ def __init__(self, update_data_func=None, state_transition_func=None, thermostat=False, kp=0.06, ki=0.0075, kd=0.01, heater_segments=8, ext_sw_heater_drive=False): """Create variables used to send in packets to the roaster. The update data function is called when a packet is opened. The state transistion function is used by the timer thread to know what to do next. See wiki for more information on packet structure and fields.""" # constants for protocol decoding self.LOOKING_FOR_HEADER_1 = 0 self.LOOKING_FOR_HEADER_2 = 1 self.PACKET_DATA = 2 self.LOOKING_FOR_FOOTER_2 = 3 # constants for connection state monitoring self.CS_NOT_CONNECTED = -2 self.CS_ATTEMPTING_CONNECT = -1 self.CS_CONNECTING = 0 self.CS_CONNECTED = 1 # constants for connection attempt type self.CA_NONE = 0 self.CA_AUTO = 1 self.CA_SINGLE_SHOT = 2 self._create_update_data_system(update_data_func) self._create_state_transition_system(state_transition_func) self._header = sharedctypes.Array('c', b'\xAA\xAA') self._temp_unit = sharedctypes.Array('c', b'\x61\x74') self._flags = sharedctypes.Array('c', b'\x63') self._current_state = sharedctypes.Array('c', b'\x02\x01') self._footer = b'\xAA\xFA' self._fan_speed = sharedctypes.Value('i', 1) self._heat_setting = sharedctypes.Value('i', 0) self._target_temp = sharedctypes.Value('i', 150) self._current_temp = sharedctypes.Value('i', 150) self._time_remaining = sharedctypes.Value('i', 0) self._total_time = sharedctypes.Value('i', 0) self._disconnect = sharedctypes.Value('i', 0) self._teardown = sharedctypes.Value('i', 0) # for SW PWM heater setting self._heater_level = sharedctypes.Value('i', 0) # the following vars are not process-safe, do not access them # from the comm or timer threads, nor from the callbacks. self._ext_sw_heater_drive = ext_sw_heater_drive if not self._ext_sw_heater_drive: self._thermostat = thermostat else: self._thermostat = False self._pid_kp = kp self._pid_ki = ki self._pid_kd = kd self._heater_bangbang_segments = heater_segments # initialize to 'not connected' self._connected = sharedctypes.Value('i', 0) self._connect_state = sharedctypes.Value('i', self.CS_NOT_CONNECTED) # initialize to 'not trying to connect' self._attempting_connect = sharedctypes.Value('i', self.CA_NONE) # create comm process self.comm_process = mp.Process( target=self._comm, args=( self._thermostat, self._pid_kp, self._pid_ki, self._pid_kd, self._heater_bangbang_segments, self._ext_sw_heater_drive, self.update_data_event,)) self.comm_process.daemon = True self.comm_process.start() # create timer process that counts down time_remaining self.time_process = mp.Process( target=self._timer, args=( self.state_transition_event,)) self.time_process.daemon = True self.time_process.start() def _create_update_data_system( self, update_data_func, setFunc=True, createThread=False): # these callbacks cannot be called from another process in Windows. # Therefore, spawn a thread belonging to the calling process # instead. # the comm and timer processes will set events that the threads # will listen for to initiate the callbacks # only create the mp.Event once - # to mimic create_state_transition_system, for future-proofing # (in this case, currently, this is only called at __init__() time) if not hasattr(self, 'update_data_event'): self.update_data_event = mp.Event() # only create the thread.Event once - this is used to exit # the callback thread if not hasattr(self, 'update_data_callback_kill_event'): self.update_data_callback_kill_event = mp.Event() # destroy an existing thread if we had created one previously if(hasattr(self, 'update_data_thread') and self.update_data_thread is not None): # let's tear this down. To kill it, two events must be set... # in the right sequence! self.update_data_callback_kill_event.set() self.update_data_event.set() self.update_data_thread.join() if setFunc: self.update_data_func = update_data_func if self.update_data_func is not None: if createThread: self.update_data_callback_kill_event.clear() self.update_data_thread = threading.Thread( name='sr700_update_data', target=self.update_data_run, args=(self.update_data_event,), daemon=True ) else: self.update_data_thread = None def _create_state_transition_system( self, state_transition_func, setFunc=True, createThread=False): # these callbacks cannot be called from another process in Windows. # Therefore, spawn a thread belonging to the calling process # instead. # the comm and timer processes will set events that the threads # will listen for to initiate the callbacks # only create the mp.Event once - this fn can get called more # than once, by __init__() and by set_state_transition_func() if not hasattr(self, 'state_transition_event'): self.state_transition_event = mp.Event() # only create the thread.Event once - this is used to exit # the callback thread if not hasattr(self, 'state_transition_callback_kill_event'): self.state_transition_callback_kill_event = mp.Event() # destroy an existing thread if we had created one previously if(hasattr(self, 'state_transition_thread') and self.state_transition_thread is not None): # let's tear this down. To kill it, two events must be set... # in the right sequence! self.state_transition_callback_kill_event.set() self.state_transition_event.set() self.state_transition_thread.join() if setFunc: self.state_transition_func = state_transition_func if self.state_transition_func is not None: if createThread: self.state_transition_callback_kill_event.clear() self.state_transition_thread = threading.Thread( name='sr700_state_transition', target=self.state_transition_run, args=(self.state_transition_event,), daemon=True ) else: self.state_transition_thread = None @property def fan_speed(self): """Get/Set fan speed. Can be 1 to 9 inclusive. Args: Setter: fan_speed (int): fan speed Returns: Getter: (int): fan speed """ return self._fan_speed.value @fan_speed.setter def fan_speed(self, value): """Verifies the value is between 1 and 9 inclusively.""" if value not in range(1, 10): raise exceptions.RoasterValueError self._fan_speed.value = value @property def heat_setting(self): """Get/Set heat setting, 0 to 3 inclusive. 0=off, 3=high. Do not set when running freshroastsr700 in thermostat mode. Args: Setter: heat_setting (int): heat setting Returns: Getter: (int): heat setting """ return self._heat_setting.value @heat_setting.setter def heat_setting(self, value): """Verifies that the heat setting is between 0 and 3.""" if value not in range(0, 4): raise exceptions.RoasterValueError self._heat_setting.value = value @property def target_temp(self): """Get/Set the target temperature for this package's built-in software PID controler. Only used when freshroastsr700 is instantiated with thermostat=True. Args: Setter: value (int): a target temperature in degF between 150 and 551. Returns: Getter: (int) target temperature in degF between 150 and 551 """ return self._target_temp.value @target_temp.setter def target_temp(self, value): if value not in range(150, 551): raise exceptions.RoasterValueError self._target_temp.value = value @property def current_temp(self): """Current temperature of the roast chamber as reported by hardware. Returns: (int) current temperature, in degrees Fahrenheit """ return self._current_temp.value @current_temp.setter def current_temp(self, value): if value not in range(150, 551): raise exceptions.RoasterValueError self._current_temp.value = value @property def time_remaining(self): """The amount of time, in seconds, remaining until a call to the state_transition_func is made. can be set to an arbitrary value up to 600 seconds at any time. When a new value is set, freshroastsr700 will count down from this new value down to 0. time_remaining is decremented to 0 only when in a roasting or cooling state. In other states, the value is not touched. Args: Setter: time_remaining (int): tiem remaining in seconds Returns: Getter: time_remaining(int): time remaining, in seconds """ return self._time_remaining.value @time_remaining.setter def time_remaining(self, value): self._time_remaining.value = value @property def total_time(self): """The total time this instance has been in roasting or cooling state sicne the latest roast began. Returns: total_time (int): time, in seconds """ return self._total_time.value @total_time.setter def total_time(self, value): self._total_time.value = value @property def heater_level(self): """A getter method for _heater_level. When thermostat=True, value is driven by built-in PID controller. When ext_sw_heater_drive=True, value is driven by calls to heater_level(). Min will always be zero, max will be heater_segments (optional instantiation parameter, defaults to 8).""" return self._heater_level.value @heater_level.setter def heater_level(self, value): """Verifies that the heater_level is between 0 and heater_segments. Can only be called when freshroastsr700 object is initialized with ext_sw_heater_drive=True. Will throw RoasterValueError otherwise.""" if self._ext_sw_heater_drive: if value not in range(0, self._heater_bangbang_segments+1): raise exceptions.RoasterValueError self._heater_level.value = value else: raise exceptions.RoasterValueError @property def connected(self): """A getter method for _connected. Indicates that the this software is currently communicating with FreshRoast SR700 hardware.""" return self._connected.value @property def connect_state(self): """A getter method for _connect_state. Indicates the current connection state this software is in for FreshRoast SR700 hardware. Returns: freshroastsr700.CS_NOT_CONNECTED the software is not currenting communicating with hardware, neither was it instructed to do so. A previously failed connection attempt will also result in this state. freshroastsr700.CS_ATTEMPTING_CONNECT A call to auto_connect() or connect() was made, and the software is currently attempting to connect to hardware. freshroastsr700.CS_CONNECTED The hardware was found, and the software is communicating with the hardware. """ return self._connect_state.value def update_data_run(self, event_to_wait_on): """This is the thread that listens to an event from the comm process to execute the update_data_func callback in the context of the main process. """ # with the daemon=Turue setting, this thread should # quit 'automatically' while event_to_wait_on.wait(): event_to_wait_on.clear() if self.update_data_callback_kill_event.is_set(): return self.update_data_func() def state_transition_run(self, event_to_wait_on): """This is the thread that listens to an event from the timer process to execute the state_transition_func callback in the context of the main process. """ # with the daemon=Turue setting, this thread should # quit 'automatically' while event_to_wait_on.wait(): event_to_wait_on.clear() if self.state_transition_callback_kill_event.is_set(): return self.state_transition_func() def _connect(self): """Do not call this directly - call auto_connect() or connect(), which will call _connect() for you. Connects to the roaster and creates communication thread. Raises a RoasterLokkupError exception if the hardware is not found. """ # the following call raises a RoasterLookupException when the device # is not found. It is port = utils.find_device('1A86:5523') # on some systems, after the device port is added to the device list, # it can take up to 20 seconds after USB insertion for # the port to become available... (!) # let's put a safety timeout in here as a precaution wait_timeout = time.time() + 40.0 # should be PLENTY of time! # let's update the _connect_state while we're at it... self._connect_state.value = self.CS_CONNECTING connect_success = False while time.time() < wait_timeout: try: self._ser = serial.Serial( port=port, baudrate=9600, bytesize=8, parity='N', stopbits=1.5, timeout=0.25, xonxoff=False, rtscts=False, dsrdtr=False) connect_success = True break except serial.SerialException: time.sleep(0.5) if not connect_success: # timeout on attempts raise exceptions.RoasterLookupError self._initialize() def _initialize(self): """Sends the initialization packet to the roaster.""" self._header.value = b'\xAA\x55' self._current_state.value = b'\x00\x00' s = self._generate_packet() self._ser.write(s) self._header.value = b'\xAA\xAA' self._current_state.value = b'\x02\x01' return self._read_existing_recipe() def _write_to_device(self): success = False try: packet = self._generate_packet() logging.debug('WR: ' + str(binascii.hexlify(packet))) self._ser.write(packet) success = True except serial.serialutil.SerialException: logging.error('caught serial exception writing') return success def _read_from_device(self): r = [] footer_reached = False while len(r) < 14 and footer_reached is False: r.append(self._ser.read(1)) if len(r) >= 2 and b''.join(r)[-2:] == self._footer: footer_reached = True logging.debug('RD: ' + str(binascii.hexlify(b''.join(r)))) return b''.join(r) def _read_existing_recipe(self): existing_recipe = [] end_of_recipe = False while not end_of_recipe: bytes_waiting = self._ser.in_waiting if bytes_waiting < 14: # still need to write to device every .25sec it seems time.sleep(0.25) self._write_to_device() else: while (bytes_waiting // 14) > 0: r = self._read_from_device() bytes_waiting = self._ser.in_waiting if len(r) < 14: logging.warn('short packet length') else: existing_recipe.append(r) if r[4:5] == b'\xAF' or r[4:5] == b'\x00': end_of_recipe = True continue return existing_recipe def connect(self): """Attempt to connect to hardware immediately. Will not retry. Check freshroastsr700.connected or freshroastsr700.connect_state to verify result. Raises: freshroastsr700.exeptions.RoasterLookupError No hardware connected to the computer. """ self._start_connect(self.CA_SINGLE_SHOT) while(self._connect_state.value == self.CS_ATTEMPTING_CONNECT or self._connect_state.value == self.CS_CONNECTING): time.sleep(0.1) if self.CS_CONNECTED != self._connect_state.value: raise exceptions.RoasterLookupError def auto_connect(self): """Starts a thread that will automatically connect to the roaster when it is plugged in.""" self._start_connect(self.CA_AUTO) def _start_connect(self, connect_type): """Starts the connection process, as called (internally) from the user context, either from auto_connect() or connect(). Never call this from the _comm() process context. """ if self._connect_state.value != self.CS_NOT_CONNECTED: # already done or in process, assume success return self._connected.value = 0 self._connect_state.value = self.CS_ATTEMPTING_CONNECT # tell comm process to attempt connection self._attempting_connect.value = connect_type # EXTREMELY IMPORTANT - for this to work at all in Windows, # where the above processes are spawned (vs forked in Unix), # the thread objects (as sattributes of this object) must be # assigned to this object AFTER we have spawned the processes. # That way, multiprocessing can pickle the freshroastsr700 # successfully. (It can't pickle thread-related stuff.) if self.update_data_func is not None: # Need to launch the thread that will listen to the event self._create_update_data_system( None, setFunc=False, createThread=True) self.update_data_thread.start() if self.state_transition_func is not None: # Need to launch the thread that will listen to the event self._create_state_transition_system( None, setFunc=False, createThread=True) self.state_transition_thread.start() def _auto_connect(self): """Attempts to connect to the roaster every quarter of a second.""" while not self._teardown.value: try: self._connect() return True except exceptions.RoasterLookupError: time.sleep(.25) return False def disconnect(self): """Stops the communication loop to the roaster. Note that this will not actually stop the roaster itself.""" self._disconnect.value = 1 def terminate(self): """Stops the communication loop to the roaster and closes down all communication processes. Note that this will not actually stop the roaster itself. You will need to instantiate a new freshroastsr700 object after calling this function, in order to re-start communications with the hardware. """ self.disconnect() self._teardown.value = 1 def _comm(self, thermostat=False, kp=0.06, ki=0.0075, kd=0.01, heater_segments=8, ext_sw_heater_drive=False, update_data_event=None): """Do not call this directly - call auto_connect(), which will spawn comm() for you. This is the main communications loop to the roaster. whenever a valid packet is received from the device, if an update_data_event is available, it will be signalled. Args: thermostat (bool): thermostat mode. if set to True, turns on thermostat mode. In thermostat mode, freshroastsr700 takes control of heat_setting and does software PID control to hit the demanded target_temp. ext_sw_heater_drive (bool): enable direct control over the internal heat_controller object. Defaults to False. When set to True, the thermostat field is IGNORED, and assumed to be False. Direct control over the software heater_level means that the PID controller cannot control the heater. Since thermostat and ext_sw_heater_drive cannot be allowed to both be True, this arg is given precedence over the thermostat arg. kp (float): Kp value to use for PID control. Defaults to 0.06. ki (float): Ki value to use for PID control. Defaults to 0.0075. kd (float): Kd value to use for PID control. Defaults to 0.01. heater_segments (int): the pseudo-control range for the internal heat_controller object. Defaults to 8. update_data_event (multiprocessing.Event): If set, allows the comm_process to signal to the parent process that new device data is available. Returns: nothing """ # since this process is started with daemon=True, it should exit # when the owning process terminates. Therefore, safe to loop forever. while not self._teardown.value: # waiting for command to attempt connect # print( "waiting for command to attempt connect") while self._attempting_connect.value == self.CA_NONE: time.sleep(0.25) if self._teardown.value: break # if we're tearing down, bail now. if self._teardown.value: break # we got the command to attempt to connect # change state to 'attempting_connect' self._connect_state.value = self.CS_ATTEMPTING_CONNECT # attempt connection if self.CA_AUTO == self._attempting_connect.value: # this call will block until a connection is achieved # it will also set _connect_state to CS_CONNECTING # if appropriate if self._auto_connect(): # when we unblock, it is an indication of a successful # connection self._connected.value = 1 self._connect_state.value = self.CS_CONNECTED else: # failure, normally due to a timeout self._connected.value = 0 self._connect_state.value = self.CS_NOT_CONNECTED # we failed to connect - start over from the top # reset flag self._attempting_connect.value = self.CA_NONE continue elif self.CA_SINGLE_SHOT == self._attempting_connect.value: # try once, now, if failure, start teh big loop over try: self._connect() self._connected.value = 1 self._connect_state.value = self.CS_CONNECTED except exceptions.RoasterLookupError: self._connected.value = 0 self._connect_state.value = self.CS_NOT_CONNECTED if self._connect_state.value != self.CS_CONNECTED: # we failed to connect - start over from the top # reset flag self._attempting_connect.value = self.CA_NONE continue else: # shouldn't be here # reset flag self._attempting_connect.value = self.CA_NONE continue # We are connected! # print( "We are connected!") # reset flag right away self._attempting_connect.value = self.CA_NONE # Initialize PID controller if thermostat function was specified at # init time pidc = None heater = None if(thermostat): pidc = pid.PID(kp, ki, kd, Output_max=heater_segments, Output_min=0 ) if thermostat or ext_sw_heater_drive: heater = heat_controller(number_of_segments=heater_segments) read_state = self.LOOKING_FOR_HEADER_1 r = [] write_errors = 0 read_errors = 0 while not self._disconnect.value: start = datetime.datetime.now() # write to device if not self._write_to_device(): logging.error('comm - _write_to_device() failed!') write_errors += 1 if write_errors > 3: # it's time to consider the device as being "gone" logging.error('comm - 3 successive write ' 'failures, disconnecting.') self._disconnect.value = 1 continue else: # reset write_errors write_errors = 0 # read from device try: while self._ser.in_waiting: _byte = self._ser.read(1) read_state, r, err = ( self._process_reponse_byte( read_state, _byte, r, update_data_event)) except IOError: # typically happens when device is suddenly unplugged logging.error('comm - read from device failed!') read_errors += 1 if write_errors > 3: # it's time to consider the device as being "gone" logging.error('comm - 3 successive read ' 'failures, disconnecting.') self._disconnect.value = 1 continue else: read_errors = 0 # next, drive SW heater when using # thermostat mode (PID controller calcs) # or in external sw heater drive mode, # when roasting. if thermostat or ext_sw_heater_drive: if 'roasting' == self.get_roaster_state(): if heater.about_to_rollover(): # it's time to use the PID controller value # and set new output level on heater! if ext_sw_heater_drive: # read user-supplied value heater.heat_level = self._heater_level.value else: # thermostat output = pidc.update( self.current_temp, self.target_temp) heater.heat_level = output # make this number visible to other processes... self._heater_level.value = heater.heat_level # read bang-bang heater output array element & apply it if heater.generate_bangbang_output(): # ON self.heat_setting = 3 else: # OFF self.heat_setting = 0 else: # for all other states, heat_level = OFF heater.heat_level = 0 # make this number visible to other processes... self._heater_level.value = heater.heat_level self.heat_setting = 0 # calculate sleep time to stick to 0.25sec period comp_time = datetime.datetime.now() - start sleep_duration = 0.25 - comp_time.total_seconds() if sleep_duration > 0: time.sleep(sleep_duration) self._ser.close() # reset disconnect flag self._disconnect.value = 0 # reset connection values self._connected.value = 0 self._connect_state.value = self.CS_NOT_CONNECTED # print("We are disconnected.") def _process_reponse_byte(self, read_state, _byte, r, update_data_event): err = False if self.LOOKING_FOR_HEADER_1 == read_state: if b'\xAA' == _byte: read_state = self.LOOKING_FOR_HEADER_2 elif self.LOOKING_FOR_HEADER_2 == read_state: if b'\xAA' == _byte: read_state = self.PACKET_DATA # reset packet array now... r = [] else: read_state = self.LOOKING_FOR_HEADER_1 elif self.PACKET_DATA == read_state: if b'\xAA' == _byte: # this could be the start of an end of packet marker read_state = self.LOOKING_FOR_FOOTER_2 else: r.append(_byte) # SR700 FW bug - if current temp is 250 degF (0xFA), # the FW does not transmit the footer at all. # fake the footer here. if(len(r) == 10 and b'\xFA' == _byte): # we will 'fake' a footer to make this decoder work # as intended read_state, r, _ = ( self._process_reponse_byte( read_state, b'\xAA', r, update_data_event)) read_state, r, err = ( self._process_reponse_byte( read_state, b'\xFA', r, update_data_event)) elif self.LOOKING_FOR_FOOTER_2 == read_state: if b'\xFA' == _byte: # OK we have a full packet - PROCESS PACKET err = self._process_response_data(r, update_data_event) read_state = self.LOOKING_FOR_HEADER_1 else: # the last byte was not the beginning of the footer r.append(b'\xAA') read_state = self.PACKET_DATA read_state, r, err = self._process_reponse_byte( read_state, _byte, r, update_data_event) else: # error state, shouldn't happen... logging.error('_process_reponse_byte - invalid read_state %d' % read_state) read_state = self.LOOKING_FOR_HEADER_1 err = True return read_state, r, err def _process_response_data(self, r, update_data_event): err = False if len(r) != 10: logging.warn('read packet data len not 10, got: %d' % len(r)) logging.warn('RD: ' + str(binascii.hexlify(b''.join(r)))) err = True else: temp = struct.unpack(">H", b''.join(r[8:10]))[0] if(temp == 65280): self.current_temp = 150 elif(temp > 550 or temp < 150): logging.warn('temperature out of range: reinitializing...') self._initialize() err = True return else: self.current_temp = temp if(update_data_event is not None): update_data_event.set() return err def _timer(self, state_transition_event=None): """Timer loop used to keep track of the time while roasting or cooling. If the time remaining reaches zero, the roaster will call the supplied state transistion function or the roaster will be set to the idle state.""" while not self._teardown.value: state = self.get_roaster_state() if(state == 'roasting' or state == 'cooling'): time.sleep(1) self.total_time += 1 if(self.time_remaining > 0): self.time_remaining -= 1 else: if(state_transition_event is not None): state_transition_event.set() else: self.idle() else: time.sleep(0.01) def get_roaster_state(self): """Returns a string based upon the current state of the roaster. Will raise an exception if the state is unknown. Returns: 'idle' if idle, 'sleeping' if sleeping, 'cooling' if cooling, 'roasting' if roasting, 'connecting' if in hardware connection phase, 'unknown' otherwise """ value = self._current_state.value if(value == b'\x02\x01'): return 'idle' elif(value == b'\x04\x04'): return 'cooling' elif(value == b'\x08\x01'): return 'sleeping' # handle null bytes as empty strings elif(value == b'\x00\x00' or value == b''): return 'connecting' elif(value == b'\x04\x02'): return 'roasting' else: return 'unknown' def _generate_packet(self): """Generates a packet based upon the current class variables. Note that current temperature is not sent, as the original application sent zeros to the roaster for the current temperature.""" roaster_time = utils.seconds_to_float(self._time_remaining.value) packet = ( self._header.value + self._temp_unit.value + self._flags.value + self._current_state.value + struct.pack(">B", self._fan_speed.value) + struct.pack(">B", int(round(roaster_time * 10.0))) + struct.pack(">B", self._heat_setting.value) + b'\x00\x00' + self._footer) return packet def idle(self): """Sets the current state of the roaster to idle.""" self._current_state.value = b'\x02\x01' def roast(self): """Sets the current state of the roaster to roast and begins roasting.""" self._current_state.value = b'\x04\x02' def cool(self): """Sets the current state of the roaster to cool. The roaster expects that cool will be run after roast, and will not work as expected if ran before.""" self._current_state.value = b'\x04\x04' def sleep(self): """Sets the current state of the roaster to sleep. Different than idle in that this will set double dashes on the roaster display rather than digits.""" self._current_state.value = b'\x08\x01'
Roastero/freshroastsr700
freshroastsr700/__init__.py
freshroastsr700.update_data_run
python
def update_data_run(self, event_to_wait_on): # with the daemon=Turue setting, this thread should # quit 'automatically' while event_to_wait_on.wait(): event_to_wait_on.clear() if self.update_data_callback_kill_event.is_set(): return self.update_data_func()
This is the thread that listens to an event from the comm process to execute the update_data_func callback in the context of the main process.
train
https://github.com/Roastero/freshroastsr700/blob/49cf4961444c0f56d051d5ac5088ace480b54f02/freshroastsr700/__init__.py#L419-L430
null
class freshroastsr700(object): """A class to interface with a freshroastsr700 coffee roaster. Args: update_data_func (func): A function to call when this object receives new data from the hardware. Defaults to None. state_transition_func (func): A function to call when time_remaining counts down to 0 and the device is either in roasting or cooling state. Defaults to None. thermostat (bool): thermostat mode. if set to True, turns on thermostat mode. In thermostat mode, freshroastsr700 takes control of heat_setting and does software PID control to hit the demanded target_temp. Defaults to False. ext_sw_heater_drive (bool): enable direct control over the internal heat_controller object. Defaults to False. When set to True, the thermostat field is IGNORED, and assumed to be False. Direct control over the software heater_level means that the freshroastsr700's PID controller cannot control the heater. Since thermostat and ext_sw_heater_drive cannot be allowed to both be True, this arg is given precedence over the thermostat arg. Note that (thermostat=False, ext_sw_heater_drive=False), (thermostat=True, ext_sw_heater_drive=False), (thermostat=False, ext_sw_heater_drive=True), are all acceptable arg combinations. Only the (thermostat=True, ext_sw_heater_drive=True), cominbation is not allowed, and this software will set thermostat=False in that case. kp (float): Kp value to use for PID control. Defaults to 0.06. ki (float): Ki value to use for PID control. Defaults to 0.0075. kd (float): Kd value to use for PID control. Defaults to 0.01. heater_segments (int): the pseudo-control range for the internal heat_controller object. Defaults to 8. """ def __init__(self, update_data_func=None, state_transition_func=None, thermostat=False, kp=0.06, ki=0.0075, kd=0.01, heater_segments=8, ext_sw_heater_drive=False): """Create variables used to send in packets to the roaster. The update data function is called when a packet is opened. The state transistion function is used by the timer thread to know what to do next. See wiki for more information on packet structure and fields.""" # constants for protocol decoding self.LOOKING_FOR_HEADER_1 = 0 self.LOOKING_FOR_HEADER_2 = 1 self.PACKET_DATA = 2 self.LOOKING_FOR_FOOTER_2 = 3 # constants for connection state monitoring self.CS_NOT_CONNECTED = -2 self.CS_ATTEMPTING_CONNECT = -1 self.CS_CONNECTING = 0 self.CS_CONNECTED = 1 # constants for connection attempt type self.CA_NONE = 0 self.CA_AUTO = 1 self.CA_SINGLE_SHOT = 2 self._create_update_data_system(update_data_func) self._create_state_transition_system(state_transition_func) self._header = sharedctypes.Array('c', b'\xAA\xAA') self._temp_unit = sharedctypes.Array('c', b'\x61\x74') self._flags = sharedctypes.Array('c', b'\x63') self._current_state = sharedctypes.Array('c', b'\x02\x01') self._footer = b'\xAA\xFA' self._fan_speed = sharedctypes.Value('i', 1) self._heat_setting = sharedctypes.Value('i', 0) self._target_temp = sharedctypes.Value('i', 150) self._current_temp = sharedctypes.Value('i', 150) self._time_remaining = sharedctypes.Value('i', 0) self._total_time = sharedctypes.Value('i', 0) self._disconnect = sharedctypes.Value('i', 0) self._teardown = sharedctypes.Value('i', 0) # for SW PWM heater setting self._heater_level = sharedctypes.Value('i', 0) # the following vars are not process-safe, do not access them # from the comm or timer threads, nor from the callbacks. self._ext_sw_heater_drive = ext_sw_heater_drive if not self._ext_sw_heater_drive: self._thermostat = thermostat else: self._thermostat = False self._pid_kp = kp self._pid_ki = ki self._pid_kd = kd self._heater_bangbang_segments = heater_segments # initialize to 'not connected' self._connected = sharedctypes.Value('i', 0) self._connect_state = sharedctypes.Value('i', self.CS_NOT_CONNECTED) # initialize to 'not trying to connect' self._attempting_connect = sharedctypes.Value('i', self.CA_NONE) # create comm process self.comm_process = mp.Process( target=self._comm, args=( self._thermostat, self._pid_kp, self._pid_ki, self._pid_kd, self._heater_bangbang_segments, self._ext_sw_heater_drive, self.update_data_event,)) self.comm_process.daemon = True self.comm_process.start() # create timer process that counts down time_remaining self.time_process = mp.Process( target=self._timer, args=( self.state_transition_event,)) self.time_process.daemon = True self.time_process.start() def _create_update_data_system( self, update_data_func, setFunc=True, createThread=False): # these callbacks cannot be called from another process in Windows. # Therefore, spawn a thread belonging to the calling process # instead. # the comm and timer processes will set events that the threads # will listen for to initiate the callbacks # only create the mp.Event once - # to mimic create_state_transition_system, for future-proofing # (in this case, currently, this is only called at __init__() time) if not hasattr(self, 'update_data_event'): self.update_data_event = mp.Event() # only create the thread.Event once - this is used to exit # the callback thread if not hasattr(self, 'update_data_callback_kill_event'): self.update_data_callback_kill_event = mp.Event() # destroy an existing thread if we had created one previously if(hasattr(self, 'update_data_thread') and self.update_data_thread is not None): # let's tear this down. To kill it, two events must be set... # in the right sequence! self.update_data_callback_kill_event.set() self.update_data_event.set() self.update_data_thread.join() if setFunc: self.update_data_func = update_data_func if self.update_data_func is not None: if createThread: self.update_data_callback_kill_event.clear() self.update_data_thread = threading.Thread( name='sr700_update_data', target=self.update_data_run, args=(self.update_data_event,), daemon=True ) else: self.update_data_thread = None def _create_state_transition_system( self, state_transition_func, setFunc=True, createThread=False): # these callbacks cannot be called from another process in Windows. # Therefore, spawn a thread belonging to the calling process # instead. # the comm and timer processes will set events that the threads # will listen for to initiate the callbacks # only create the mp.Event once - this fn can get called more # than once, by __init__() and by set_state_transition_func() if not hasattr(self, 'state_transition_event'): self.state_transition_event = mp.Event() # only create the thread.Event once - this is used to exit # the callback thread if not hasattr(self, 'state_transition_callback_kill_event'): self.state_transition_callback_kill_event = mp.Event() # destroy an existing thread if we had created one previously if(hasattr(self, 'state_transition_thread') and self.state_transition_thread is not None): # let's tear this down. To kill it, two events must be set... # in the right sequence! self.state_transition_callback_kill_event.set() self.state_transition_event.set() self.state_transition_thread.join() if setFunc: self.state_transition_func = state_transition_func if self.state_transition_func is not None: if createThread: self.state_transition_callback_kill_event.clear() self.state_transition_thread = threading.Thread( name='sr700_state_transition', target=self.state_transition_run, args=(self.state_transition_event,), daemon=True ) else: self.state_transition_thread = None @property def fan_speed(self): """Get/Set fan speed. Can be 1 to 9 inclusive. Args: Setter: fan_speed (int): fan speed Returns: Getter: (int): fan speed """ return self._fan_speed.value @fan_speed.setter def fan_speed(self, value): """Verifies the value is between 1 and 9 inclusively.""" if value not in range(1, 10): raise exceptions.RoasterValueError self._fan_speed.value = value @property def heat_setting(self): """Get/Set heat setting, 0 to 3 inclusive. 0=off, 3=high. Do not set when running freshroastsr700 in thermostat mode. Args: Setter: heat_setting (int): heat setting Returns: Getter: (int): heat setting """ return self._heat_setting.value @heat_setting.setter def heat_setting(self, value): """Verifies that the heat setting is between 0 and 3.""" if value not in range(0, 4): raise exceptions.RoasterValueError self._heat_setting.value = value @property def target_temp(self): """Get/Set the target temperature for this package's built-in software PID controler. Only used when freshroastsr700 is instantiated with thermostat=True. Args: Setter: value (int): a target temperature in degF between 150 and 551. Returns: Getter: (int) target temperature in degF between 150 and 551 """ return self._target_temp.value @target_temp.setter def target_temp(self, value): if value not in range(150, 551): raise exceptions.RoasterValueError self._target_temp.value = value @property def current_temp(self): """Current temperature of the roast chamber as reported by hardware. Returns: (int) current temperature, in degrees Fahrenheit """ return self._current_temp.value @current_temp.setter def current_temp(self, value): if value not in range(150, 551): raise exceptions.RoasterValueError self._current_temp.value = value @property def time_remaining(self): """The amount of time, in seconds, remaining until a call to the state_transition_func is made. can be set to an arbitrary value up to 600 seconds at any time. When a new value is set, freshroastsr700 will count down from this new value down to 0. time_remaining is decremented to 0 only when in a roasting or cooling state. In other states, the value is not touched. Args: Setter: time_remaining (int): tiem remaining in seconds Returns: Getter: time_remaining(int): time remaining, in seconds """ return self._time_remaining.value @time_remaining.setter def time_remaining(self, value): self._time_remaining.value = value @property def total_time(self): """The total time this instance has been in roasting or cooling state sicne the latest roast began. Returns: total_time (int): time, in seconds """ return self._total_time.value @total_time.setter def total_time(self, value): self._total_time.value = value @property def heater_level(self): """A getter method for _heater_level. When thermostat=True, value is driven by built-in PID controller. When ext_sw_heater_drive=True, value is driven by calls to heater_level(). Min will always be zero, max will be heater_segments (optional instantiation parameter, defaults to 8).""" return self._heater_level.value @heater_level.setter def heater_level(self, value): """Verifies that the heater_level is between 0 and heater_segments. Can only be called when freshroastsr700 object is initialized with ext_sw_heater_drive=True. Will throw RoasterValueError otherwise.""" if self._ext_sw_heater_drive: if value not in range(0, self._heater_bangbang_segments+1): raise exceptions.RoasterValueError self._heater_level.value = value else: raise exceptions.RoasterValueError @property def connected(self): """A getter method for _connected. Indicates that the this software is currently communicating with FreshRoast SR700 hardware.""" return self._connected.value @property def connect_state(self): """A getter method for _connect_state. Indicates the current connection state this software is in for FreshRoast SR700 hardware. Returns: freshroastsr700.CS_NOT_CONNECTED the software is not currenting communicating with hardware, neither was it instructed to do so. A previously failed connection attempt will also result in this state. freshroastsr700.CS_ATTEMPTING_CONNECT A call to auto_connect() or connect() was made, and the software is currently attempting to connect to hardware. freshroastsr700.CS_CONNECTED The hardware was found, and the software is communicating with the hardware. """ return self._connect_state.value def set_state_transition_func(self, func): """THIS FUNCTION MUST BE CALLED BEFORE CALLING freshroastsr700.auto_connect(). Set, or re-set, the state transition function callback. The supplied function will be called from a separate thread within freshroastsr700, triggered by a separate, internal child process. This function will fail if the freshroastsr700 device is already connected to hardware, because by that time, the timer process and thread have already been spawned. Args: state_transition_func (func): the function to call for every state transition. A state transition occurs whenever the freshroastsr700's time_remaining value counts down to 0. Returns: nothing """ if self._connected.value: logging.error("freshroastsr700.set_state_transition_func must be " "called before freshroastsr700.auto_connect()." " Not registering func.") return False # no connection yet. so OK to set func pointer self._create_state_transition_system(func) return True def state_transition_run(self, event_to_wait_on): """This is the thread that listens to an event from the timer process to execute the state_transition_func callback in the context of the main process. """ # with the daemon=Turue setting, this thread should # quit 'automatically' while event_to_wait_on.wait(): event_to_wait_on.clear() if self.state_transition_callback_kill_event.is_set(): return self.state_transition_func() def _connect(self): """Do not call this directly - call auto_connect() or connect(), which will call _connect() for you. Connects to the roaster and creates communication thread. Raises a RoasterLokkupError exception if the hardware is not found. """ # the following call raises a RoasterLookupException when the device # is not found. It is port = utils.find_device('1A86:5523') # on some systems, after the device port is added to the device list, # it can take up to 20 seconds after USB insertion for # the port to become available... (!) # let's put a safety timeout in here as a precaution wait_timeout = time.time() + 40.0 # should be PLENTY of time! # let's update the _connect_state while we're at it... self._connect_state.value = self.CS_CONNECTING connect_success = False while time.time() < wait_timeout: try: self._ser = serial.Serial( port=port, baudrate=9600, bytesize=8, parity='N', stopbits=1.5, timeout=0.25, xonxoff=False, rtscts=False, dsrdtr=False) connect_success = True break except serial.SerialException: time.sleep(0.5) if not connect_success: # timeout on attempts raise exceptions.RoasterLookupError self._initialize() def _initialize(self): """Sends the initialization packet to the roaster.""" self._header.value = b'\xAA\x55' self._current_state.value = b'\x00\x00' s = self._generate_packet() self._ser.write(s) self._header.value = b'\xAA\xAA' self._current_state.value = b'\x02\x01' return self._read_existing_recipe() def _write_to_device(self): success = False try: packet = self._generate_packet() logging.debug('WR: ' + str(binascii.hexlify(packet))) self._ser.write(packet) success = True except serial.serialutil.SerialException: logging.error('caught serial exception writing') return success def _read_from_device(self): r = [] footer_reached = False while len(r) < 14 and footer_reached is False: r.append(self._ser.read(1)) if len(r) >= 2 and b''.join(r)[-2:] == self._footer: footer_reached = True logging.debug('RD: ' + str(binascii.hexlify(b''.join(r)))) return b''.join(r) def _read_existing_recipe(self): existing_recipe = [] end_of_recipe = False while not end_of_recipe: bytes_waiting = self._ser.in_waiting if bytes_waiting < 14: # still need to write to device every .25sec it seems time.sleep(0.25) self._write_to_device() else: while (bytes_waiting // 14) > 0: r = self._read_from_device() bytes_waiting = self._ser.in_waiting if len(r) < 14: logging.warn('short packet length') else: existing_recipe.append(r) if r[4:5] == b'\xAF' or r[4:5] == b'\x00': end_of_recipe = True continue return existing_recipe def connect(self): """Attempt to connect to hardware immediately. Will not retry. Check freshroastsr700.connected or freshroastsr700.connect_state to verify result. Raises: freshroastsr700.exeptions.RoasterLookupError No hardware connected to the computer. """ self._start_connect(self.CA_SINGLE_SHOT) while(self._connect_state.value == self.CS_ATTEMPTING_CONNECT or self._connect_state.value == self.CS_CONNECTING): time.sleep(0.1) if self.CS_CONNECTED != self._connect_state.value: raise exceptions.RoasterLookupError def auto_connect(self): """Starts a thread that will automatically connect to the roaster when it is plugged in.""" self._start_connect(self.CA_AUTO) def _start_connect(self, connect_type): """Starts the connection process, as called (internally) from the user context, either from auto_connect() or connect(). Never call this from the _comm() process context. """ if self._connect_state.value != self.CS_NOT_CONNECTED: # already done or in process, assume success return self._connected.value = 0 self._connect_state.value = self.CS_ATTEMPTING_CONNECT # tell comm process to attempt connection self._attempting_connect.value = connect_type # EXTREMELY IMPORTANT - for this to work at all in Windows, # where the above processes are spawned (vs forked in Unix), # the thread objects (as sattributes of this object) must be # assigned to this object AFTER we have spawned the processes. # That way, multiprocessing can pickle the freshroastsr700 # successfully. (It can't pickle thread-related stuff.) if self.update_data_func is not None: # Need to launch the thread that will listen to the event self._create_update_data_system( None, setFunc=False, createThread=True) self.update_data_thread.start() if self.state_transition_func is not None: # Need to launch the thread that will listen to the event self._create_state_transition_system( None, setFunc=False, createThread=True) self.state_transition_thread.start() def _auto_connect(self): """Attempts to connect to the roaster every quarter of a second.""" while not self._teardown.value: try: self._connect() return True except exceptions.RoasterLookupError: time.sleep(.25) return False def disconnect(self): """Stops the communication loop to the roaster. Note that this will not actually stop the roaster itself.""" self._disconnect.value = 1 def terminate(self): """Stops the communication loop to the roaster and closes down all communication processes. Note that this will not actually stop the roaster itself. You will need to instantiate a new freshroastsr700 object after calling this function, in order to re-start communications with the hardware. """ self.disconnect() self._teardown.value = 1 def _comm(self, thermostat=False, kp=0.06, ki=0.0075, kd=0.01, heater_segments=8, ext_sw_heater_drive=False, update_data_event=None): """Do not call this directly - call auto_connect(), which will spawn comm() for you. This is the main communications loop to the roaster. whenever a valid packet is received from the device, if an update_data_event is available, it will be signalled. Args: thermostat (bool): thermostat mode. if set to True, turns on thermostat mode. In thermostat mode, freshroastsr700 takes control of heat_setting and does software PID control to hit the demanded target_temp. ext_sw_heater_drive (bool): enable direct control over the internal heat_controller object. Defaults to False. When set to True, the thermostat field is IGNORED, and assumed to be False. Direct control over the software heater_level means that the PID controller cannot control the heater. Since thermostat and ext_sw_heater_drive cannot be allowed to both be True, this arg is given precedence over the thermostat arg. kp (float): Kp value to use for PID control. Defaults to 0.06. ki (float): Ki value to use for PID control. Defaults to 0.0075. kd (float): Kd value to use for PID control. Defaults to 0.01. heater_segments (int): the pseudo-control range for the internal heat_controller object. Defaults to 8. update_data_event (multiprocessing.Event): If set, allows the comm_process to signal to the parent process that new device data is available. Returns: nothing """ # since this process is started with daemon=True, it should exit # when the owning process terminates. Therefore, safe to loop forever. while not self._teardown.value: # waiting for command to attempt connect # print( "waiting for command to attempt connect") while self._attempting_connect.value == self.CA_NONE: time.sleep(0.25) if self._teardown.value: break # if we're tearing down, bail now. if self._teardown.value: break # we got the command to attempt to connect # change state to 'attempting_connect' self._connect_state.value = self.CS_ATTEMPTING_CONNECT # attempt connection if self.CA_AUTO == self._attempting_connect.value: # this call will block until a connection is achieved # it will also set _connect_state to CS_CONNECTING # if appropriate if self._auto_connect(): # when we unblock, it is an indication of a successful # connection self._connected.value = 1 self._connect_state.value = self.CS_CONNECTED else: # failure, normally due to a timeout self._connected.value = 0 self._connect_state.value = self.CS_NOT_CONNECTED # we failed to connect - start over from the top # reset flag self._attempting_connect.value = self.CA_NONE continue elif self.CA_SINGLE_SHOT == self._attempting_connect.value: # try once, now, if failure, start teh big loop over try: self._connect() self._connected.value = 1 self._connect_state.value = self.CS_CONNECTED except exceptions.RoasterLookupError: self._connected.value = 0 self._connect_state.value = self.CS_NOT_CONNECTED if self._connect_state.value != self.CS_CONNECTED: # we failed to connect - start over from the top # reset flag self._attempting_connect.value = self.CA_NONE continue else: # shouldn't be here # reset flag self._attempting_connect.value = self.CA_NONE continue # We are connected! # print( "We are connected!") # reset flag right away self._attempting_connect.value = self.CA_NONE # Initialize PID controller if thermostat function was specified at # init time pidc = None heater = None if(thermostat): pidc = pid.PID(kp, ki, kd, Output_max=heater_segments, Output_min=0 ) if thermostat or ext_sw_heater_drive: heater = heat_controller(number_of_segments=heater_segments) read_state = self.LOOKING_FOR_HEADER_1 r = [] write_errors = 0 read_errors = 0 while not self._disconnect.value: start = datetime.datetime.now() # write to device if not self._write_to_device(): logging.error('comm - _write_to_device() failed!') write_errors += 1 if write_errors > 3: # it's time to consider the device as being "gone" logging.error('comm - 3 successive write ' 'failures, disconnecting.') self._disconnect.value = 1 continue else: # reset write_errors write_errors = 0 # read from device try: while self._ser.in_waiting: _byte = self._ser.read(1) read_state, r, err = ( self._process_reponse_byte( read_state, _byte, r, update_data_event)) except IOError: # typically happens when device is suddenly unplugged logging.error('comm - read from device failed!') read_errors += 1 if write_errors > 3: # it's time to consider the device as being "gone" logging.error('comm - 3 successive read ' 'failures, disconnecting.') self._disconnect.value = 1 continue else: read_errors = 0 # next, drive SW heater when using # thermostat mode (PID controller calcs) # or in external sw heater drive mode, # when roasting. if thermostat or ext_sw_heater_drive: if 'roasting' == self.get_roaster_state(): if heater.about_to_rollover(): # it's time to use the PID controller value # and set new output level on heater! if ext_sw_heater_drive: # read user-supplied value heater.heat_level = self._heater_level.value else: # thermostat output = pidc.update( self.current_temp, self.target_temp) heater.heat_level = output # make this number visible to other processes... self._heater_level.value = heater.heat_level # read bang-bang heater output array element & apply it if heater.generate_bangbang_output(): # ON self.heat_setting = 3 else: # OFF self.heat_setting = 0 else: # for all other states, heat_level = OFF heater.heat_level = 0 # make this number visible to other processes... self._heater_level.value = heater.heat_level self.heat_setting = 0 # calculate sleep time to stick to 0.25sec period comp_time = datetime.datetime.now() - start sleep_duration = 0.25 - comp_time.total_seconds() if sleep_duration > 0: time.sleep(sleep_duration) self._ser.close() # reset disconnect flag self._disconnect.value = 0 # reset connection values self._connected.value = 0 self._connect_state.value = self.CS_NOT_CONNECTED # print("We are disconnected.") def _process_reponse_byte(self, read_state, _byte, r, update_data_event): err = False if self.LOOKING_FOR_HEADER_1 == read_state: if b'\xAA' == _byte: read_state = self.LOOKING_FOR_HEADER_2 elif self.LOOKING_FOR_HEADER_2 == read_state: if b'\xAA' == _byte: read_state = self.PACKET_DATA # reset packet array now... r = [] else: read_state = self.LOOKING_FOR_HEADER_1 elif self.PACKET_DATA == read_state: if b'\xAA' == _byte: # this could be the start of an end of packet marker read_state = self.LOOKING_FOR_FOOTER_2 else: r.append(_byte) # SR700 FW bug - if current temp is 250 degF (0xFA), # the FW does not transmit the footer at all. # fake the footer here. if(len(r) == 10 and b'\xFA' == _byte): # we will 'fake' a footer to make this decoder work # as intended read_state, r, _ = ( self._process_reponse_byte( read_state, b'\xAA', r, update_data_event)) read_state, r, err = ( self._process_reponse_byte( read_state, b'\xFA', r, update_data_event)) elif self.LOOKING_FOR_FOOTER_2 == read_state: if b'\xFA' == _byte: # OK we have a full packet - PROCESS PACKET err = self._process_response_data(r, update_data_event) read_state = self.LOOKING_FOR_HEADER_1 else: # the last byte was not the beginning of the footer r.append(b'\xAA') read_state = self.PACKET_DATA read_state, r, err = self._process_reponse_byte( read_state, _byte, r, update_data_event) else: # error state, shouldn't happen... logging.error('_process_reponse_byte - invalid read_state %d' % read_state) read_state = self.LOOKING_FOR_HEADER_1 err = True return read_state, r, err def _process_response_data(self, r, update_data_event): err = False if len(r) != 10: logging.warn('read packet data len not 10, got: %d' % len(r)) logging.warn('RD: ' + str(binascii.hexlify(b''.join(r)))) err = True else: temp = struct.unpack(">H", b''.join(r[8:10]))[0] if(temp == 65280): self.current_temp = 150 elif(temp > 550 or temp < 150): logging.warn('temperature out of range: reinitializing...') self._initialize() err = True return else: self.current_temp = temp if(update_data_event is not None): update_data_event.set() return err def _timer(self, state_transition_event=None): """Timer loop used to keep track of the time while roasting or cooling. If the time remaining reaches zero, the roaster will call the supplied state transistion function or the roaster will be set to the idle state.""" while not self._teardown.value: state = self.get_roaster_state() if(state == 'roasting' or state == 'cooling'): time.sleep(1) self.total_time += 1 if(self.time_remaining > 0): self.time_remaining -= 1 else: if(state_transition_event is not None): state_transition_event.set() else: self.idle() else: time.sleep(0.01) def get_roaster_state(self): """Returns a string based upon the current state of the roaster. Will raise an exception if the state is unknown. Returns: 'idle' if idle, 'sleeping' if sleeping, 'cooling' if cooling, 'roasting' if roasting, 'connecting' if in hardware connection phase, 'unknown' otherwise """ value = self._current_state.value if(value == b'\x02\x01'): return 'idle' elif(value == b'\x04\x04'): return 'cooling' elif(value == b'\x08\x01'): return 'sleeping' # handle null bytes as empty strings elif(value == b'\x00\x00' or value == b''): return 'connecting' elif(value == b'\x04\x02'): return 'roasting' else: return 'unknown' def _generate_packet(self): """Generates a packet based upon the current class variables. Note that current temperature is not sent, as the original application sent zeros to the roaster for the current temperature.""" roaster_time = utils.seconds_to_float(self._time_remaining.value) packet = ( self._header.value + self._temp_unit.value + self._flags.value + self._current_state.value + struct.pack(">B", self._fan_speed.value) + struct.pack(">B", int(round(roaster_time * 10.0))) + struct.pack(">B", self._heat_setting.value) + b'\x00\x00' + self._footer) return packet def idle(self): """Sets the current state of the roaster to idle.""" self._current_state.value = b'\x02\x01' def roast(self): """Sets the current state of the roaster to roast and begins roasting.""" self._current_state.value = b'\x04\x02' def cool(self): """Sets the current state of the roaster to cool. The roaster expects that cool will be run after roast, and will not work as expected if ran before.""" self._current_state.value = b'\x04\x04' def sleep(self): """Sets the current state of the roaster to sleep. Different than idle in that this will set double dashes on the roaster display rather than digits.""" self._current_state.value = b'\x08\x01'
Roastero/freshroastsr700
freshroastsr700/__init__.py
freshroastsr700.state_transition_run
python
def state_transition_run(self, event_to_wait_on): # with the daemon=Turue setting, this thread should # quit 'automatically' while event_to_wait_on.wait(): event_to_wait_on.clear() if self.state_transition_callback_kill_event.is_set(): return self.state_transition_func()
This is the thread that listens to an event from the timer process to execute the state_transition_func callback in the context of the main process.
train
https://github.com/Roastero/freshroastsr700/blob/49cf4961444c0f56d051d5ac5088ace480b54f02/freshroastsr700/__init__.py#L432-L443
null
class freshroastsr700(object): """A class to interface with a freshroastsr700 coffee roaster. Args: update_data_func (func): A function to call when this object receives new data from the hardware. Defaults to None. state_transition_func (func): A function to call when time_remaining counts down to 0 and the device is either in roasting or cooling state. Defaults to None. thermostat (bool): thermostat mode. if set to True, turns on thermostat mode. In thermostat mode, freshroastsr700 takes control of heat_setting and does software PID control to hit the demanded target_temp. Defaults to False. ext_sw_heater_drive (bool): enable direct control over the internal heat_controller object. Defaults to False. When set to True, the thermostat field is IGNORED, and assumed to be False. Direct control over the software heater_level means that the freshroastsr700's PID controller cannot control the heater. Since thermostat and ext_sw_heater_drive cannot be allowed to both be True, this arg is given precedence over the thermostat arg. Note that (thermostat=False, ext_sw_heater_drive=False), (thermostat=True, ext_sw_heater_drive=False), (thermostat=False, ext_sw_heater_drive=True), are all acceptable arg combinations. Only the (thermostat=True, ext_sw_heater_drive=True), cominbation is not allowed, and this software will set thermostat=False in that case. kp (float): Kp value to use for PID control. Defaults to 0.06. ki (float): Ki value to use for PID control. Defaults to 0.0075. kd (float): Kd value to use for PID control. Defaults to 0.01. heater_segments (int): the pseudo-control range for the internal heat_controller object. Defaults to 8. """ def __init__(self, update_data_func=None, state_transition_func=None, thermostat=False, kp=0.06, ki=0.0075, kd=0.01, heater_segments=8, ext_sw_heater_drive=False): """Create variables used to send in packets to the roaster. The update data function is called when a packet is opened. The state transistion function is used by the timer thread to know what to do next. See wiki for more information on packet structure and fields.""" # constants for protocol decoding self.LOOKING_FOR_HEADER_1 = 0 self.LOOKING_FOR_HEADER_2 = 1 self.PACKET_DATA = 2 self.LOOKING_FOR_FOOTER_2 = 3 # constants for connection state monitoring self.CS_NOT_CONNECTED = -2 self.CS_ATTEMPTING_CONNECT = -1 self.CS_CONNECTING = 0 self.CS_CONNECTED = 1 # constants for connection attempt type self.CA_NONE = 0 self.CA_AUTO = 1 self.CA_SINGLE_SHOT = 2 self._create_update_data_system(update_data_func) self._create_state_transition_system(state_transition_func) self._header = sharedctypes.Array('c', b'\xAA\xAA') self._temp_unit = sharedctypes.Array('c', b'\x61\x74') self._flags = sharedctypes.Array('c', b'\x63') self._current_state = sharedctypes.Array('c', b'\x02\x01') self._footer = b'\xAA\xFA' self._fan_speed = sharedctypes.Value('i', 1) self._heat_setting = sharedctypes.Value('i', 0) self._target_temp = sharedctypes.Value('i', 150) self._current_temp = sharedctypes.Value('i', 150) self._time_remaining = sharedctypes.Value('i', 0) self._total_time = sharedctypes.Value('i', 0) self._disconnect = sharedctypes.Value('i', 0) self._teardown = sharedctypes.Value('i', 0) # for SW PWM heater setting self._heater_level = sharedctypes.Value('i', 0) # the following vars are not process-safe, do not access them # from the comm or timer threads, nor from the callbacks. self._ext_sw_heater_drive = ext_sw_heater_drive if not self._ext_sw_heater_drive: self._thermostat = thermostat else: self._thermostat = False self._pid_kp = kp self._pid_ki = ki self._pid_kd = kd self._heater_bangbang_segments = heater_segments # initialize to 'not connected' self._connected = sharedctypes.Value('i', 0) self._connect_state = sharedctypes.Value('i', self.CS_NOT_CONNECTED) # initialize to 'not trying to connect' self._attempting_connect = sharedctypes.Value('i', self.CA_NONE) # create comm process self.comm_process = mp.Process( target=self._comm, args=( self._thermostat, self._pid_kp, self._pid_ki, self._pid_kd, self._heater_bangbang_segments, self._ext_sw_heater_drive, self.update_data_event,)) self.comm_process.daemon = True self.comm_process.start() # create timer process that counts down time_remaining self.time_process = mp.Process( target=self._timer, args=( self.state_transition_event,)) self.time_process.daemon = True self.time_process.start() def _create_update_data_system( self, update_data_func, setFunc=True, createThread=False): # these callbacks cannot be called from another process in Windows. # Therefore, spawn a thread belonging to the calling process # instead. # the comm and timer processes will set events that the threads # will listen for to initiate the callbacks # only create the mp.Event once - # to mimic create_state_transition_system, for future-proofing # (in this case, currently, this is only called at __init__() time) if not hasattr(self, 'update_data_event'): self.update_data_event = mp.Event() # only create the thread.Event once - this is used to exit # the callback thread if not hasattr(self, 'update_data_callback_kill_event'): self.update_data_callback_kill_event = mp.Event() # destroy an existing thread if we had created one previously if(hasattr(self, 'update_data_thread') and self.update_data_thread is not None): # let's tear this down. To kill it, two events must be set... # in the right sequence! self.update_data_callback_kill_event.set() self.update_data_event.set() self.update_data_thread.join() if setFunc: self.update_data_func = update_data_func if self.update_data_func is not None: if createThread: self.update_data_callback_kill_event.clear() self.update_data_thread = threading.Thread( name='sr700_update_data', target=self.update_data_run, args=(self.update_data_event,), daemon=True ) else: self.update_data_thread = None def _create_state_transition_system( self, state_transition_func, setFunc=True, createThread=False): # these callbacks cannot be called from another process in Windows. # Therefore, spawn a thread belonging to the calling process # instead. # the comm and timer processes will set events that the threads # will listen for to initiate the callbacks # only create the mp.Event once - this fn can get called more # than once, by __init__() and by set_state_transition_func() if not hasattr(self, 'state_transition_event'): self.state_transition_event = mp.Event() # only create the thread.Event once - this is used to exit # the callback thread if not hasattr(self, 'state_transition_callback_kill_event'): self.state_transition_callback_kill_event = mp.Event() # destroy an existing thread if we had created one previously if(hasattr(self, 'state_transition_thread') and self.state_transition_thread is not None): # let's tear this down. To kill it, two events must be set... # in the right sequence! self.state_transition_callback_kill_event.set() self.state_transition_event.set() self.state_transition_thread.join() if setFunc: self.state_transition_func = state_transition_func if self.state_transition_func is not None: if createThread: self.state_transition_callback_kill_event.clear() self.state_transition_thread = threading.Thread( name='sr700_state_transition', target=self.state_transition_run, args=(self.state_transition_event,), daemon=True ) else: self.state_transition_thread = None @property def fan_speed(self): """Get/Set fan speed. Can be 1 to 9 inclusive. Args: Setter: fan_speed (int): fan speed Returns: Getter: (int): fan speed """ return self._fan_speed.value @fan_speed.setter def fan_speed(self, value): """Verifies the value is between 1 and 9 inclusively.""" if value not in range(1, 10): raise exceptions.RoasterValueError self._fan_speed.value = value @property def heat_setting(self): """Get/Set heat setting, 0 to 3 inclusive. 0=off, 3=high. Do not set when running freshroastsr700 in thermostat mode. Args: Setter: heat_setting (int): heat setting Returns: Getter: (int): heat setting """ return self._heat_setting.value @heat_setting.setter def heat_setting(self, value): """Verifies that the heat setting is between 0 and 3.""" if value not in range(0, 4): raise exceptions.RoasterValueError self._heat_setting.value = value @property def target_temp(self): """Get/Set the target temperature for this package's built-in software PID controler. Only used when freshroastsr700 is instantiated with thermostat=True. Args: Setter: value (int): a target temperature in degF between 150 and 551. Returns: Getter: (int) target temperature in degF between 150 and 551 """ return self._target_temp.value @target_temp.setter def target_temp(self, value): if value not in range(150, 551): raise exceptions.RoasterValueError self._target_temp.value = value @property def current_temp(self): """Current temperature of the roast chamber as reported by hardware. Returns: (int) current temperature, in degrees Fahrenheit """ return self._current_temp.value @current_temp.setter def current_temp(self, value): if value not in range(150, 551): raise exceptions.RoasterValueError self._current_temp.value = value @property def time_remaining(self): """The amount of time, in seconds, remaining until a call to the state_transition_func is made. can be set to an arbitrary value up to 600 seconds at any time. When a new value is set, freshroastsr700 will count down from this new value down to 0. time_remaining is decremented to 0 only when in a roasting or cooling state. In other states, the value is not touched. Args: Setter: time_remaining (int): tiem remaining in seconds Returns: Getter: time_remaining(int): time remaining, in seconds """ return self._time_remaining.value @time_remaining.setter def time_remaining(self, value): self._time_remaining.value = value @property def total_time(self): """The total time this instance has been in roasting or cooling state sicne the latest roast began. Returns: total_time (int): time, in seconds """ return self._total_time.value @total_time.setter def total_time(self, value): self._total_time.value = value @property def heater_level(self): """A getter method for _heater_level. When thermostat=True, value is driven by built-in PID controller. When ext_sw_heater_drive=True, value is driven by calls to heater_level(). Min will always be zero, max will be heater_segments (optional instantiation parameter, defaults to 8).""" return self._heater_level.value @heater_level.setter def heater_level(self, value): """Verifies that the heater_level is between 0 and heater_segments. Can only be called when freshroastsr700 object is initialized with ext_sw_heater_drive=True. Will throw RoasterValueError otherwise.""" if self._ext_sw_heater_drive: if value not in range(0, self._heater_bangbang_segments+1): raise exceptions.RoasterValueError self._heater_level.value = value else: raise exceptions.RoasterValueError @property def connected(self): """A getter method for _connected. Indicates that the this software is currently communicating with FreshRoast SR700 hardware.""" return self._connected.value @property def connect_state(self): """A getter method for _connect_state. Indicates the current connection state this software is in for FreshRoast SR700 hardware. Returns: freshroastsr700.CS_NOT_CONNECTED the software is not currenting communicating with hardware, neither was it instructed to do so. A previously failed connection attempt will also result in this state. freshroastsr700.CS_ATTEMPTING_CONNECT A call to auto_connect() or connect() was made, and the software is currently attempting to connect to hardware. freshroastsr700.CS_CONNECTED The hardware was found, and the software is communicating with the hardware. """ return self._connect_state.value def set_state_transition_func(self, func): """THIS FUNCTION MUST BE CALLED BEFORE CALLING freshroastsr700.auto_connect(). Set, or re-set, the state transition function callback. The supplied function will be called from a separate thread within freshroastsr700, triggered by a separate, internal child process. This function will fail if the freshroastsr700 device is already connected to hardware, because by that time, the timer process and thread have already been spawned. Args: state_transition_func (func): the function to call for every state transition. A state transition occurs whenever the freshroastsr700's time_remaining value counts down to 0. Returns: nothing """ if self._connected.value: logging.error("freshroastsr700.set_state_transition_func must be " "called before freshroastsr700.auto_connect()." " Not registering func.") return False # no connection yet. so OK to set func pointer self._create_state_transition_system(func) return True def update_data_run(self, event_to_wait_on): """This is the thread that listens to an event from the comm process to execute the update_data_func callback in the context of the main process. """ # with the daemon=Turue setting, this thread should # quit 'automatically' while event_to_wait_on.wait(): event_to_wait_on.clear() if self.update_data_callback_kill_event.is_set(): return self.update_data_func() def _connect(self): """Do not call this directly - call auto_connect() or connect(), which will call _connect() for you. Connects to the roaster and creates communication thread. Raises a RoasterLokkupError exception if the hardware is not found. """ # the following call raises a RoasterLookupException when the device # is not found. It is port = utils.find_device('1A86:5523') # on some systems, after the device port is added to the device list, # it can take up to 20 seconds after USB insertion for # the port to become available... (!) # let's put a safety timeout in here as a precaution wait_timeout = time.time() + 40.0 # should be PLENTY of time! # let's update the _connect_state while we're at it... self._connect_state.value = self.CS_CONNECTING connect_success = False while time.time() < wait_timeout: try: self._ser = serial.Serial( port=port, baudrate=9600, bytesize=8, parity='N', stopbits=1.5, timeout=0.25, xonxoff=False, rtscts=False, dsrdtr=False) connect_success = True break except serial.SerialException: time.sleep(0.5) if not connect_success: # timeout on attempts raise exceptions.RoasterLookupError self._initialize() def _initialize(self): """Sends the initialization packet to the roaster.""" self._header.value = b'\xAA\x55' self._current_state.value = b'\x00\x00' s = self._generate_packet() self._ser.write(s) self._header.value = b'\xAA\xAA' self._current_state.value = b'\x02\x01' return self._read_existing_recipe() def _write_to_device(self): success = False try: packet = self._generate_packet() logging.debug('WR: ' + str(binascii.hexlify(packet))) self._ser.write(packet) success = True except serial.serialutil.SerialException: logging.error('caught serial exception writing') return success def _read_from_device(self): r = [] footer_reached = False while len(r) < 14 and footer_reached is False: r.append(self._ser.read(1)) if len(r) >= 2 and b''.join(r)[-2:] == self._footer: footer_reached = True logging.debug('RD: ' + str(binascii.hexlify(b''.join(r)))) return b''.join(r) def _read_existing_recipe(self): existing_recipe = [] end_of_recipe = False while not end_of_recipe: bytes_waiting = self._ser.in_waiting if bytes_waiting < 14: # still need to write to device every .25sec it seems time.sleep(0.25) self._write_to_device() else: while (bytes_waiting // 14) > 0: r = self._read_from_device() bytes_waiting = self._ser.in_waiting if len(r) < 14: logging.warn('short packet length') else: existing_recipe.append(r) if r[4:5] == b'\xAF' or r[4:5] == b'\x00': end_of_recipe = True continue return existing_recipe def connect(self): """Attempt to connect to hardware immediately. Will not retry. Check freshroastsr700.connected or freshroastsr700.connect_state to verify result. Raises: freshroastsr700.exeptions.RoasterLookupError No hardware connected to the computer. """ self._start_connect(self.CA_SINGLE_SHOT) while(self._connect_state.value == self.CS_ATTEMPTING_CONNECT or self._connect_state.value == self.CS_CONNECTING): time.sleep(0.1) if self.CS_CONNECTED != self._connect_state.value: raise exceptions.RoasterLookupError def auto_connect(self): """Starts a thread that will automatically connect to the roaster when it is plugged in.""" self._start_connect(self.CA_AUTO) def _start_connect(self, connect_type): """Starts the connection process, as called (internally) from the user context, either from auto_connect() or connect(). Never call this from the _comm() process context. """ if self._connect_state.value != self.CS_NOT_CONNECTED: # already done or in process, assume success return self._connected.value = 0 self._connect_state.value = self.CS_ATTEMPTING_CONNECT # tell comm process to attempt connection self._attempting_connect.value = connect_type # EXTREMELY IMPORTANT - for this to work at all in Windows, # where the above processes are spawned (vs forked in Unix), # the thread objects (as sattributes of this object) must be # assigned to this object AFTER we have spawned the processes. # That way, multiprocessing can pickle the freshroastsr700 # successfully. (It can't pickle thread-related stuff.) if self.update_data_func is not None: # Need to launch the thread that will listen to the event self._create_update_data_system( None, setFunc=False, createThread=True) self.update_data_thread.start() if self.state_transition_func is not None: # Need to launch the thread that will listen to the event self._create_state_transition_system( None, setFunc=False, createThread=True) self.state_transition_thread.start() def _auto_connect(self): """Attempts to connect to the roaster every quarter of a second.""" while not self._teardown.value: try: self._connect() return True except exceptions.RoasterLookupError: time.sleep(.25) return False def disconnect(self): """Stops the communication loop to the roaster. Note that this will not actually stop the roaster itself.""" self._disconnect.value = 1 def terminate(self): """Stops the communication loop to the roaster and closes down all communication processes. Note that this will not actually stop the roaster itself. You will need to instantiate a new freshroastsr700 object after calling this function, in order to re-start communications with the hardware. """ self.disconnect() self._teardown.value = 1 def _comm(self, thermostat=False, kp=0.06, ki=0.0075, kd=0.01, heater_segments=8, ext_sw_heater_drive=False, update_data_event=None): """Do not call this directly - call auto_connect(), which will spawn comm() for you. This is the main communications loop to the roaster. whenever a valid packet is received from the device, if an update_data_event is available, it will be signalled. Args: thermostat (bool): thermostat mode. if set to True, turns on thermostat mode. In thermostat mode, freshroastsr700 takes control of heat_setting and does software PID control to hit the demanded target_temp. ext_sw_heater_drive (bool): enable direct control over the internal heat_controller object. Defaults to False. When set to True, the thermostat field is IGNORED, and assumed to be False. Direct control over the software heater_level means that the PID controller cannot control the heater. Since thermostat and ext_sw_heater_drive cannot be allowed to both be True, this arg is given precedence over the thermostat arg. kp (float): Kp value to use for PID control. Defaults to 0.06. ki (float): Ki value to use for PID control. Defaults to 0.0075. kd (float): Kd value to use for PID control. Defaults to 0.01. heater_segments (int): the pseudo-control range for the internal heat_controller object. Defaults to 8. update_data_event (multiprocessing.Event): If set, allows the comm_process to signal to the parent process that new device data is available. Returns: nothing """ # since this process is started with daemon=True, it should exit # when the owning process terminates. Therefore, safe to loop forever. while not self._teardown.value: # waiting for command to attempt connect # print( "waiting for command to attempt connect") while self._attempting_connect.value == self.CA_NONE: time.sleep(0.25) if self._teardown.value: break # if we're tearing down, bail now. if self._teardown.value: break # we got the command to attempt to connect # change state to 'attempting_connect' self._connect_state.value = self.CS_ATTEMPTING_CONNECT # attempt connection if self.CA_AUTO == self._attempting_connect.value: # this call will block until a connection is achieved # it will also set _connect_state to CS_CONNECTING # if appropriate if self._auto_connect(): # when we unblock, it is an indication of a successful # connection self._connected.value = 1 self._connect_state.value = self.CS_CONNECTED else: # failure, normally due to a timeout self._connected.value = 0 self._connect_state.value = self.CS_NOT_CONNECTED # we failed to connect - start over from the top # reset flag self._attempting_connect.value = self.CA_NONE continue elif self.CA_SINGLE_SHOT == self._attempting_connect.value: # try once, now, if failure, start teh big loop over try: self._connect() self._connected.value = 1 self._connect_state.value = self.CS_CONNECTED except exceptions.RoasterLookupError: self._connected.value = 0 self._connect_state.value = self.CS_NOT_CONNECTED if self._connect_state.value != self.CS_CONNECTED: # we failed to connect - start over from the top # reset flag self._attempting_connect.value = self.CA_NONE continue else: # shouldn't be here # reset flag self._attempting_connect.value = self.CA_NONE continue # We are connected! # print( "We are connected!") # reset flag right away self._attempting_connect.value = self.CA_NONE # Initialize PID controller if thermostat function was specified at # init time pidc = None heater = None if(thermostat): pidc = pid.PID(kp, ki, kd, Output_max=heater_segments, Output_min=0 ) if thermostat or ext_sw_heater_drive: heater = heat_controller(number_of_segments=heater_segments) read_state = self.LOOKING_FOR_HEADER_1 r = [] write_errors = 0 read_errors = 0 while not self._disconnect.value: start = datetime.datetime.now() # write to device if not self._write_to_device(): logging.error('comm - _write_to_device() failed!') write_errors += 1 if write_errors > 3: # it's time to consider the device as being "gone" logging.error('comm - 3 successive write ' 'failures, disconnecting.') self._disconnect.value = 1 continue else: # reset write_errors write_errors = 0 # read from device try: while self._ser.in_waiting: _byte = self._ser.read(1) read_state, r, err = ( self._process_reponse_byte( read_state, _byte, r, update_data_event)) except IOError: # typically happens when device is suddenly unplugged logging.error('comm - read from device failed!') read_errors += 1 if write_errors > 3: # it's time to consider the device as being "gone" logging.error('comm - 3 successive read ' 'failures, disconnecting.') self._disconnect.value = 1 continue else: read_errors = 0 # next, drive SW heater when using # thermostat mode (PID controller calcs) # or in external sw heater drive mode, # when roasting. if thermostat or ext_sw_heater_drive: if 'roasting' == self.get_roaster_state(): if heater.about_to_rollover(): # it's time to use the PID controller value # and set new output level on heater! if ext_sw_heater_drive: # read user-supplied value heater.heat_level = self._heater_level.value else: # thermostat output = pidc.update( self.current_temp, self.target_temp) heater.heat_level = output # make this number visible to other processes... self._heater_level.value = heater.heat_level # read bang-bang heater output array element & apply it if heater.generate_bangbang_output(): # ON self.heat_setting = 3 else: # OFF self.heat_setting = 0 else: # for all other states, heat_level = OFF heater.heat_level = 0 # make this number visible to other processes... self._heater_level.value = heater.heat_level self.heat_setting = 0 # calculate sleep time to stick to 0.25sec period comp_time = datetime.datetime.now() - start sleep_duration = 0.25 - comp_time.total_seconds() if sleep_duration > 0: time.sleep(sleep_duration) self._ser.close() # reset disconnect flag self._disconnect.value = 0 # reset connection values self._connected.value = 0 self._connect_state.value = self.CS_NOT_CONNECTED # print("We are disconnected.") def _process_reponse_byte(self, read_state, _byte, r, update_data_event): err = False if self.LOOKING_FOR_HEADER_1 == read_state: if b'\xAA' == _byte: read_state = self.LOOKING_FOR_HEADER_2 elif self.LOOKING_FOR_HEADER_2 == read_state: if b'\xAA' == _byte: read_state = self.PACKET_DATA # reset packet array now... r = [] else: read_state = self.LOOKING_FOR_HEADER_1 elif self.PACKET_DATA == read_state: if b'\xAA' == _byte: # this could be the start of an end of packet marker read_state = self.LOOKING_FOR_FOOTER_2 else: r.append(_byte) # SR700 FW bug - if current temp is 250 degF (0xFA), # the FW does not transmit the footer at all. # fake the footer here. if(len(r) == 10 and b'\xFA' == _byte): # we will 'fake' a footer to make this decoder work # as intended read_state, r, _ = ( self._process_reponse_byte( read_state, b'\xAA', r, update_data_event)) read_state, r, err = ( self._process_reponse_byte( read_state, b'\xFA', r, update_data_event)) elif self.LOOKING_FOR_FOOTER_2 == read_state: if b'\xFA' == _byte: # OK we have a full packet - PROCESS PACKET err = self._process_response_data(r, update_data_event) read_state = self.LOOKING_FOR_HEADER_1 else: # the last byte was not the beginning of the footer r.append(b'\xAA') read_state = self.PACKET_DATA read_state, r, err = self._process_reponse_byte( read_state, _byte, r, update_data_event) else: # error state, shouldn't happen... logging.error('_process_reponse_byte - invalid read_state %d' % read_state) read_state = self.LOOKING_FOR_HEADER_1 err = True return read_state, r, err def _process_response_data(self, r, update_data_event): err = False if len(r) != 10: logging.warn('read packet data len not 10, got: %d' % len(r)) logging.warn('RD: ' + str(binascii.hexlify(b''.join(r)))) err = True else: temp = struct.unpack(">H", b''.join(r[8:10]))[0] if(temp == 65280): self.current_temp = 150 elif(temp > 550 or temp < 150): logging.warn('temperature out of range: reinitializing...') self._initialize() err = True return else: self.current_temp = temp if(update_data_event is not None): update_data_event.set() return err def _timer(self, state_transition_event=None): """Timer loop used to keep track of the time while roasting or cooling. If the time remaining reaches zero, the roaster will call the supplied state transistion function or the roaster will be set to the idle state.""" while not self._teardown.value: state = self.get_roaster_state() if(state == 'roasting' or state == 'cooling'): time.sleep(1) self.total_time += 1 if(self.time_remaining > 0): self.time_remaining -= 1 else: if(state_transition_event is not None): state_transition_event.set() else: self.idle() else: time.sleep(0.01) def get_roaster_state(self): """Returns a string based upon the current state of the roaster. Will raise an exception if the state is unknown. Returns: 'idle' if idle, 'sleeping' if sleeping, 'cooling' if cooling, 'roasting' if roasting, 'connecting' if in hardware connection phase, 'unknown' otherwise """ value = self._current_state.value if(value == b'\x02\x01'): return 'idle' elif(value == b'\x04\x04'): return 'cooling' elif(value == b'\x08\x01'): return 'sleeping' # handle null bytes as empty strings elif(value == b'\x00\x00' or value == b''): return 'connecting' elif(value == b'\x04\x02'): return 'roasting' else: return 'unknown' def _generate_packet(self): """Generates a packet based upon the current class variables. Note that current temperature is not sent, as the original application sent zeros to the roaster for the current temperature.""" roaster_time = utils.seconds_to_float(self._time_remaining.value) packet = ( self._header.value + self._temp_unit.value + self._flags.value + self._current_state.value + struct.pack(">B", self._fan_speed.value) + struct.pack(">B", int(round(roaster_time * 10.0))) + struct.pack(">B", self._heat_setting.value) + b'\x00\x00' + self._footer) return packet def idle(self): """Sets the current state of the roaster to idle.""" self._current_state.value = b'\x02\x01' def roast(self): """Sets the current state of the roaster to roast and begins roasting.""" self._current_state.value = b'\x04\x02' def cool(self): """Sets the current state of the roaster to cool. The roaster expects that cool will be run after roast, and will not work as expected if ran before.""" self._current_state.value = b'\x04\x04' def sleep(self): """Sets the current state of the roaster to sleep. Different than idle in that this will set double dashes on the roaster display rather than digits.""" self._current_state.value = b'\x08\x01'
Roastero/freshroastsr700
freshroastsr700/__init__.py
freshroastsr700._connect
python
def _connect(self): # the following call raises a RoasterLookupException when the device # is not found. It is port = utils.find_device('1A86:5523') # on some systems, after the device port is added to the device list, # it can take up to 20 seconds after USB insertion for # the port to become available... (!) # let's put a safety timeout in here as a precaution wait_timeout = time.time() + 40.0 # should be PLENTY of time! # let's update the _connect_state while we're at it... self._connect_state.value = self.CS_CONNECTING connect_success = False while time.time() < wait_timeout: try: self._ser = serial.Serial( port=port, baudrate=9600, bytesize=8, parity='N', stopbits=1.5, timeout=0.25, xonxoff=False, rtscts=False, dsrdtr=False) connect_success = True break except serial.SerialException: time.sleep(0.5) if not connect_success: # timeout on attempts raise exceptions.RoasterLookupError self._initialize()
Do not call this directly - call auto_connect() or connect(), which will call _connect() for you. Connects to the roaster and creates communication thread. Raises a RoasterLokkupError exception if the hardware is not found.
train
https://github.com/Roastero/freshroastsr700/blob/49cf4961444c0f56d051d5ac5088ace480b54f02/freshroastsr700/__init__.py#L445-L483
null
class freshroastsr700(object): """A class to interface with a freshroastsr700 coffee roaster. Args: update_data_func (func): A function to call when this object receives new data from the hardware. Defaults to None. state_transition_func (func): A function to call when time_remaining counts down to 0 and the device is either in roasting or cooling state. Defaults to None. thermostat (bool): thermostat mode. if set to True, turns on thermostat mode. In thermostat mode, freshroastsr700 takes control of heat_setting and does software PID control to hit the demanded target_temp. Defaults to False. ext_sw_heater_drive (bool): enable direct control over the internal heat_controller object. Defaults to False. When set to True, the thermostat field is IGNORED, and assumed to be False. Direct control over the software heater_level means that the freshroastsr700's PID controller cannot control the heater. Since thermostat and ext_sw_heater_drive cannot be allowed to both be True, this arg is given precedence over the thermostat arg. Note that (thermostat=False, ext_sw_heater_drive=False), (thermostat=True, ext_sw_heater_drive=False), (thermostat=False, ext_sw_heater_drive=True), are all acceptable arg combinations. Only the (thermostat=True, ext_sw_heater_drive=True), cominbation is not allowed, and this software will set thermostat=False in that case. kp (float): Kp value to use for PID control. Defaults to 0.06. ki (float): Ki value to use for PID control. Defaults to 0.0075. kd (float): Kd value to use for PID control. Defaults to 0.01. heater_segments (int): the pseudo-control range for the internal heat_controller object. Defaults to 8. """ def __init__(self, update_data_func=None, state_transition_func=None, thermostat=False, kp=0.06, ki=0.0075, kd=0.01, heater_segments=8, ext_sw_heater_drive=False): """Create variables used to send in packets to the roaster. The update data function is called when a packet is opened. The state transistion function is used by the timer thread to know what to do next. See wiki for more information on packet structure and fields.""" # constants for protocol decoding self.LOOKING_FOR_HEADER_1 = 0 self.LOOKING_FOR_HEADER_2 = 1 self.PACKET_DATA = 2 self.LOOKING_FOR_FOOTER_2 = 3 # constants for connection state monitoring self.CS_NOT_CONNECTED = -2 self.CS_ATTEMPTING_CONNECT = -1 self.CS_CONNECTING = 0 self.CS_CONNECTED = 1 # constants for connection attempt type self.CA_NONE = 0 self.CA_AUTO = 1 self.CA_SINGLE_SHOT = 2 self._create_update_data_system(update_data_func) self._create_state_transition_system(state_transition_func) self._header = sharedctypes.Array('c', b'\xAA\xAA') self._temp_unit = sharedctypes.Array('c', b'\x61\x74') self._flags = sharedctypes.Array('c', b'\x63') self._current_state = sharedctypes.Array('c', b'\x02\x01') self._footer = b'\xAA\xFA' self._fan_speed = sharedctypes.Value('i', 1) self._heat_setting = sharedctypes.Value('i', 0) self._target_temp = sharedctypes.Value('i', 150) self._current_temp = sharedctypes.Value('i', 150) self._time_remaining = sharedctypes.Value('i', 0) self._total_time = sharedctypes.Value('i', 0) self._disconnect = sharedctypes.Value('i', 0) self._teardown = sharedctypes.Value('i', 0) # for SW PWM heater setting self._heater_level = sharedctypes.Value('i', 0) # the following vars are not process-safe, do not access them # from the comm or timer threads, nor from the callbacks. self._ext_sw_heater_drive = ext_sw_heater_drive if not self._ext_sw_heater_drive: self._thermostat = thermostat else: self._thermostat = False self._pid_kp = kp self._pid_ki = ki self._pid_kd = kd self._heater_bangbang_segments = heater_segments # initialize to 'not connected' self._connected = sharedctypes.Value('i', 0) self._connect_state = sharedctypes.Value('i', self.CS_NOT_CONNECTED) # initialize to 'not trying to connect' self._attempting_connect = sharedctypes.Value('i', self.CA_NONE) # create comm process self.comm_process = mp.Process( target=self._comm, args=( self._thermostat, self._pid_kp, self._pid_ki, self._pid_kd, self._heater_bangbang_segments, self._ext_sw_heater_drive, self.update_data_event,)) self.comm_process.daemon = True self.comm_process.start() # create timer process that counts down time_remaining self.time_process = mp.Process( target=self._timer, args=( self.state_transition_event,)) self.time_process.daemon = True self.time_process.start() def _create_update_data_system( self, update_data_func, setFunc=True, createThread=False): # these callbacks cannot be called from another process in Windows. # Therefore, spawn a thread belonging to the calling process # instead. # the comm and timer processes will set events that the threads # will listen for to initiate the callbacks # only create the mp.Event once - # to mimic create_state_transition_system, for future-proofing # (in this case, currently, this is only called at __init__() time) if not hasattr(self, 'update_data_event'): self.update_data_event = mp.Event() # only create the thread.Event once - this is used to exit # the callback thread if not hasattr(self, 'update_data_callback_kill_event'): self.update_data_callback_kill_event = mp.Event() # destroy an existing thread if we had created one previously if(hasattr(self, 'update_data_thread') and self.update_data_thread is not None): # let's tear this down. To kill it, two events must be set... # in the right sequence! self.update_data_callback_kill_event.set() self.update_data_event.set() self.update_data_thread.join() if setFunc: self.update_data_func = update_data_func if self.update_data_func is not None: if createThread: self.update_data_callback_kill_event.clear() self.update_data_thread = threading.Thread( name='sr700_update_data', target=self.update_data_run, args=(self.update_data_event,), daemon=True ) else: self.update_data_thread = None def _create_state_transition_system( self, state_transition_func, setFunc=True, createThread=False): # these callbacks cannot be called from another process in Windows. # Therefore, spawn a thread belonging to the calling process # instead. # the comm and timer processes will set events that the threads # will listen for to initiate the callbacks # only create the mp.Event once - this fn can get called more # than once, by __init__() and by set_state_transition_func() if not hasattr(self, 'state_transition_event'): self.state_transition_event = mp.Event() # only create the thread.Event once - this is used to exit # the callback thread if not hasattr(self, 'state_transition_callback_kill_event'): self.state_transition_callback_kill_event = mp.Event() # destroy an existing thread if we had created one previously if(hasattr(self, 'state_transition_thread') and self.state_transition_thread is not None): # let's tear this down. To kill it, two events must be set... # in the right sequence! self.state_transition_callback_kill_event.set() self.state_transition_event.set() self.state_transition_thread.join() if setFunc: self.state_transition_func = state_transition_func if self.state_transition_func is not None: if createThread: self.state_transition_callback_kill_event.clear() self.state_transition_thread = threading.Thread( name='sr700_state_transition', target=self.state_transition_run, args=(self.state_transition_event,), daemon=True ) else: self.state_transition_thread = None @property def fan_speed(self): """Get/Set fan speed. Can be 1 to 9 inclusive. Args: Setter: fan_speed (int): fan speed Returns: Getter: (int): fan speed """ return self._fan_speed.value @fan_speed.setter def fan_speed(self, value): """Verifies the value is between 1 and 9 inclusively.""" if value not in range(1, 10): raise exceptions.RoasterValueError self._fan_speed.value = value @property def heat_setting(self): """Get/Set heat setting, 0 to 3 inclusive. 0=off, 3=high. Do not set when running freshroastsr700 in thermostat mode. Args: Setter: heat_setting (int): heat setting Returns: Getter: (int): heat setting """ return self._heat_setting.value @heat_setting.setter def heat_setting(self, value): """Verifies that the heat setting is between 0 and 3.""" if value not in range(0, 4): raise exceptions.RoasterValueError self._heat_setting.value = value @property def target_temp(self): """Get/Set the target temperature for this package's built-in software PID controler. Only used when freshroastsr700 is instantiated with thermostat=True. Args: Setter: value (int): a target temperature in degF between 150 and 551. Returns: Getter: (int) target temperature in degF between 150 and 551 """ return self._target_temp.value @target_temp.setter def target_temp(self, value): if value not in range(150, 551): raise exceptions.RoasterValueError self._target_temp.value = value @property def current_temp(self): """Current temperature of the roast chamber as reported by hardware. Returns: (int) current temperature, in degrees Fahrenheit """ return self._current_temp.value @current_temp.setter def current_temp(self, value): if value not in range(150, 551): raise exceptions.RoasterValueError self._current_temp.value = value @property def time_remaining(self): """The amount of time, in seconds, remaining until a call to the state_transition_func is made. can be set to an arbitrary value up to 600 seconds at any time. When a new value is set, freshroastsr700 will count down from this new value down to 0. time_remaining is decremented to 0 only when in a roasting or cooling state. In other states, the value is not touched. Args: Setter: time_remaining (int): tiem remaining in seconds Returns: Getter: time_remaining(int): time remaining, in seconds """ return self._time_remaining.value @time_remaining.setter def time_remaining(self, value): self._time_remaining.value = value @property def total_time(self): """The total time this instance has been in roasting or cooling state sicne the latest roast began. Returns: total_time (int): time, in seconds """ return self._total_time.value @total_time.setter def total_time(self, value): self._total_time.value = value @property def heater_level(self): """A getter method for _heater_level. When thermostat=True, value is driven by built-in PID controller. When ext_sw_heater_drive=True, value is driven by calls to heater_level(). Min will always be zero, max will be heater_segments (optional instantiation parameter, defaults to 8).""" return self._heater_level.value @heater_level.setter def heater_level(self, value): """Verifies that the heater_level is between 0 and heater_segments. Can only be called when freshroastsr700 object is initialized with ext_sw_heater_drive=True. Will throw RoasterValueError otherwise.""" if self._ext_sw_heater_drive: if value not in range(0, self._heater_bangbang_segments+1): raise exceptions.RoasterValueError self._heater_level.value = value else: raise exceptions.RoasterValueError @property def connected(self): """A getter method for _connected. Indicates that the this software is currently communicating with FreshRoast SR700 hardware.""" return self._connected.value @property def connect_state(self): """A getter method for _connect_state. Indicates the current connection state this software is in for FreshRoast SR700 hardware. Returns: freshroastsr700.CS_NOT_CONNECTED the software is not currenting communicating with hardware, neither was it instructed to do so. A previously failed connection attempt will also result in this state. freshroastsr700.CS_ATTEMPTING_CONNECT A call to auto_connect() or connect() was made, and the software is currently attempting to connect to hardware. freshroastsr700.CS_CONNECTED The hardware was found, and the software is communicating with the hardware. """ return self._connect_state.value def set_state_transition_func(self, func): """THIS FUNCTION MUST BE CALLED BEFORE CALLING freshroastsr700.auto_connect(). Set, or re-set, the state transition function callback. The supplied function will be called from a separate thread within freshroastsr700, triggered by a separate, internal child process. This function will fail if the freshroastsr700 device is already connected to hardware, because by that time, the timer process and thread have already been spawned. Args: state_transition_func (func): the function to call for every state transition. A state transition occurs whenever the freshroastsr700's time_remaining value counts down to 0. Returns: nothing """ if self._connected.value: logging.error("freshroastsr700.set_state_transition_func must be " "called before freshroastsr700.auto_connect()." " Not registering func.") return False # no connection yet. so OK to set func pointer self._create_state_transition_system(func) return True def update_data_run(self, event_to_wait_on): """This is the thread that listens to an event from the comm process to execute the update_data_func callback in the context of the main process. """ # with the daemon=Turue setting, this thread should # quit 'automatically' while event_to_wait_on.wait(): event_to_wait_on.clear() if self.update_data_callback_kill_event.is_set(): return self.update_data_func() def state_transition_run(self, event_to_wait_on): """This is the thread that listens to an event from the timer process to execute the state_transition_func callback in the context of the main process. """ # with the daemon=Turue setting, this thread should # quit 'automatically' while event_to_wait_on.wait(): event_to_wait_on.clear() if self.state_transition_callback_kill_event.is_set(): return self.state_transition_func() def _initialize(self): """Sends the initialization packet to the roaster.""" self._header.value = b'\xAA\x55' self._current_state.value = b'\x00\x00' s = self._generate_packet() self._ser.write(s) self._header.value = b'\xAA\xAA' self._current_state.value = b'\x02\x01' return self._read_existing_recipe() def _write_to_device(self): success = False try: packet = self._generate_packet() logging.debug('WR: ' + str(binascii.hexlify(packet))) self._ser.write(packet) success = True except serial.serialutil.SerialException: logging.error('caught serial exception writing') return success def _read_from_device(self): r = [] footer_reached = False while len(r) < 14 and footer_reached is False: r.append(self._ser.read(1)) if len(r) >= 2 and b''.join(r)[-2:] == self._footer: footer_reached = True logging.debug('RD: ' + str(binascii.hexlify(b''.join(r)))) return b''.join(r) def _read_existing_recipe(self): existing_recipe = [] end_of_recipe = False while not end_of_recipe: bytes_waiting = self._ser.in_waiting if bytes_waiting < 14: # still need to write to device every .25sec it seems time.sleep(0.25) self._write_to_device() else: while (bytes_waiting // 14) > 0: r = self._read_from_device() bytes_waiting = self._ser.in_waiting if len(r) < 14: logging.warn('short packet length') else: existing_recipe.append(r) if r[4:5] == b'\xAF' or r[4:5] == b'\x00': end_of_recipe = True continue return existing_recipe def connect(self): """Attempt to connect to hardware immediately. Will not retry. Check freshroastsr700.connected or freshroastsr700.connect_state to verify result. Raises: freshroastsr700.exeptions.RoasterLookupError No hardware connected to the computer. """ self._start_connect(self.CA_SINGLE_SHOT) while(self._connect_state.value == self.CS_ATTEMPTING_CONNECT or self._connect_state.value == self.CS_CONNECTING): time.sleep(0.1) if self.CS_CONNECTED != self._connect_state.value: raise exceptions.RoasterLookupError def auto_connect(self): """Starts a thread that will automatically connect to the roaster when it is plugged in.""" self._start_connect(self.CA_AUTO) def _start_connect(self, connect_type): """Starts the connection process, as called (internally) from the user context, either from auto_connect() or connect(). Never call this from the _comm() process context. """ if self._connect_state.value != self.CS_NOT_CONNECTED: # already done or in process, assume success return self._connected.value = 0 self._connect_state.value = self.CS_ATTEMPTING_CONNECT # tell comm process to attempt connection self._attempting_connect.value = connect_type # EXTREMELY IMPORTANT - for this to work at all in Windows, # where the above processes are spawned (vs forked in Unix), # the thread objects (as sattributes of this object) must be # assigned to this object AFTER we have spawned the processes. # That way, multiprocessing can pickle the freshroastsr700 # successfully. (It can't pickle thread-related stuff.) if self.update_data_func is not None: # Need to launch the thread that will listen to the event self._create_update_data_system( None, setFunc=False, createThread=True) self.update_data_thread.start() if self.state_transition_func is not None: # Need to launch the thread that will listen to the event self._create_state_transition_system( None, setFunc=False, createThread=True) self.state_transition_thread.start() def _auto_connect(self): """Attempts to connect to the roaster every quarter of a second.""" while not self._teardown.value: try: self._connect() return True except exceptions.RoasterLookupError: time.sleep(.25) return False def disconnect(self): """Stops the communication loop to the roaster. Note that this will not actually stop the roaster itself.""" self._disconnect.value = 1 def terminate(self): """Stops the communication loop to the roaster and closes down all communication processes. Note that this will not actually stop the roaster itself. You will need to instantiate a new freshroastsr700 object after calling this function, in order to re-start communications with the hardware. """ self.disconnect() self._teardown.value = 1 def _comm(self, thermostat=False, kp=0.06, ki=0.0075, kd=0.01, heater_segments=8, ext_sw_heater_drive=False, update_data_event=None): """Do not call this directly - call auto_connect(), which will spawn comm() for you. This is the main communications loop to the roaster. whenever a valid packet is received from the device, if an update_data_event is available, it will be signalled. Args: thermostat (bool): thermostat mode. if set to True, turns on thermostat mode. In thermostat mode, freshroastsr700 takes control of heat_setting and does software PID control to hit the demanded target_temp. ext_sw_heater_drive (bool): enable direct control over the internal heat_controller object. Defaults to False. When set to True, the thermostat field is IGNORED, and assumed to be False. Direct control over the software heater_level means that the PID controller cannot control the heater. Since thermostat and ext_sw_heater_drive cannot be allowed to both be True, this arg is given precedence over the thermostat arg. kp (float): Kp value to use for PID control. Defaults to 0.06. ki (float): Ki value to use for PID control. Defaults to 0.0075. kd (float): Kd value to use for PID control. Defaults to 0.01. heater_segments (int): the pseudo-control range for the internal heat_controller object. Defaults to 8. update_data_event (multiprocessing.Event): If set, allows the comm_process to signal to the parent process that new device data is available. Returns: nothing """ # since this process is started with daemon=True, it should exit # when the owning process terminates. Therefore, safe to loop forever. while not self._teardown.value: # waiting for command to attempt connect # print( "waiting for command to attempt connect") while self._attempting_connect.value == self.CA_NONE: time.sleep(0.25) if self._teardown.value: break # if we're tearing down, bail now. if self._teardown.value: break # we got the command to attempt to connect # change state to 'attempting_connect' self._connect_state.value = self.CS_ATTEMPTING_CONNECT # attempt connection if self.CA_AUTO == self._attempting_connect.value: # this call will block until a connection is achieved # it will also set _connect_state to CS_CONNECTING # if appropriate if self._auto_connect(): # when we unblock, it is an indication of a successful # connection self._connected.value = 1 self._connect_state.value = self.CS_CONNECTED else: # failure, normally due to a timeout self._connected.value = 0 self._connect_state.value = self.CS_NOT_CONNECTED # we failed to connect - start over from the top # reset flag self._attempting_connect.value = self.CA_NONE continue elif self.CA_SINGLE_SHOT == self._attempting_connect.value: # try once, now, if failure, start teh big loop over try: self._connect() self._connected.value = 1 self._connect_state.value = self.CS_CONNECTED except exceptions.RoasterLookupError: self._connected.value = 0 self._connect_state.value = self.CS_NOT_CONNECTED if self._connect_state.value != self.CS_CONNECTED: # we failed to connect - start over from the top # reset flag self._attempting_connect.value = self.CA_NONE continue else: # shouldn't be here # reset flag self._attempting_connect.value = self.CA_NONE continue # We are connected! # print( "We are connected!") # reset flag right away self._attempting_connect.value = self.CA_NONE # Initialize PID controller if thermostat function was specified at # init time pidc = None heater = None if(thermostat): pidc = pid.PID(kp, ki, kd, Output_max=heater_segments, Output_min=0 ) if thermostat or ext_sw_heater_drive: heater = heat_controller(number_of_segments=heater_segments) read_state = self.LOOKING_FOR_HEADER_1 r = [] write_errors = 0 read_errors = 0 while not self._disconnect.value: start = datetime.datetime.now() # write to device if not self._write_to_device(): logging.error('comm - _write_to_device() failed!') write_errors += 1 if write_errors > 3: # it's time to consider the device as being "gone" logging.error('comm - 3 successive write ' 'failures, disconnecting.') self._disconnect.value = 1 continue else: # reset write_errors write_errors = 0 # read from device try: while self._ser.in_waiting: _byte = self._ser.read(1) read_state, r, err = ( self._process_reponse_byte( read_state, _byte, r, update_data_event)) except IOError: # typically happens when device is suddenly unplugged logging.error('comm - read from device failed!') read_errors += 1 if write_errors > 3: # it's time to consider the device as being "gone" logging.error('comm - 3 successive read ' 'failures, disconnecting.') self._disconnect.value = 1 continue else: read_errors = 0 # next, drive SW heater when using # thermostat mode (PID controller calcs) # or in external sw heater drive mode, # when roasting. if thermostat or ext_sw_heater_drive: if 'roasting' == self.get_roaster_state(): if heater.about_to_rollover(): # it's time to use the PID controller value # and set new output level on heater! if ext_sw_heater_drive: # read user-supplied value heater.heat_level = self._heater_level.value else: # thermostat output = pidc.update( self.current_temp, self.target_temp) heater.heat_level = output # make this number visible to other processes... self._heater_level.value = heater.heat_level # read bang-bang heater output array element & apply it if heater.generate_bangbang_output(): # ON self.heat_setting = 3 else: # OFF self.heat_setting = 0 else: # for all other states, heat_level = OFF heater.heat_level = 0 # make this number visible to other processes... self._heater_level.value = heater.heat_level self.heat_setting = 0 # calculate sleep time to stick to 0.25sec period comp_time = datetime.datetime.now() - start sleep_duration = 0.25 - comp_time.total_seconds() if sleep_duration > 0: time.sleep(sleep_duration) self._ser.close() # reset disconnect flag self._disconnect.value = 0 # reset connection values self._connected.value = 0 self._connect_state.value = self.CS_NOT_CONNECTED # print("We are disconnected.") def _process_reponse_byte(self, read_state, _byte, r, update_data_event): err = False if self.LOOKING_FOR_HEADER_1 == read_state: if b'\xAA' == _byte: read_state = self.LOOKING_FOR_HEADER_2 elif self.LOOKING_FOR_HEADER_2 == read_state: if b'\xAA' == _byte: read_state = self.PACKET_DATA # reset packet array now... r = [] else: read_state = self.LOOKING_FOR_HEADER_1 elif self.PACKET_DATA == read_state: if b'\xAA' == _byte: # this could be the start of an end of packet marker read_state = self.LOOKING_FOR_FOOTER_2 else: r.append(_byte) # SR700 FW bug - if current temp is 250 degF (0xFA), # the FW does not transmit the footer at all. # fake the footer here. if(len(r) == 10 and b'\xFA' == _byte): # we will 'fake' a footer to make this decoder work # as intended read_state, r, _ = ( self._process_reponse_byte( read_state, b'\xAA', r, update_data_event)) read_state, r, err = ( self._process_reponse_byte( read_state, b'\xFA', r, update_data_event)) elif self.LOOKING_FOR_FOOTER_2 == read_state: if b'\xFA' == _byte: # OK we have a full packet - PROCESS PACKET err = self._process_response_data(r, update_data_event) read_state = self.LOOKING_FOR_HEADER_1 else: # the last byte was not the beginning of the footer r.append(b'\xAA') read_state = self.PACKET_DATA read_state, r, err = self._process_reponse_byte( read_state, _byte, r, update_data_event) else: # error state, shouldn't happen... logging.error('_process_reponse_byte - invalid read_state %d' % read_state) read_state = self.LOOKING_FOR_HEADER_1 err = True return read_state, r, err def _process_response_data(self, r, update_data_event): err = False if len(r) != 10: logging.warn('read packet data len not 10, got: %d' % len(r)) logging.warn('RD: ' + str(binascii.hexlify(b''.join(r)))) err = True else: temp = struct.unpack(">H", b''.join(r[8:10]))[0] if(temp == 65280): self.current_temp = 150 elif(temp > 550 or temp < 150): logging.warn('temperature out of range: reinitializing...') self._initialize() err = True return else: self.current_temp = temp if(update_data_event is not None): update_data_event.set() return err def _timer(self, state_transition_event=None): """Timer loop used to keep track of the time while roasting or cooling. If the time remaining reaches zero, the roaster will call the supplied state transistion function or the roaster will be set to the idle state.""" while not self._teardown.value: state = self.get_roaster_state() if(state == 'roasting' or state == 'cooling'): time.sleep(1) self.total_time += 1 if(self.time_remaining > 0): self.time_remaining -= 1 else: if(state_transition_event is not None): state_transition_event.set() else: self.idle() else: time.sleep(0.01) def get_roaster_state(self): """Returns a string based upon the current state of the roaster. Will raise an exception if the state is unknown. Returns: 'idle' if idle, 'sleeping' if sleeping, 'cooling' if cooling, 'roasting' if roasting, 'connecting' if in hardware connection phase, 'unknown' otherwise """ value = self._current_state.value if(value == b'\x02\x01'): return 'idle' elif(value == b'\x04\x04'): return 'cooling' elif(value == b'\x08\x01'): return 'sleeping' # handle null bytes as empty strings elif(value == b'\x00\x00' or value == b''): return 'connecting' elif(value == b'\x04\x02'): return 'roasting' else: return 'unknown' def _generate_packet(self): """Generates a packet based upon the current class variables. Note that current temperature is not sent, as the original application sent zeros to the roaster for the current temperature.""" roaster_time = utils.seconds_to_float(self._time_remaining.value) packet = ( self._header.value + self._temp_unit.value + self._flags.value + self._current_state.value + struct.pack(">B", self._fan_speed.value) + struct.pack(">B", int(round(roaster_time * 10.0))) + struct.pack(">B", self._heat_setting.value) + b'\x00\x00' + self._footer) return packet def idle(self): """Sets the current state of the roaster to idle.""" self._current_state.value = b'\x02\x01' def roast(self): """Sets the current state of the roaster to roast and begins roasting.""" self._current_state.value = b'\x04\x02' def cool(self): """Sets the current state of the roaster to cool. The roaster expects that cool will be run after roast, and will not work as expected if ran before.""" self._current_state.value = b'\x04\x04' def sleep(self): """Sets the current state of the roaster to sleep. Different than idle in that this will set double dashes on the roaster display rather than digits.""" self._current_state.value = b'\x08\x01'
Roastero/freshroastsr700
freshroastsr700/__init__.py
freshroastsr700._initialize
python
def _initialize(self): self._header.value = b'\xAA\x55' self._current_state.value = b'\x00\x00' s = self._generate_packet() self._ser.write(s) self._header.value = b'\xAA\xAA' self._current_state.value = b'\x02\x01' return self._read_existing_recipe()
Sends the initialization packet to the roaster.
train
https://github.com/Roastero/freshroastsr700/blob/49cf4961444c0f56d051d5ac5088ace480b54f02/freshroastsr700/__init__.py#L485-L494
null
class freshroastsr700(object): """A class to interface with a freshroastsr700 coffee roaster. Args: update_data_func (func): A function to call when this object receives new data from the hardware. Defaults to None. state_transition_func (func): A function to call when time_remaining counts down to 0 and the device is either in roasting or cooling state. Defaults to None. thermostat (bool): thermostat mode. if set to True, turns on thermostat mode. In thermostat mode, freshroastsr700 takes control of heat_setting and does software PID control to hit the demanded target_temp. Defaults to False. ext_sw_heater_drive (bool): enable direct control over the internal heat_controller object. Defaults to False. When set to True, the thermostat field is IGNORED, and assumed to be False. Direct control over the software heater_level means that the freshroastsr700's PID controller cannot control the heater. Since thermostat and ext_sw_heater_drive cannot be allowed to both be True, this arg is given precedence over the thermostat arg. Note that (thermostat=False, ext_sw_heater_drive=False), (thermostat=True, ext_sw_heater_drive=False), (thermostat=False, ext_sw_heater_drive=True), are all acceptable arg combinations. Only the (thermostat=True, ext_sw_heater_drive=True), cominbation is not allowed, and this software will set thermostat=False in that case. kp (float): Kp value to use for PID control. Defaults to 0.06. ki (float): Ki value to use for PID control. Defaults to 0.0075. kd (float): Kd value to use for PID control. Defaults to 0.01. heater_segments (int): the pseudo-control range for the internal heat_controller object. Defaults to 8. """ def __init__(self, update_data_func=None, state_transition_func=None, thermostat=False, kp=0.06, ki=0.0075, kd=0.01, heater_segments=8, ext_sw_heater_drive=False): """Create variables used to send in packets to the roaster. The update data function is called when a packet is opened. The state transistion function is used by the timer thread to know what to do next. See wiki for more information on packet structure and fields.""" # constants for protocol decoding self.LOOKING_FOR_HEADER_1 = 0 self.LOOKING_FOR_HEADER_2 = 1 self.PACKET_DATA = 2 self.LOOKING_FOR_FOOTER_2 = 3 # constants for connection state monitoring self.CS_NOT_CONNECTED = -2 self.CS_ATTEMPTING_CONNECT = -1 self.CS_CONNECTING = 0 self.CS_CONNECTED = 1 # constants for connection attempt type self.CA_NONE = 0 self.CA_AUTO = 1 self.CA_SINGLE_SHOT = 2 self._create_update_data_system(update_data_func) self._create_state_transition_system(state_transition_func) self._header = sharedctypes.Array('c', b'\xAA\xAA') self._temp_unit = sharedctypes.Array('c', b'\x61\x74') self._flags = sharedctypes.Array('c', b'\x63') self._current_state = sharedctypes.Array('c', b'\x02\x01') self._footer = b'\xAA\xFA' self._fan_speed = sharedctypes.Value('i', 1) self._heat_setting = sharedctypes.Value('i', 0) self._target_temp = sharedctypes.Value('i', 150) self._current_temp = sharedctypes.Value('i', 150) self._time_remaining = sharedctypes.Value('i', 0) self._total_time = sharedctypes.Value('i', 0) self._disconnect = sharedctypes.Value('i', 0) self._teardown = sharedctypes.Value('i', 0) # for SW PWM heater setting self._heater_level = sharedctypes.Value('i', 0) # the following vars are not process-safe, do not access them # from the comm or timer threads, nor from the callbacks. self._ext_sw_heater_drive = ext_sw_heater_drive if not self._ext_sw_heater_drive: self._thermostat = thermostat else: self._thermostat = False self._pid_kp = kp self._pid_ki = ki self._pid_kd = kd self._heater_bangbang_segments = heater_segments # initialize to 'not connected' self._connected = sharedctypes.Value('i', 0) self._connect_state = sharedctypes.Value('i', self.CS_NOT_CONNECTED) # initialize to 'not trying to connect' self._attempting_connect = sharedctypes.Value('i', self.CA_NONE) # create comm process self.comm_process = mp.Process( target=self._comm, args=( self._thermostat, self._pid_kp, self._pid_ki, self._pid_kd, self._heater_bangbang_segments, self._ext_sw_heater_drive, self.update_data_event,)) self.comm_process.daemon = True self.comm_process.start() # create timer process that counts down time_remaining self.time_process = mp.Process( target=self._timer, args=( self.state_transition_event,)) self.time_process.daemon = True self.time_process.start() def _create_update_data_system( self, update_data_func, setFunc=True, createThread=False): # these callbacks cannot be called from another process in Windows. # Therefore, spawn a thread belonging to the calling process # instead. # the comm and timer processes will set events that the threads # will listen for to initiate the callbacks # only create the mp.Event once - # to mimic create_state_transition_system, for future-proofing # (in this case, currently, this is only called at __init__() time) if not hasattr(self, 'update_data_event'): self.update_data_event = mp.Event() # only create the thread.Event once - this is used to exit # the callback thread if not hasattr(self, 'update_data_callback_kill_event'): self.update_data_callback_kill_event = mp.Event() # destroy an existing thread if we had created one previously if(hasattr(self, 'update_data_thread') and self.update_data_thread is not None): # let's tear this down. To kill it, two events must be set... # in the right sequence! self.update_data_callback_kill_event.set() self.update_data_event.set() self.update_data_thread.join() if setFunc: self.update_data_func = update_data_func if self.update_data_func is not None: if createThread: self.update_data_callback_kill_event.clear() self.update_data_thread = threading.Thread( name='sr700_update_data', target=self.update_data_run, args=(self.update_data_event,), daemon=True ) else: self.update_data_thread = None def _create_state_transition_system( self, state_transition_func, setFunc=True, createThread=False): # these callbacks cannot be called from another process in Windows. # Therefore, spawn a thread belonging to the calling process # instead. # the comm and timer processes will set events that the threads # will listen for to initiate the callbacks # only create the mp.Event once - this fn can get called more # than once, by __init__() and by set_state_transition_func() if not hasattr(self, 'state_transition_event'): self.state_transition_event = mp.Event() # only create the thread.Event once - this is used to exit # the callback thread if not hasattr(self, 'state_transition_callback_kill_event'): self.state_transition_callback_kill_event = mp.Event() # destroy an existing thread if we had created one previously if(hasattr(self, 'state_transition_thread') and self.state_transition_thread is not None): # let's tear this down. To kill it, two events must be set... # in the right sequence! self.state_transition_callback_kill_event.set() self.state_transition_event.set() self.state_transition_thread.join() if setFunc: self.state_transition_func = state_transition_func if self.state_transition_func is not None: if createThread: self.state_transition_callback_kill_event.clear() self.state_transition_thread = threading.Thread( name='sr700_state_transition', target=self.state_transition_run, args=(self.state_transition_event,), daemon=True ) else: self.state_transition_thread = None @property def fan_speed(self): """Get/Set fan speed. Can be 1 to 9 inclusive. Args: Setter: fan_speed (int): fan speed Returns: Getter: (int): fan speed """ return self._fan_speed.value @fan_speed.setter def fan_speed(self, value): """Verifies the value is between 1 and 9 inclusively.""" if value not in range(1, 10): raise exceptions.RoasterValueError self._fan_speed.value = value @property def heat_setting(self): """Get/Set heat setting, 0 to 3 inclusive. 0=off, 3=high. Do not set when running freshroastsr700 in thermostat mode. Args: Setter: heat_setting (int): heat setting Returns: Getter: (int): heat setting """ return self._heat_setting.value @heat_setting.setter def heat_setting(self, value): """Verifies that the heat setting is between 0 and 3.""" if value not in range(0, 4): raise exceptions.RoasterValueError self._heat_setting.value = value @property def target_temp(self): """Get/Set the target temperature for this package's built-in software PID controler. Only used when freshroastsr700 is instantiated with thermostat=True. Args: Setter: value (int): a target temperature in degF between 150 and 551. Returns: Getter: (int) target temperature in degF between 150 and 551 """ return self._target_temp.value @target_temp.setter def target_temp(self, value): if value not in range(150, 551): raise exceptions.RoasterValueError self._target_temp.value = value @property def current_temp(self): """Current temperature of the roast chamber as reported by hardware. Returns: (int) current temperature, in degrees Fahrenheit """ return self._current_temp.value @current_temp.setter def current_temp(self, value): if value not in range(150, 551): raise exceptions.RoasterValueError self._current_temp.value = value @property def time_remaining(self): """The amount of time, in seconds, remaining until a call to the state_transition_func is made. can be set to an arbitrary value up to 600 seconds at any time. When a new value is set, freshroastsr700 will count down from this new value down to 0. time_remaining is decremented to 0 only when in a roasting or cooling state. In other states, the value is not touched. Args: Setter: time_remaining (int): tiem remaining in seconds Returns: Getter: time_remaining(int): time remaining, in seconds """ return self._time_remaining.value @time_remaining.setter def time_remaining(self, value): self._time_remaining.value = value @property def total_time(self): """The total time this instance has been in roasting or cooling state sicne the latest roast began. Returns: total_time (int): time, in seconds """ return self._total_time.value @total_time.setter def total_time(self, value): self._total_time.value = value @property def heater_level(self): """A getter method for _heater_level. When thermostat=True, value is driven by built-in PID controller. When ext_sw_heater_drive=True, value is driven by calls to heater_level(). Min will always be zero, max will be heater_segments (optional instantiation parameter, defaults to 8).""" return self._heater_level.value @heater_level.setter def heater_level(self, value): """Verifies that the heater_level is between 0 and heater_segments. Can only be called when freshroastsr700 object is initialized with ext_sw_heater_drive=True. Will throw RoasterValueError otherwise.""" if self._ext_sw_heater_drive: if value not in range(0, self._heater_bangbang_segments+1): raise exceptions.RoasterValueError self._heater_level.value = value else: raise exceptions.RoasterValueError @property def connected(self): """A getter method for _connected. Indicates that the this software is currently communicating with FreshRoast SR700 hardware.""" return self._connected.value @property def connect_state(self): """A getter method for _connect_state. Indicates the current connection state this software is in for FreshRoast SR700 hardware. Returns: freshroastsr700.CS_NOT_CONNECTED the software is not currenting communicating with hardware, neither was it instructed to do so. A previously failed connection attempt will also result in this state. freshroastsr700.CS_ATTEMPTING_CONNECT A call to auto_connect() or connect() was made, and the software is currently attempting to connect to hardware. freshroastsr700.CS_CONNECTED The hardware was found, and the software is communicating with the hardware. """ return self._connect_state.value def set_state_transition_func(self, func): """THIS FUNCTION MUST BE CALLED BEFORE CALLING freshroastsr700.auto_connect(). Set, or re-set, the state transition function callback. The supplied function will be called from a separate thread within freshroastsr700, triggered by a separate, internal child process. This function will fail if the freshroastsr700 device is already connected to hardware, because by that time, the timer process and thread have already been spawned. Args: state_transition_func (func): the function to call for every state transition. A state transition occurs whenever the freshroastsr700's time_remaining value counts down to 0. Returns: nothing """ if self._connected.value: logging.error("freshroastsr700.set_state_transition_func must be " "called before freshroastsr700.auto_connect()." " Not registering func.") return False # no connection yet. so OK to set func pointer self._create_state_transition_system(func) return True def update_data_run(self, event_to_wait_on): """This is the thread that listens to an event from the comm process to execute the update_data_func callback in the context of the main process. """ # with the daemon=Turue setting, this thread should # quit 'automatically' while event_to_wait_on.wait(): event_to_wait_on.clear() if self.update_data_callback_kill_event.is_set(): return self.update_data_func() def state_transition_run(self, event_to_wait_on): """This is the thread that listens to an event from the timer process to execute the state_transition_func callback in the context of the main process. """ # with the daemon=Turue setting, this thread should # quit 'automatically' while event_to_wait_on.wait(): event_to_wait_on.clear() if self.state_transition_callback_kill_event.is_set(): return self.state_transition_func() def _connect(self): """Do not call this directly - call auto_connect() or connect(), which will call _connect() for you. Connects to the roaster and creates communication thread. Raises a RoasterLokkupError exception if the hardware is not found. """ # the following call raises a RoasterLookupException when the device # is not found. It is port = utils.find_device('1A86:5523') # on some systems, after the device port is added to the device list, # it can take up to 20 seconds after USB insertion for # the port to become available... (!) # let's put a safety timeout in here as a precaution wait_timeout = time.time() + 40.0 # should be PLENTY of time! # let's update the _connect_state while we're at it... self._connect_state.value = self.CS_CONNECTING connect_success = False while time.time() < wait_timeout: try: self._ser = serial.Serial( port=port, baudrate=9600, bytesize=8, parity='N', stopbits=1.5, timeout=0.25, xonxoff=False, rtscts=False, dsrdtr=False) connect_success = True break except serial.SerialException: time.sleep(0.5) if not connect_success: # timeout on attempts raise exceptions.RoasterLookupError self._initialize() def _write_to_device(self): success = False try: packet = self._generate_packet() logging.debug('WR: ' + str(binascii.hexlify(packet))) self._ser.write(packet) success = True except serial.serialutil.SerialException: logging.error('caught serial exception writing') return success def _read_from_device(self): r = [] footer_reached = False while len(r) < 14 and footer_reached is False: r.append(self._ser.read(1)) if len(r) >= 2 and b''.join(r)[-2:] == self._footer: footer_reached = True logging.debug('RD: ' + str(binascii.hexlify(b''.join(r)))) return b''.join(r) def _read_existing_recipe(self): existing_recipe = [] end_of_recipe = False while not end_of_recipe: bytes_waiting = self._ser.in_waiting if bytes_waiting < 14: # still need to write to device every .25sec it seems time.sleep(0.25) self._write_to_device() else: while (bytes_waiting // 14) > 0: r = self._read_from_device() bytes_waiting = self._ser.in_waiting if len(r) < 14: logging.warn('short packet length') else: existing_recipe.append(r) if r[4:5] == b'\xAF' or r[4:5] == b'\x00': end_of_recipe = True continue return existing_recipe def connect(self): """Attempt to connect to hardware immediately. Will not retry. Check freshroastsr700.connected or freshroastsr700.connect_state to verify result. Raises: freshroastsr700.exeptions.RoasterLookupError No hardware connected to the computer. """ self._start_connect(self.CA_SINGLE_SHOT) while(self._connect_state.value == self.CS_ATTEMPTING_CONNECT or self._connect_state.value == self.CS_CONNECTING): time.sleep(0.1) if self.CS_CONNECTED != self._connect_state.value: raise exceptions.RoasterLookupError def auto_connect(self): """Starts a thread that will automatically connect to the roaster when it is plugged in.""" self._start_connect(self.CA_AUTO) def _start_connect(self, connect_type): """Starts the connection process, as called (internally) from the user context, either from auto_connect() or connect(). Never call this from the _comm() process context. """ if self._connect_state.value != self.CS_NOT_CONNECTED: # already done or in process, assume success return self._connected.value = 0 self._connect_state.value = self.CS_ATTEMPTING_CONNECT # tell comm process to attempt connection self._attempting_connect.value = connect_type # EXTREMELY IMPORTANT - for this to work at all in Windows, # where the above processes are spawned (vs forked in Unix), # the thread objects (as sattributes of this object) must be # assigned to this object AFTER we have spawned the processes. # That way, multiprocessing can pickle the freshroastsr700 # successfully. (It can't pickle thread-related stuff.) if self.update_data_func is not None: # Need to launch the thread that will listen to the event self._create_update_data_system( None, setFunc=False, createThread=True) self.update_data_thread.start() if self.state_transition_func is not None: # Need to launch the thread that will listen to the event self._create_state_transition_system( None, setFunc=False, createThread=True) self.state_transition_thread.start() def _auto_connect(self): """Attempts to connect to the roaster every quarter of a second.""" while not self._teardown.value: try: self._connect() return True except exceptions.RoasterLookupError: time.sleep(.25) return False def disconnect(self): """Stops the communication loop to the roaster. Note that this will not actually stop the roaster itself.""" self._disconnect.value = 1 def terminate(self): """Stops the communication loop to the roaster and closes down all communication processes. Note that this will not actually stop the roaster itself. You will need to instantiate a new freshroastsr700 object after calling this function, in order to re-start communications with the hardware. """ self.disconnect() self._teardown.value = 1 def _comm(self, thermostat=False, kp=0.06, ki=0.0075, kd=0.01, heater_segments=8, ext_sw_heater_drive=False, update_data_event=None): """Do not call this directly - call auto_connect(), which will spawn comm() for you. This is the main communications loop to the roaster. whenever a valid packet is received from the device, if an update_data_event is available, it will be signalled. Args: thermostat (bool): thermostat mode. if set to True, turns on thermostat mode. In thermostat mode, freshroastsr700 takes control of heat_setting and does software PID control to hit the demanded target_temp. ext_sw_heater_drive (bool): enable direct control over the internal heat_controller object. Defaults to False. When set to True, the thermostat field is IGNORED, and assumed to be False. Direct control over the software heater_level means that the PID controller cannot control the heater. Since thermostat and ext_sw_heater_drive cannot be allowed to both be True, this arg is given precedence over the thermostat arg. kp (float): Kp value to use for PID control. Defaults to 0.06. ki (float): Ki value to use for PID control. Defaults to 0.0075. kd (float): Kd value to use for PID control. Defaults to 0.01. heater_segments (int): the pseudo-control range for the internal heat_controller object. Defaults to 8. update_data_event (multiprocessing.Event): If set, allows the comm_process to signal to the parent process that new device data is available. Returns: nothing """ # since this process is started with daemon=True, it should exit # when the owning process terminates. Therefore, safe to loop forever. while not self._teardown.value: # waiting for command to attempt connect # print( "waiting for command to attempt connect") while self._attempting_connect.value == self.CA_NONE: time.sleep(0.25) if self._teardown.value: break # if we're tearing down, bail now. if self._teardown.value: break # we got the command to attempt to connect # change state to 'attempting_connect' self._connect_state.value = self.CS_ATTEMPTING_CONNECT # attempt connection if self.CA_AUTO == self._attempting_connect.value: # this call will block until a connection is achieved # it will also set _connect_state to CS_CONNECTING # if appropriate if self._auto_connect(): # when we unblock, it is an indication of a successful # connection self._connected.value = 1 self._connect_state.value = self.CS_CONNECTED else: # failure, normally due to a timeout self._connected.value = 0 self._connect_state.value = self.CS_NOT_CONNECTED # we failed to connect - start over from the top # reset flag self._attempting_connect.value = self.CA_NONE continue elif self.CA_SINGLE_SHOT == self._attempting_connect.value: # try once, now, if failure, start teh big loop over try: self._connect() self._connected.value = 1 self._connect_state.value = self.CS_CONNECTED except exceptions.RoasterLookupError: self._connected.value = 0 self._connect_state.value = self.CS_NOT_CONNECTED if self._connect_state.value != self.CS_CONNECTED: # we failed to connect - start over from the top # reset flag self._attempting_connect.value = self.CA_NONE continue else: # shouldn't be here # reset flag self._attempting_connect.value = self.CA_NONE continue # We are connected! # print( "We are connected!") # reset flag right away self._attempting_connect.value = self.CA_NONE # Initialize PID controller if thermostat function was specified at # init time pidc = None heater = None if(thermostat): pidc = pid.PID(kp, ki, kd, Output_max=heater_segments, Output_min=0 ) if thermostat or ext_sw_heater_drive: heater = heat_controller(number_of_segments=heater_segments) read_state = self.LOOKING_FOR_HEADER_1 r = [] write_errors = 0 read_errors = 0 while not self._disconnect.value: start = datetime.datetime.now() # write to device if not self._write_to_device(): logging.error('comm - _write_to_device() failed!') write_errors += 1 if write_errors > 3: # it's time to consider the device as being "gone" logging.error('comm - 3 successive write ' 'failures, disconnecting.') self._disconnect.value = 1 continue else: # reset write_errors write_errors = 0 # read from device try: while self._ser.in_waiting: _byte = self._ser.read(1) read_state, r, err = ( self._process_reponse_byte( read_state, _byte, r, update_data_event)) except IOError: # typically happens when device is suddenly unplugged logging.error('comm - read from device failed!') read_errors += 1 if write_errors > 3: # it's time to consider the device as being "gone" logging.error('comm - 3 successive read ' 'failures, disconnecting.') self._disconnect.value = 1 continue else: read_errors = 0 # next, drive SW heater when using # thermostat mode (PID controller calcs) # or in external sw heater drive mode, # when roasting. if thermostat or ext_sw_heater_drive: if 'roasting' == self.get_roaster_state(): if heater.about_to_rollover(): # it's time to use the PID controller value # and set new output level on heater! if ext_sw_heater_drive: # read user-supplied value heater.heat_level = self._heater_level.value else: # thermostat output = pidc.update( self.current_temp, self.target_temp) heater.heat_level = output # make this number visible to other processes... self._heater_level.value = heater.heat_level # read bang-bang heater output array element & apply it if heater.generate_bangbang_output(): # ON self.heat_setting = 3 else: # OFF self.heat_setting = 0 else: # for all other states, heat_level = OFF heater.heat_level = 0 # make this number visible to other processes... self._heater_level.value = heater.heat_level self.heat_setting = 0 # calculate sleep time to stick to 0.25sec period comp_time = datetime.datetime.now() - start sleep_duration = 0.25 - comp_time.total_seconds() if sleep_duration > 0: time.sleep(sleep_duration) self._ser.close() # reset disconnect flag self._disconnect.value = 0 # reset connection values self._connected.value = 0 self._connect_state.value = self.CS_NOT_CONNECTED # print("We are disconnected.") def _process_reponse_byte(self, read_state, _byte, r, update_data_event): err = False if self.LOOKING_FOR_HEADER_1 == read_state: if b'\xAA' == _byte: read_state = self.LOOKING_FOR_HEADER_2 elif self.LOOKING_FOR_HEADER_2 == read_state: if b'\xAA' == _byte: read_state = self.PACKET_DATA # reset packet array now... r = [] else: read_state = self.LOOKING_FOR_HEADER_1 elif self.PACKET_DATA == read_state: if b'\xAA' == _byte: # this could be the start of an end of packet marker read_state = self.LOOKING_FOR_FOOTER_2 else: r.append(_byte) # SR700 FW bug - if current temp is 250 degF (0xFA), # the FW does not transmit the footer at all. # fake the footer here. if(len(r) == 10 and b'\xFA' == _byte): # we will 'fake' a footer to make this decoder work # as intended read_state, r, _ = ( self._process_reponse_byte( read_state, b'\xAA', r, update_data_event)) read_state, r, err = ( self._process_reponse_byte( read_state, b'\xFA', r, update_data_event)) elif self.LOOKING_FOR_FOOTER_2 == read_state: if b'\xFA' == _byte: # OK we have a full packet - PROCESS PACKET err = self._process_response_data(r, update_data_event) read_state = self.LOOKING_FOR_HEADER_1 else: # the last byte was not the beginning of the footer r.append(b'\xAA') read_state = self.PACKET_DATA read_state, r, err = self._process_reponse_byte( read_state, _byte, r, update_data_event) else: # error state, shouldn't happen... logging.error('_process_reponse_byte - invalid read_state %d' % read_state) read_state = self.LOOKING_FOR_HEADER_1 err = True return read_state, r, err def _process_response_data(self, r, update_data_event): err = False if len(r) != 10: logging.warn('read packet data len not 10, got: %d' % len(r)) logging.warn('RD: ' + str(binascii.hexlify(b''.join(r)))) err = True else: temp = struct.unpack(">H", b''.join(r[8:10]))[0] if(temp == 65280): self.current_temp = 150 elif(temp > 550 or temp < 150): logging.warn('temperature out of range: reinitializing...') self._initialize() err = True return else: self.current_temp = temp if(update_data_event is not None): update_data_event.set() return err def _timer(self, state_transition_event=None): """Timer loop used to keep track of the time while roasting or cooling. If the time remaining reaches zero, the roaster will call the supplied state transistion function or the roaster will be set to the idle state.""" while not self._teardown.value: state = self.get_roaster_state() if(state == 'roasting' or state == 'cooling'): time.sleep(1) self.total_time += 1 if(self.time_remaining > 0): self.time_remaining -= 1 else: if(state_transition_event is not None): state_transition_event.set() else: self.idle() else: time.sleep(0.01) def get_roaster_state(self): """Returns a string based upon the current state of the roaster. Will raise an exception if the state is unknown. Returns: 'idle' if idle, 'sleeping' if sleeping, 'cooling' if cooling, 'roasting' if roasting, 'connecting' if in hardware connection phase, 'unknown' otherwise """ value = self._current_state.value if(value == b'\x02\x01'): return 'idle' elif(value == b'\x04\x04'): return 'cooling' elif(value == b'\x08\x01'): return 'sleeping' # handle null bytes as empty strings elif(value == b'\x00\x00' or value == b''): return 'connecting' elif(value == b'\x04\x02'): return 'roasting' else: return 'unknown' def _generate_packet(self): """Generates a packet based upon the current class variables. Note that current temperature is not sent, as the original application sent zeros to the roaster for the current temperature.""" roaster_time = utils.seconds_to_float(self._time_remaining.value) packet = ( self._header.value + self._temp_unit.value + self._flags.value + self._current_state.value + struct.pack(">B", self._fan_speed.value) + struct.pack(">B", int(round(roaster_time * 10.0))) + struct.pack(">B", self._heat_setting.value) + b'\x00\x00' + self._footer) return packet def idle(self): """Sets the current state of the roaster to idle.""" self._current_state.value = b'\x02\x01' def roast(self): """Sets the current state of the roaster to roast and begins roasting.""" self._current_state.value = b'\x04\x02' def cool(self): """Sets the current state of the roaster to cool. The roaster expects that cool will be run after roast, and will not work as expected if ran before.""" self._current_state.value = b'\x04\x04' def sleep(self): """Sets the current state of the roaster to sleep. Different than idle in that this will set double dashes on the roaster display rather than digits.""" self._current_state.value = b'\x08\x01'
Roastero/freshroastsr700
freshroastsr700/__init__.py
freshroastsr700.connect
python
def connect(self): self._start_connect(self.CA_SINGLE_SHOT) while(self._connect_state.value == self.CS_ATTEMPTING_CONNECT or self._connect_state.value == self.CS_CONNECTING): time.sleep(0.1) if self.CS_CONNECTED != self._connect_state.value: raise exceptions.RoasterLookupError
Attempt to connect to hardware immediately. Will not retry. Check freshroastsr700.connected or freshroastsr700.connect_state to verify result. Raises: freshroastsr700.exeptions.RoasterLookupError No hardware connected to the computer.
train
https://github.com/Roastero/freshroastsr700/blob/49cf4961444c0f56d051d5ac5088ace480b54f02/freshroastsr700/__init__.py#L539-L552
[ "def _start_connect(self, connect_type):\n \"\"\"Starts the connection process, as called (internally)\n from the user context, either from auto_connect() or connect().\n Never call this from the _comm() process context.\n \"\"\"\n if self._connect_state.value != self.CS_NOT_CONNECTED:\n # alr...
class freshroastsr700(object): """A class to interface with a freshroastsr700 coffee roaster. Args: update_data_func (func): A function to call when this object receives new data from the hardware. Defaults to None. state_transition_func (func): A function to call when time_remaining counts down to 0 and the device is either in roasting or cooling state. Defaults to None. thermostat (bool): thermostat mode. if set to True, turns on thermostat mode. In thermostat mode, freshroastsr700 takes control of heat_setting and does software PID control to hit the demanded target_temp. Defaults to False. ext_sw_heater_drive (bool): enable direct control over the internal heat_controller object. Defaults to False. When set to True, the thermostat field is IGNORED, and assumed to be False. Direct control over the software heater_level means that the freshroastsr700's PID controller cannot control the heater. Since thermostat and ext_sw_heater_drive cannot be allowed to both be True, this arg is given precedence over the thermostat arg. Note that (thermostat=False, ext_sw_heater_drive=False), (thermostat=True, ext_sw_heater_drive=False), (thermostat=False, ext_sw_heater_drive=True), are all acceptable arg combinations. Only the (thermostat=True, ext_sw_heater_drive=True), cominbation is not allowed, and this software will set thermostat=False in that case. kp (float): Kp value to use for PID control. Defaults to 0.06. ki (float): Ki value to use for PID control. Defaults to 0.0075. kd (float): Kd value to use for PID control. Defaults to 0.01. heater_segments (int): the pseudo-control range for the internal heat_controller object. Defaults to 8. """ def __init__(self, update_data_func=None, state_transition_func=None, thermostat=False, kp=0.06, ki=0.0075, kd=0.01, heater_segments=8, ext_sw_heater_drive=False): """Create variables used to send in packets to the roaster. The update data function is called when a packet is opened. The state transistion function is used by the timer thread to know what to do next. See wiki for more information on packet structure and fields.""" # constants for protocol decoding self.LOOKING_FOR_HEADER_1 = 0 self.LOOKING_FOR_HEADER_2 = 1 self.PACKET_DATA = 2 self.LOOKING_FOR_FOOTER_2 = 3 # constants for connection state monitoring self.CS_NOT_CONNECTED = -2 self.CS_ATTEMPTING_CONNECT = -1 self.CS_CONNECTING = 0 self.CS_CONNECTED = 1 # constants for connection attempt type self.CA_NONE = 0 self.CA_AUTO = 1 self.CA_SINGLE_SHOT = 2 self._create_update_data_system(update_data_func) self._create_state_transition_system(state_transition_func) self._header = sharedctypes.Array('c', b'\xAA\xAA') self._temp_unit = sharedctypes.Array('c', b'\x61\x74') self._flags = sharedctypes.Array('c', b'\x63') self._current_state = sharedctypes.Array('c', b'\x02\x01') self._footer = b'\xAA\xFA' self._fan_speed = sharedctypes.Value('i', 1) self._heat_setting = sharedctypes.Value('i', 0) self._target_temp = sharedctypes.Value('i', 150) self._current_temp = sharedctypes.Value('i', 150) self._time_remaining = sharedctypes.Value('i', 0) self._total_time = sharedctypes.Value('i', 0) self._disconnect = sharedctypes.Value('i', 0) self._teardown = sharedctypes.Value('i', 0) # for SW PWM heater setting self._heater_level = sharedctypes.Value('i', 0) # the following vars are not process-safe, do not access them # from the comm or timer threads, nor from the callbacks. self._ext_sw_heater_drive = ext_sw_heater_drive if not self._ext_sw_heater_drive: self._thermostat = thermostat else: self._thermostat = False self._pid_kp = kp self._pid_ki = ki self._pid_kd = kd self._heater_bangbang_segments = heater_segments # initialize to 'not connected' self._connected = sharedctypes.Value('i', 0) self._connect_state = sharedctypes.Value('i', self.CS_NOT_CONNECTED) # initialize to 'not trying to connect' self._attempting_connect = sharedctypes.Value('i', self.CA_NONE) # create comm process self.comm_process = mp.Process( target=self._comm, args=( self._thermostat, self._pid_kp, self._pid_ki, self._pid_kd, self._heater_bangbang_segments, self._ext_sw_heater_drive, self.update_data_event,)) self.comm_process.daemon = True self.comm_process.start() # create timer process that counts down time_remaining self.time_process = mp.Process( target=self._timer, args=( self.state_transition_event,)) self.time_process.daemon = True self.time_process.start() def _create_update_data_system( self, update_data_func, setFunc=True, createThread=False): # these callbacks cannot be called from another process in Windows. # Therefore, spawn a thread belonging to the calling process # instead. # the comm and timer processes will set events that the threads # will listen for to initiate the callbacks # only create the mp.Event once - # to mimic create_state_transition_system, for future-proofing # (in this case, currently, this is only called at __init__() time) if not hasattr(self, 'update_data_event'): self.update_data_event = mp.Event() # only create the thread.Event once - this is used to exit # the callback thread if not hasattr(self, 'update_data_callback_kill_event'): self.update_data_callback_kill_event = mp.Event() # destroy an existing thread if we had created one previously if(hasattr(self, 'update_data_thread') and self.update_data_thread is not None): # let's tear this down. To kill it, two events must be set... # in the right sequence! self.update_data_callback_kill_event.set() self.update_data_event.set() self.update_data_thread.join() if setFunc: self.update_data_func = update_data_func if self.update_data_func is not None: if createThread: self.update_data_callback_kill_event.clear() self.update_data_thread = threading.Thread( name='sr700_update_data', target=self.update_data_run, args=(self.update_data_event,), daemon=True ) else: self.update_data_thread = None def _create_state_transition_system( self, state_transition_func, setFunc=True, createThread=False): # these callbacks cannot be called from another process in Windows. # Therefore, spawn a thread belonging to the calling process # instead. # the comm and timer processes will set events that the threads # will listen for to initiate the callbacks # only create the mp.Event once - this fn can get called more # than once, by __init__() and by set_state_transition_func() if not hasattr(self, 'state_transition_event'): self.state_transition_event = mp.Event() # only create the thread.Event once - this is used to exit # the callback thread if not hasattr(self, 'state_transition_callback_kill_event'): self.state_transition_callback_kill_event = mp.Event() # destroy an existing thread if we had created one previously if(hasattr(self, 'state_transition_thread') and self.state_transition_thread is not None): # let's tear this down. To kill it, two events must be set... # in the right sequence! self.state_transition_callback_kill_event.set() self.state_transition_event.set() self.state_transition_thread.join() if setFunc: self.state_transition_func = state_transition_func if self.state_transition_func is not None: if createThread: self.state_transition_callback_kill_event.clear() self.state_transition_thread = threading.Thread( name='sr700_state_transition', target=self.state_transition_run, args=(self.state_transition_event,), daemon=True ) else: self.state_transition_thread = None @property def fan_speed(self): """Get/Set fan speed. Can be 1 to 9 inclusive. Args: Setter: fan_speed (int): fan speed Returns: Getter: (int): fan speed """ return self._fan_speed.value @fan_speed.setter def fan_speed(self, value): """Verifies the value is between 1 and 9 inclusively.""" if value not in range(1, 10): raise exceptions.RoasterValueError self._fan_speed.value = value @property def heat_setting(self): """Get/Set heat setting, 0 to 3 inclusive. 0=off, 3=high. Do not set when running freshroastsr700 in thermostat mode. Args: Setter: heat_setting (int): heat setting Returns: Getter: (int): heat setting """ return self._heat_setting.value @heat_setting.setter def heat_setting(self, value): """Verifies that the heat setting is between 0 and 3.""" if value not in range(0, 4): raise exceptions.RoasterValueError self._heat_setting.value = value @property def target_temp(self): """Get/Set the target temperature for this package's built-in software PID controler. Only used when freshroastsr700 is instantiated with thermostat=True. Args: Setter: value (int): a target temperature in degF between 150 and 551. Returns: Getter: (int) target temperature in degF between 150 and 551 """ return self._target_temp.value @target_temp.setter def target_temp(self, value): if value not in range(150, 551): raise exceptions.RoasterValueError self._target_temp.value = value @property def current_temp(self): """Current temperature of the roast chamber as reported by hardware. Returns: (int) current temperature, in degrees Fahrenheit """ return self._current_temp.value @current_temp.setter def current_temp(self, value): if value not in range(150, 551): raise exceptions.RoasterValueError self._current_temp.value = value @property def time_remaining(self): """The amount of time, in seconds, remaining until a call to the state_transition_func is made. can be set to an arbitrary value up to 600 seconds at any time. When a new value is set, freshroastsr700 will count down from this new value down to 0. time_remaining is decremented to 0 only when in a roasting or cooling state. In other states, the value is not touched. Args: Setter: time_remaining (int): tiem remaining in seconds Returns: Getter: time_remaining(int): time remaining, in seconds """ return self._time_remaining.value @time_remaining.setter def time_remaining(self, value): self._time_remaining.value = value @property def total_time(self): """The total time this instance has been in roasting or cooling state sicne the latest roast began. Returns: total_time (int): time, in seconds """ return self._total_time.value @total_time.setter def total_time(self, value): self._total_time.value = value @property def heater_level(self): """A getter method for _heater_level. When thermostat=True, value is driven by built-in PID controller. When ext_sw_heater_drive=True, value is driven by calls to heater_level(). Min will always be zero, max will be heater_segments (optional instantiation parameter, defaults to 8).""" return self._heater_level.value @heater_level.setter def heater_level(self, value): """Verifies that the heater_level is between 0 and heater_segments. Can only be called when freshroastsr700 object is initialized with ext_sw_heater_drive=True. Will throw RoasterValueError otherwise.""" if self._ext_sw_heater_drive: if value not in range(0, self._heater_bangbang_segments+1): raise exceptions.RoasterValueError self._heater_level.value = value else: raise exceptions.RoasterValueError @property def connected(self): """A getter method for _connected. Indicates that the this software is currently communicating with FreshRoast SR700 hardware.""" return self._connected.value @property def connect_state(self): """A getter method for _connect_state. Indicates the current connection state this software is in for FreshRoast SR700 hardware. Returns: freshroastsr700.CS_NOT_CONNECTED the software is not currenting communicating with hardware, neither was it instructed to do so. A previously failed connection attempt will also result in this state. freshroastsr700.CS_ATTEMPTING_CONNECT A call to auto_connect() or connect() was made, and the software is currently attempting to connect to hardware. freshroastsr700.CS_CONNECTED The hardware was found, and the software is communicating with the hardware. """ return self._connect_state.value def set_state_transition_func(self, func): """THIS FUNCTION MUST BE CALLED BEFORE CALLING freshroastsr700.auto_connect(). Set, or re-set, the state transition function callback. The supplied function will be called from a separate thread within freshroastsr700, triggered by a separate, internal child process. This function will fail if the freshroastsr700 device is already connected to hardware, because by that time, the timer process and thread have already been spawned. Args: state_transition_func (func): the function to call for every state transition. A state transition occurs whenever the freshroastsr700's time_remaining value counts down to 0. Returns: nothing """ if self._connected.value: logging.error("freshroastsr700.set_state_transition_func must be " "called before freshroastsr700.auto_connect()." " Not registering func.") return False # no connection yet. so OK to set func pointer self._create_state_transition_system(func) return True def update_data_run(self, event_to_wait_on): """This is the thread that listens to an event from the comm process to execute the update_data_func callback in the context of the main process. """ # with the daemon=Turue setting, this thread should # quit 'automatically' while event_to_wait_on.wait(): event_to_wait_on.clear() if self.update_data_callback_kill_event.is_set(): return self.update_data_func() def state_transition_run(self, event_to_wait_on): """This is the thread that listens to an event from the timer process to execute the state_transition_func callback in the context of the main process. """ # with the daemon=Turue setting, this thread should # quit 'automatically' while event_to_wait_on.wait(): event_to_wait_on.clear() if self.state_transition_callback_kill_event.is_set(): return self.state_transition_func() def _connect(self): """Do not call this directly - call auto_connect() or connect(), which will call _connect() for you. Connects to the roaster and creates communication thread. Raises a RoasterLokkupError exception if the hardware is not found. """ # the following call raises a RoasterLookupException when the device # is not found. It is port = utils.find_device('1A86:5523') # on some systems, after the device port is added to the device list, # it can take up to 20 seconds after USB insertion for # the port to become available... (!) # let's put a safety timeout in here as a precaution wait_timeout = time.time() + 40.0 # should be PLENTY of time! # let's update the _connect_state while we're at it... self._connect_state.value = self.CS_CONNECTING connect_success = False while time.time() < wait_timeout: try: self._ser = serial.Serial( port=port, baudrate=9600, bytesize=8, parity='N', stopbits=1.5, timeout=0.25, xonxoff=False, rtscts=False, dsrdtr=False) connect_success = True break except serial.SerialException: time.sleep(0.5) if not connect_success: # timeout on attempts raise exceptions.RoasterLookupError self._initialize() def _initialize(self): """Sends the initialization packet to the roaster.""" self._header.value = b'\xAA\x55' self._current_state.value = b'\x00\x00' s = self._generate_packet() self._ser.write(s) self._header.value = b'\xAA\xAA' self._current_state.value = b'\x02\x01' return self._read_existing_recipe() def _write_to_device(self): success = False try: packet = self._generate_packet() logging.debug('WR: ' + str(binascii.hexlify(packet))) self._ser.write(packet) success = True except serial.serialutil.SerialException: logging.error('caught serial exception writing') return success def _read_from_device(self): r = [] footer_reached = False while len(r) < 14 and footer_reached is False: r.append(self._ser.read(1)) if len(r) >= 2 and b''.join(r)[-2:] == self._footer: footer_reached = True logging.debug('RD: ' + str(binascii.hexlify(b''.join(r)))) return b''.join(r) def _read_existing_recipe(self): existing_recipe = [] end_of_recipe = False while not end_of_recipe: bytes_waiting = self._ser.in_waiting if bytes_waiting < 14: # still need to write to device every .25sec it seems time.sleep(0.25) self._write_to_device() else: while (bytes_waiting // 14) > 0: r = self._read_from_device() bytes_waiting = self._ser.in_waiting if len(r) < 14: logging.warn('short packet length') else: existing_recipe.append(r) if r[4:5] == b'\xAF' or r[4:5] == b'\x00': end_of_recipe = True continue return existing_recipe def auto_connect(self): """Starts a thread that will automatically connect to the roaster when it is plugged in.""" self._start_connect(self.CA_AUTO) def _start_connect(self, connect_type): """Starts the connection process, as called (internally) from the user context, either from auto_connect() or connect(). Never call this from the _comm() process context. """ if self._connect_state.value != self.CS_NOT_CONNECTED: # already done or in process, assume success return self._connected.value = 0 self._connect_state.value = self.CS_ATTEMPTING_CONNECT # tell comm process to attempt connection self._attempting_connect.value = connect_type # EXTREMELY IMPORTANT - for this to work at all in Windows, # where the above processes are spawned (vs forked in Unix), # the thread objects (as sattributes of this object) must be # assigned to this object AFTER we have spawned the processes. # That way, multiprocessing can pickle the freshroastsr700 # successfully. (It can't pickle thread-related stuff.) if self.update_data_func is not None: # Need to launch the thread that will listen to the event self._create_update_data_system( None, setFunc=False, createThread=True) self.update_data_thread.start() if self.state_transition_func is not None: # Need to launch the thread that will listen to the event self._create_state_transition_system( None, setFunc=False, createThread=True) self.state_transition_thread.start() def _auto_connect(self): """Attempts to connect to the roaster every quarter of a second.""" while not self._teardown.value: try: self._connect() return True except exceptions.RoasterLookupError: time.sleep(.25) return False def disconnect(self): """Stops the communication loop to the roaster. Note that this will not actually stop the roaster itself.""" self._disconnect.value = 1 def terminate(self): """Stops the communication loop to the roaster and closes down all communication processes. Note that this will not actually stop the roaster itself. You will need to instantiate a new freshroastsr700 object after calling this function, in order to re-start communications with the hardware. """ self.disconnect() self._teardown.value = 1 def _comm(self, thermostat=False, kp=0.06, ki=0.0075, kd=0.01, heater_segments=8, ext_sw_heater_drive=False, update_data_event=None): """Do not call this directly - call auto_connect(), which will spawn comm() for you. This is the main communications loop to the roaster. whenever a valid packet is received from the device, if an update_data_event is available, it will be signalled. Args: thermostat (bool): thermostat mode. if set to True, turns on thermostat mode. In thermostat mode, freshroastsr700 takes control of heat_setting and does software PID control to hit the demanded target_temp. ext_sw_heater_drive (bool): enable direct control over the internal heat_controller object. Defaults to False. When set to True, the thermostat field is IGNORED, and assumed to be False. Direct control over the software heater_level means that the PID controller cannot control the heater. Since thermostat and ext_sw_heater_drive cannot be allowed to both be True, this arg is given precedence over the thermostat arg. kp (float): Kp value to use for PID control. Defaults to 0.06. ki (float): Ki value to use for PID control. Defaults to 0.0075. kd (float): Kd value to use for PID control. Defaults to 0.01. heater_segments (int): the pseudo-control range for the internal heat_controller object. Defaults to 8. update_data_event (multiprocessing.Event): If set, allows the comm_process to signal to the parent process that new device data is available. Returns: nothing """ # since this process is started with daemon=True, it should exit # when the owning process terminates. Therefore, safe to loop forever. while not self._teardown.value: # waiting for command to attempt connect # print( "waiting for command to attempt connect") while self._attempting_connect.value == self.CA_NONE: time.sleep(0.25) if self._teardown.value: break # if we're tearing down, bail now. if self._teardown.value: break # we got the command to attempt to connect # change state to 'attempting_connect' self._connect_state.value = self.CS_ATTEMPTING_CONNECT # attempt connection if self.CA_AUTO == self._attempting_connect.value: # this call will block until a connection is achieved # it will also set _connect_state to CS_CONNECTING # if appropriate if self._auto_connect(): # when we unblock, it is an indication of a successful # connection self._connected.value = 1 self._connect_state.value = self.CS_CONNECTED else: # failure, normally due to a timeout self._connected.value = 0 self._connect_state.value = self.CS_NOT_CONNECTED # we failed to connect - start over from the top # reset flag self._attempting_connect.value = self.CA_NONE continue elif self.CA_SINGLE_SHOT == self._attempting_connect.value: # try once, now, if failure, start teh big loop over try: self._connect() self._connected.value = 1 self._connect_state.value = self.CS_CONNECTED except exceptions.RoasterLookupError: self._connected.value = 0 self._connect_state.value = self.CS_NOT_CONNECTED if self._connect_state.value != self.CS_CONNECTED: # we failed to connect - start over from the top # reset flag self._attempting_connect.value = self.CA_NONE continue else: # shouldn't be here # reset flag self._attempting_connect.value = self.CA_NONE continue # We are connected! # print( "We are connected!") # reset flag right away self._attempting_connect.value = self.CA_NONE # Initialize PID controller if thermostat function was specified at # init time pidc = None heater = None if(thermostat): pidc = pid.PID(kp, ki, kd, Output_max=heater_segments, Output_min=0 ) if thermostat or ext_sw_heater_drive: heater = heat_controller(number_of_segments=heater_segments) read_state = self.LOOKING_FOR_HEADER_1 r = [] write_errors = 0 read_errors = 0 while not self._disconnect.value: start = datetime.datetime.now() # write to device if not self._write_to_device(): logging.error('comm - _write_to_device() failed!') write_errors += 1 if write_errors > 3: # it's time to consider the device as being "gone" logging.error('comm - 3 successive write ' 'failures, disconnecting.') self._disconnect.value = 1 continue else: # reset write_errors write_errors = 0 # read from device try: while self._ser.in_waiting: _byte = self._ser.read(1) read_state, r, err = ( self._process_reponse_byte( read_state, _byte, r, update_data_event)) except IOError: # typically happens when device is suddenly unplugged logging.error('comm - read from device failed!') read_errors += 1 if write_errors > 3: # it's time to consider the device as being "gone" logging.error('comm - 3 successive read ' 'failures, disconnecting.') self._disconnect.value = 1 continue else: read_errors = 0 # next, drive SW heater when using # thermostat mode (PID controller calcs) # or in external sw heater drive mode, # when roasting. if thermostat or ext_sw_heater_drive: if 'roasting' == self.get_roaster_state(): if heater.about_to_rollover(): # it's time to use the PID controller value # and set new output level on heater! if ext_sw_heater_drive: # read user-supplied value heater.heat_level = self._heater_level.value else: # thermostat output = pidc.update( self.current_temp, self.target_temp) heater.heat_level = output # make this number visible to other processes... self._heater_level.value = heater.heat_level # read bang-bang heater output array element & apply it if heater.generate_bangbang_output(): # ON self.heat_setting = 3 else: # OFF self.heat_setting = 0 else: # for all other states, heat_level = OFF heater.heat_level = 0 # make this number visible to other processes... self._heater_level.value = heater.heat_level self.heat_setting = 0 # calculate sleep time to stick to 0.25sec period comp_time = datetime.datetime.now() - start sleep_duration = 0.25 - comp_time.total_seconds() if sleep_duration > 0: time.sleep(sleep_duration) self._ser.close() # reset disconnect flag self._disconnect.value = 0 # reset connection values self._connected.value = 0 self._connect_state.value = self.CS_NOT_CONNECTED # print("We are disconnected.") def _process_reponse_byte(self, read_state, _byte, r, update_data_event): err = False if self.LOOKING_FOR_HEADER_1 == read_state: if b'\xAA' == _byte: read_state = self.LOOKING_FOR_HEADER_2 elif self.LOOKING_FOR_HEADER_2 == read_state: if b'\xAA' == _byte: read_state = self.PACKET_DATA # reset packet array now... r = [] else: read_state = self.LOOKING_FOR_HEADER_1 elif self.PACKET_DATA == read_state: if b'\xAA' == _byte: # this could be the start of an end of packet marker read_state = self.LOOKING_FOR_FOOTER_2 else: r.append(_byte) # SR700 FW bug - if current temp is 250 degF (0xFA), # the FW does not transmit the footer at all. # fake the footer here. if(len(r) == 10 and b'\xFA' == _byte): # we will 'fake' a footer to make this decoder work # as intended read_state, r, _ = ( self._process_reponse_byte( read_state, b'\xAA', r, update_data_event)) read_state, r, err = ( self._process_reponse_byte( read_state, b'\xFA', r, update_data_event)) elif self.LOOKING_FOR_FOOTER_2 == read_state: if b'\xFA' == _byte: # OK we have a full packet - PROCESS PACKET err = self._process_response_data(r, update_data_event) read_state = self.LOOKING_FOR_HEADER_1 else: # the last byte was not the beginning of the footer r.append(b'\xAA') read_state = self.PACKET_DATA read_state, r, err = self._process_reponse_byte( read_state, _byte, r, update_data_event) else: # error state, shouldn't happen... logging.error('_process_reponse_byte - invalid read_state %d' % read_state) read_state = self.LOOKING_FOR_HEADER_1 err = True return read_state, r, err def _process_response_data(self, r, update_data_event): err = False if len(r) != 10: logging.warn('read packet data len not 10, got: %d' % len(r)) logging.warn('RD: ' + str(binascii.hexlify(b''.join(r)))) err = True else: temp = struct.unpack(">H", b''.join(r[8:10]))[0] if(temp == 65280): self.current_temp = 150 elif(temp > 550 or temp < 150): logging.warn('temperature out of range: reinitializing...') self._initialize() err = True return else: self.current_temp = temp if(update_data_event is not None): update_data_event.set() return err def _timer(self, state_transition_event=None): """Timer loop used to keep track of the time while roasting or cooling. If the time remaining reaches zero, the roaster will call the supplied state transistion function or the roaster will be set to the idle state.""" while not self._teardown.value: state = self.get_roaster_state() if(state == 'roasting' or state == 'cooling'): time.sleep(1) self.total_time += 1 if(self.time_remaining > 0): self.time_remaining -= 1 else: if(state_transition_event is not None): state_transition_event.set() else: self.idle() else: time.sleep(0.01) def get_roaster_state(self): """Returns a string based upon the current state of the roaster. Will raise an exception if the state is unknown. Returns: 'idle' if idle, 'sleeping' if sleeping, 'cooling' if cooling, 'roasting' if roasting, 'connecting' if in hardware connection phase, 'unknown' otherwise """ value = self._current_state.value if(value == b'\x02\x01'): return 'idle' elif(value == b'\x04\x04'): return 'cooling' elif(value == b'\x08\x01'): return 'sleeping' # handle null bytes as empty strings elif(value == b'\x00\x00' or value == b''): return 'connecting' elif(value == b'\x04\x02'): return 'roasting' else: return 'unknown' def _generate_packet(self): """Generates a packet based upon the current class variables. Note that current temperature is not sent, as the original application sent zeros to the roaster for the current temperature.""" roaster_time = utils.seconds_to_float(self._time_remaining.value) packet = ( self._header.value + self._temp_unit.value + self._flags.value + self._current_state.value + struct.pack(">B", self._fan_speed.value) + struct.pack(">B", int(round(roaster_time * 10.0))) + struct.pack(">B", self._heat_setting.value) + b'\x00\x00' + self._footer) return packet def idle(self): """Sets the current state of the roaster to idle.""" self._current_state.value = b'\x02\x01' def roast(self): """Sets the current state of the roaster to roast and begins roasting.""" self._current_state.value = b'\x04\x02' def cool(self): """Sets the current state of the roaster to cool. The roaster expects that cool will be run after roast, and will not work as expected if ran before.""" self._current_state.value = b'\x04\x04' def sleep(self): """Sets the current state of the roaster to sleep. Different than idle in that this will set double dashes on the roaster display rather than digits.""" self._current_state.value = b'\x08\x01'
Roastero/freshroastsr700
freshroastsr700/__init__.py
freshroastsr700._start_connect
python
def _start_connect(self, connect_type): if self._connect_state.value != self.CS_NOT_CONNECTED: # already done or in process, assume success return self._connected.value = 0 self._connect_state.value = self.CS_ATTEMPTING_CONNECT # tell comm process to attempt connection self._attempting_connect.value = connect_type # EXTREMELY IMPORTANT - for this to work at all in Windows, # where the above processes are spawned (vs forked in Unix), # the thread objects (as sattributes of this object) must be # assigned to this object AFTER we have spawned the processes. # That way, multiprocessing can pickle the freshroastsr700 # successfully. (It can't pickle thread-related stuff.) if self.update_data_func is not None: # Need to launch the thread that will listen to the event self._create_update_data_system( None, setFunc=False, createThread=True) self.update_data_thread.start() if self.state_transition_func is not None: # Need to launch the thread that will listen to the event self._create_state_transition_system( None, setFunc=False, createThread=True) self.state_transition_thread.start()
Starts the connection process, as called (internally) from the user context, either from auto_connect() or connect(). Never call this from the _comm() process context.
train
https://github.com/Roastero/freshroastsr700/blob/49cf4961444c0f56d051d5ac5088ace480b54f02/freshroastsr700/__init__.py#L559-L588
[ "def _create_update_data_system(\n self, update_data_func, setFunc=True, createThread=False):\n # these callbacks cannot be called from another process in Windows.\n # Therefore, spawn a thread belonging to the calling process\n # instead.\n # the comm and timer processes will set events that the...
class freshroastsr700(object): """A class to interface with a freshroastsr700 coffee roaster. Args: update_data_func (func): A function to call when this object receives new data from the hardware. Defaults to None. state_transition_func (func): A function to call when time_remaining counts down to 0 and the device is either in roasting or cooling state. Defaults to None. thermostat (bool): thermostat mode. if set to True, turns on thermostat mode. In thermostat mode, freshroastsr700 takes control of heat_setting and does software PID control to hit the demanded target_temp. Defaults to False. ext_sw_heater_drive (bool): enable direct control over the internal heat_controller object. Defaults to False. When set to True, the thermostat field is IGNORED, and assumed to be False. Direct control over the software heater_level means that the freshroastsr700's PID controller cannot control the heater. Since thermostat and ext_sw_heater_drive cannot be allowed to both be True, this arg is given precedence over the thermostat arg. Note that (thermostat=False, ext_sw_heater_drive=False), (thermostat=True, ext_sw_heater_drive=False), (thermostat=False, ext_sw_heater_drive=True), are all acceptable arg combinations. Only the (thermostat=True, ext_sw_heater_drive=True), cominbation is not allowed, and this software will set thermostat=False in that case. kp (float): Kp value to use for PID control. Defaults to 0.06. ki (float): Ki value to use for PID control. Defaults to 0.0075. kd (float): Kd value to use for PID control. Defaults to 0.01. heater_segments (int): the pseudo-control range for the internal heat_controller object. Defaults to 8. """ def __init__(self, update_data_func=None, state_transition_func=None, thermostat=False, kp=0.06, ki=0.0075, kd=0.01, heater_segments=8, ext_sw_heater_drive=False): """Create variables used to send in packets to the roaster. The update data function is called when a packet is opened. The state transistion function is used by the timer thread to know what to do next. See wiki for more information on packet structure and fields.""" # constants for protocol decoding self.LOOKING_FOR_HEADER_1 = 0 self.LOOKING_FOR_HEADER_2 = 1 self.PACKET_DATA = 2 self.LOOKING_FOR_FOOTER_2 = 3 # constants for connection state monitoring self.CS_NOT_CONNECTED = -2 self.CS_ATTEMPTING_CONNECT = -1 self.CS_CONNECTING = 0 self.CS_CONNECTED = 1 # constants for connection attempt type self.CA_NONE = 0 self.CA_AUTO = 1 self.CA_SINGLE_SHOT = 2 self._create_update_data_system(update_data_func) self._create_state_transition_system(state_transition_func) self._header = sharedctypes.Array('c', b'\xAA\xAA') self._temp_unit = sharedctypes.Array('c', b'\x61\x74') self._flags = sharedctypes.Array('c', b'\x63') self._current_state = sharedctypes.Array('c', b'\x02\x01') self._footer = b'\xAA\xFA' self._fan_speed = sharedctypes.Value('i', 1) self._heat_setting = sharedctypes.Value('i', 0) self._target_temp = sharedctypes.Value('i', 150) self._current_temp = sharedctypes.Value('i', 150) self._time_remaining = sharedctypes.Value('i', 0) self._total_time = sharedctypes.Value('i', 0) self._disconnect = sharedctypes.Value('i', 0) self._teardown = sharedctypes.Value('i', 0) # for SW PWM heater setting self._heater_level = sharedctypes.Value('i', 0) # the following vars are not process-safe, do not access them # from the comm or timer threads, nor from the callbacks. self._ext_sw_heater_drive = ext_sw_heater_drive if not self._ext_sw_heater_drive: self._thermostat = thermostat else: self._thermostat = False self._pid_kp = kp self._pid_ki = ki self._pid_kd = kd self._heater_bangbang_segments = heater_segments # initialize to 'not connected' self._connected = sharedctypes.Value('i', 0) self._connect_state = sharedctypes.Value('i', self.CS_NOT_CONNECTED) # initialize to 'not trying to connect' self._attempting_connect = sharedctypes.Value('i', self.CA_NONE) # create comm process self.comm_process = mp.Process( target=self._comm, args=( self._thermostat, self._pid_kp, self._pid_ki, self._pid_kd, self._heater_bangbang_segments, self._ext_sw_heater_drive, self.update_data_event,)) self.comm_process.daemon = True self.comm_process.start() # create timer process that counts down time_remaining self.time_process = mp.Process( target=self._timer, args=( self.state_transition_event,)) self.time_process.daemon = True self.time_process.start() def _create_update_data_system( self, update_data_func, setFunc=True, createThread=False): # these callbacks cannot be called from another process in Windows. # Therefore, spawn a thread belonging to the calling process # instead. # the comm and timer processes will set events that the threads # will listen for to initiate the callbacks # only create the mp.Event once - # to mimic create_state_transition_system, for future-proofing # (in this case, currently, this is only called at __init__() time) if not hasattr(self, 'update_data_event'): self.update_data_event = mp.Event() # only create the thread.Event once - this is used to exit # the callback thread if not hasattr(self, 'update_data_callback_kill_event'): self.update_data_callback_kill_event = mp.Event() # destroy an existing thread if we had created one previously if(hasattr(self, 'update_data_thread') and self.update_data_thread is not None): # let's tear this down. To kill it, two events must be set... # in the right sequence! self.update_data_callback_kill_event.set() self.update_data_event.set() self.update_data_thread.join() if setFunc: self.update_data_func = update_data_func if self.update_data_func is not None: if createThread: self.update_data_callback_kill_event.clear() self.update_data_thread = threading.Thread( name='sr700_update_data', target=self.update_data_run, args=(self.update_data_event,), daemon=True ) else: self.update_data_thread = None def _create_state_transition_system( self, state_transition_func, setFunc=True, createThread=False): # these callbacks cannot be called from another process in Windows. # Therefore, spawn a thread belonging to the calling process # instead. # the comm and timer processes will set events that the threads # will listen for to initiate the callbacks # only create the mp.Event once - this fn can get called more # than once, by __init__() and by set_state_transition_func() if not hasattr(self, 'state_transition_event'): self.state_transition_event = mp.Event() # only create the thread.Event once - this is used to exit # the callback thread if not hasattr(self, 'state_transition_callback_kill_event'): self.state_transition_callback_kill_event = mp.Event() # destroy an existing thread if we had created one previously if(hasattr(self, 'state_transition_thread') and self.state_transition_thread is not None): # let's tear this down. To kill it, two events must be set... # in the right sequence! self.state_transition_callback_kill_event.set() self.state_transition_event.set() self.state_transition_thread.join() if setFunc: self.state_transition_func = state_transition_func if self.state_transition_func is not None: if createThread: self.state_transition_callback_kill_event.clear() self.state_transition_thread = threading.Thread( name='sr700_state_transition', target=self.state_transition_run, args=(self.state_transition_event,), daemon=True ) else: self.state_transition_thread = None @property def fan_speed(self): """Get/Set fan speed. Can be 1 to 9 inclusive. Args: Setter: fan_speed (int): fan speed Returns: Getter: (int): fan speed """ return self._fan_speed.value @fan_speed.setter def fan_speed(self, value): """Verifies the value is between 1 and 9 inclusively.""" if value not in range(1, 10): raise exceptions.RoasterValueError self._fan_speed.value = value @property def heat_setting(self): """Get/Set heat setting, 0 to 3 inclusive. 0=off, 3=high. Do not set when running freshroastsr700 in thermostat mode. Args: Setter: heat_setting (int): heat setting Returns: Getter: (int): heat setting """ return self._heat_setting.value @heat_setting.setter def heat_setting(self, value): """Verifies that the heat setting is between 0 and 3.""" if value not in range(0, 4): raise exceptions.RoasterValueError self._heat_setting.value = value @property def target_temp(self): """Get/Set the target temperature for this package's built-in software PID controler. Only used when freshroastsr700 is instantiated with thermostat=True. Args: Setter: value (int): a target temperature in degF between 150 and 551. Returns: Getter: (int) target temperature in degF between 150 and 551 """ return self._target_temp.value @target_temp.setter def target_temp(self, value): if value not in range(150, 551): raise exceptions.RoasterValueError self._target_temp.value = value @property def current_temp(self): """Current temperature of the roast chamber as reported by hardware. Returns: (int) current temperature, in degrees Fahrenheit """ return self._current_temp.value @current_temp.setter def current_temp(self, value): if value not in range(150, 551): raise exceptions.RoasterValueError self._current_temp.value = value @property def time_remaining(self): """The amount of time, in seconds, remaining until a call to the state_transition_func is made. can be set to an arbitrary value up to 600 seconds at any time. When a new value is set, freshroastsr700 will count down from this new value down to 0. time_remaining is decremented to 0 only when in a roasting or cooling state. In other states, the value is not touched. Args: Setter: time_remaining (int): tiem remaining in seconds Returns: Getter: time_remaining(int): time remaining, in seconds """ return self._time_remaining.value @time_remaining.setter def time_remaining(self, value): self._time_remaining.value = value @property def total_time(self): """The total time this instance has been in roasting or cooling state sicne the latest roast began. Returns: total_time (int): time, in seconds """ return self._total_time.value @total_time.setter def total_time(self, value): self._total_time.value = value @property def heater_level(self): """A getter method for _heater_level. When thermostat=True, value is driven by built-in PID controller. When ext_sw_heater_drive=True, value is driven by calls to heater_level(). Min will always be zero, max will be heater_segments (optional instantiation parameter, defaults to 8).""" return self._heater_level.value @heater_level.setter def heater_level(self, value): """Verifies that the heater_level is between 0 and heater_segments. Can only be called when freshroastsr700 object is initialized with ext_sw_heater_drive=True. Will throw RoasterValueError otherwise.""" if self._ext_sw_heater_drive: if value not in range(0, self._heater_bangbang_segments+1): raise exceptions.RoasterValueError self._heater_level.value = value else: raise exceptions.RoasterValueError @property def connected(self): """A getter method for _connected. Indicates that the this software is currently communicating with FreshRoast SR700 hardware.""" return self._connected.value @property def connect_state(self): """A getter method for _connect_state. Indicates the current connection state this software is in for FreshRoast SR700 hardware. Returns: freshroastsr700.CS_NOT_CONNECTED the software is not currenting communicating with hardware, neither was it instructed to do so. A previously failed connection attempt will also result in this state. freshroastsr700.CS_ATTEMPTING_CONNECT A call to auto_connect() or connect() was made, and the software is currently attempting to connect to hardware. freshroastsr700.CS_CONNECTED The hardware was found, and the software is communicating with the hardware. """ return self._connect_state.value def set_state_transition_func(self, func): """THIS FUNCTION MUST BE CALLED BEFORE CALLING freshroastsr700.auto_connect(). Set, or re-set, the state transition function callback. The supplied function will be called from a separate thread within freshroastsr700, triggered by a separate, internal child process. This function will fail if the freshroastsr700 device is already connected to hardware, because by that time, the timer process and thread have already been spawned. Args: state_transition_func (func): the function to call for every state transition. A state transition occurs whenever the freshroastsr700's time_remaining value counts down to 0. Returns: nothing """ if self._connected.value: logging.error("freshroastsr700.set_state_transition_func must be " "called before freshroastsr700.auto_connect()." " Not registering func.") return False # no connection yet. so OK to set func pointer self._create_state_transition_system(func) return True def update_data_run(self, event_to_wait_on): """This is the thread that listens to an event from the comm process to execute the update_data_func callback in the context of the main process. """ # with the daemon=Turue setting, this thread should # quit 'automatically' while event_to_wait_on.wait(): event_to_wait_on.clear() if self.update_data_callback_kill_event.is_set(): return self.update_data_func() def state_transition_run(self, event_to_wait_on): """This is the thread that listens to an event from the timer process to execute the state_transition_func callback in the context of the main process. """ # with the daemon=Turue setting, this thread should # quit 'automatically' while event_to_wait_on.wait(): event_to_wait_on.clear() if self.state_transition_callback_kill_event.is_set(): return self.state_transition_func() def _connect(self): """Do not call this directly - call auto_connect() or connect(), which will call _connect() for you. Connects to the roaster and creates communication thread. Raises a RoasterLokkupError exception if the hardware is not found. """ # the following call raises a RoasterLookupException when the device # is not found. It is port = utils.find_device('1A86:5523') # on some systems, after the device port is added to the device list, # it can take up to 20 seconds after USB insertion for # the port to become available... (!) # let's put a safety timeout in here as a precaution wait_timeout = time.time() + 40.0 # should be PLENTY of time! # let's update the _connect_state while we're at it... self._connect_state.value = self.CS_CONNECTING connect_success = False while time.time() < wait_timeout: try: self._ser = serial.Serial( port=port, baudrate=9600, bytesize=8, parity='N', stopbits=1.5, timeout=0.25, xonxoff=False, rtscts=False, dsrdtr=False) connect_success = True break except serial.SerialException: time.sleep(0.5) if not connect_success: # timeout on attempts raise exceptions.RoasterLookupError self._initialize() def _initialize(self): """Sends the initialization packet to the roaster.""" self._header.value = b'\xAA\x55' self._current_state.value = b'\x00\x00' s = self._generate_packet() self._ser.write(s) self._header.value = b'\xAA\xAA' self._current_state.value = b'\x02\x01' return self._read_existing_recipe() def _write_to_device(self): success = False try: packet = self._generate_packet() logging.debug('WR: ' + str(binascii.hexlify(packet))) self._ser.write(packet) success = True except serial.serialutil.SerialException: logging.error('caught serial exception writing') return success def _read_from_device(self): r = [] footer_reached = False while len(r) < 14 and footer_reached is False: r.append(self._ser.read(1)) if len(r) >= 2 and b''.join(r)[-2:] == self._footer: footer_reached = True logging.debug('RD: ' + str(binascii.hexlify(b''.join(r)))) return b''.join(r) def _read_existing_recipe(self): existing_recipe = [] end_of_recipe = False while not end_of_recipe: bytes_waiting = self._ser.in_waiting if bytes_waiting < 14: # still need to write to device every .25sec it seems time.sleep(0.25) self._write_to_device() else: while (bytes_waiting // 14) > 0: r = self._read_from_device() bytes_waiting = self._ser.in_waiting if len(r) < 14: logging.warn('short packet length') else: existing_recipe.append(r) if r[4:5] == b'\xAF' or r[4:5] == b'\x00': end_of_recipe = True continue return existing_recipe def connect(self): """Attempt to connect to hardware immediately. Will not retry. Check freshroastsr700.connected or freshroastsr700.connect_state to verify result. Raises: freshroastsr700.exeptions.RoasterLookupError No hardware connected to the computer. """ self._start_connect(self.CA_SINGLE_SHOT) while(self._connect_state.value == self.CS_ATTEMPTING_CONNECT or self._connect_state.value == self.CS_CONNECTING): time.sleep(0.1) if self.CS_CONNECTED != self._connect_state.value: raise exceptions.RoasterLookupError def auto_connect(self): """Starts a thread that will automatically connect to the roaster when it is plugged in.""" self._start_connect(self.CA_AUTO) def _auto_connect(self): """Attempts to connect to the roaster every quarter of a second.""" while not self._teardown.value: try: self._connect() return True except exceptions.RoasterLookupError: time.sleep(.25) return False def disconnect(self): """Stops the communication loop to the roaster. Note that this will not actually stop the roaster itself.""" self._disconnect.value = 1 def terminate(self): """Stops the communication loop to the roaster and closes down all communication processes. Note that this will not actually stop the roaster itself. You will need to instantiate a new freshroastsr700 object after calling this function, in order to re-start communications with the hardware. """ self.disconnect() self._teardown.value = 1 def _comm(self, thermostat=False, kp=0.06, ki=0.0075, kd=0.01, heater_segments=8, ext_sw_heater_drive=False, update_data_event=None): """Do not call this directly - call auto_connect(), which will spawn comm() for you. This is the main communications loop to the roaster. whenever a valid packet is received from the device, if an update_data_event is available, it will be signalled. Args: thermostat (bool): thermostat mode. if set to True, turns on thermostat mode. In thermostat mode, freshroastsr700 takes control of heat_setting and does software PID control to hit the demanded target_temp. ext_sw_heater_drive (bool): enable direct control over the internal heat_controller object. Defaults to False. When set to True, the thermostat field is IGNORED, and assumed to be False. Direct control over the software heater_level means that the PID controller cannot control the heater. Since thermostat and ext_sw_heater_drive cannot be allowed to both be True, this arg is given precedence over the thermostat arg. kp (float): Kp value to use for PID control. Defaults to 0.06. ki (float): Ki value to use for PID control. Defaults to 0.0075. kd (float): Kd value to use for PID control. Defaults to 0.01. heater_segments (int): the pseudo-control range for the internal heat_controller object. Defaults to 8. update_data_event (multiprocessing.Event): If set, allows the comm_process to signal to the parent process that new device data is available. Returns: nothing """ # since this process is started with daemon=True, it should exit # when the owning process terminates. Therefore, safe to loop forever. while not self._teardown.value: # waiting for command to attempt connect # print( "waiting for command to attempt connect") while self._attempting_connect.value == self.CA_NONE: time.sleep(0.25) if self._teardown.value: break # if we're tearing down, bail now. if self._teardown.value: break # we got the command to attempt to connect # change state to 'attempting_connect' self._connect_state.value = self.CS_ATTEMPTING_CONNECT # attempt connection if self.CA_AUTO == self._attempting_connect.value: # this call will block until a connection is achieved # it will also set _connect_state to CS_CONNECTING # if appropriate if self._auto_connect(): # when we unblock, it is an indication of a successful # connection self._connected.value = 1 self._connect_state.value = self.CS_CONNECTED else: # failure, normally due to a timeout self._connected.value = 0 self._connect_state.value = self.CS_NOT_CONNECTED # we failed to connect - start over from the top # reset flag self._attempting_connect.value = self.CA_NONE continue elif self.CA_SINGLE_SHOT == self._attempting_connect.value: # try once, now, if failure, start teh big loop over try: self._connect() self._connected.value = 1 self._connect_state.value = self.CS_CONNECTED except exceptions.RoasterLookupError: self._connected.value = 0 self._connect_state.value = self.CS_NOT_CONNECTED if self._connect_state.value != self.CS_CONNECTED: # we failed to connect - start over from the top # reset flag self._attempting_connect.value = self.CA_NONE continue else: # shouldn't be here # reset flag self._attempting_connect.value = self.CA_NONE continue # We are connected! # print( "We are connected!") # reset flag right away self._attempting_connect.value = self.CA_NONE # Initialize PID controller if thermostat function was specified at # init time pidc = None heater = None if(thermostat): pidc = pid.PID(kp, ki, kd, Output_max=heater_segments, Output_min=0 ) if thermostat or ext_sw_heater_drive: heater = heat_controller(number_of_segments=heater_segments) read_state = self.LOOKING_FOR_HEADER_1 r = [] write_errors = 0 read_errors = 0 while not self._disconnect.value: start = datetime.datetime.now() # write to device if not self._write_to_device(): logging.error('comm - _write_to_device() failed!') write_errors += 1 if write_errors > 3: # it's time to consider the device as being "gone" logging.error('comm - 3 successive write ' 'failures, disconnecting.') self._disconnect.value = 1 continue else: # reset write_errors write_errors = 0 # read from device try: while self._ser.in_waiting: _byte = self._ser.read(1) read_state, r, err = ( self._process_reponse_byte( read_state, _byte, r, update_data_event)) except IOError: # typically happens when device is suddenly unplugged logging.error('comm - read from device failed!') read_errors += 1 if write_errors > 3: # it's time to consider the device as being "gone" logging.error('comm - 3 successive read ' 'failures, disconnecting.') self._disconnect.value = 1 continue else: read_errors = 0 # next, drive SW heater when using # thermostat mode (PID controller calcs) # or in external sw heater drive mode, # when roasting. if thermostat or ext_sw_heater_drive: if 'roasting' == self.get_roaster_state(): if heater.about_to_rollover(): # it's time to use the PID controller value # and set new output level on heater! if ext_sw_heater_drive: # read user-supplied value heater.heat_level = self._heater_level.value else: # thermostat output = pidc.update( self.current_temp, self.target_temp) heater.heat_level = output # make this number visible to other processes... self._heater_level.value = heater.heat_level # read bang-bang heater output array element & apply it if heater.generate_bangbang_output(): # ON self.heat_setting = 3 else: # OFF self.heat_setting = 0 else: # for all other states, heat_level = OFF heater.heat_level = 0 # make this number visible to other processes... self._heater_level.value = heater.heat_level self.heat_setting = 0 # calculate sleep time to stick to 0.25sec period comp_time = datetime.datetime.now() - start sleep_duration = 0.25 - comp_time.total_seconds() if sleep_duration > 0: time.sleep(sleep_duration) self._ser.close() # reset disconnect flag self._disconnect.value = 0 # reset connection values self._connected.value = 0 self._connect_state.value = self.CS_NOT_CONNECTED # print("We are disconnected.") def _process_reponse_byte(self, read_state, _byte, r, update_data_event): err = False if self.LOOKING_FOR_HEADER_1 == read_state: if b'\xAA' == _byte: read_state = self.LOOKING_FOR_HEADER_2 elif self.LOOKING_FOR_HEADER_2 == read_state: if b'\xAA' == _byte: read_state = self.PACKET_DATA # reset packet array now... r = [] else: read_state = self.LOOKING_FOR_HEADER_1 elif self.PACKET_DATA == read_state: if b'\xAA' == _byte: # this could be the start of an end of packet marker read_state = self.LOOKING_FOR_FOOTER_2 else: r.append(_byte) # SR700 FW bug - if current temp is 250 degF (0xFA), # the FW does not transmit the footer at all. # fake the footer here. if(len(r) == 10 and b'\xFA' == _byte): # we will 'fake' a footer to make this decoder work # as intended read_state, r, _ = ( self._process_reponse_byte( read_state, b'\xAA', r, update_data_event)) read_state, r, err = ( self._process_reponse_byte( read_state, b'\xFA', r, update_data_event)) elif self.LOOKING_FOR_FOOTER_2 == read_state: if b'\xFA' == _byte: # OK we have a full packet - PROCESS PACKET err = self._process_response_data(r, update_data_event) read_state = self.LOOKING_FOR_HEADER_1 else: # the last byte was not the beginning of the footer r.append(b'\xAA') read_state = self.PACKET_DATA read_state, r, err = self._process_reponse_byte( read_state, _byte, r, update_data_event) else: # error state, shouldn't happen... logging.error('_process_reponse_byte - invalid read_state %d' % read_state) read_state = self.LOOKING_FOR_HEADER_1 err = True return read_state, r, err def _process_response_data(self, r, update_data_event): err = False if len(r) != 10: logging.warn('read packet data len not 10, got: %d' % len(r)) logging.warn('RD: ' + str(binascii.hexlify(b''.join(r)))) err = True else: temp = struct.unpack(">H", b''.join(r[8:10]))[0] if(temp == 65280): self.current_temp = 150 elif(temp > 550 or temp < 150): logging.warn('temperature out of range: reinitializing...') self._initialize() err = True return else: self.current_temp = temp if(update_data_event is not None): update_data_event.set() return err def _timer(self, state_transition_event=None): """Timer loop used to keep track of the time while roasting or cooling. If the time remaining reaches zero, the roaster will call the supplied state transistion function or the roaster will be set to the idle state.""" while not self._teardown.value: state = self.get_roaster_state() if(state == 'roasting' or state == 'cooling'): time.sleep(1) self.total_time += 1 if(self.time_remaining > 0): self.time_remaining -= 1 else: if(state_transition_event is not None): state_transition_event.set() else: self.idle() else: time.sleep(0.01) def get_roaster_state(self): """Returns a string based upon the current state of the roaster. Will raise an exception if the state is unknown. Returns: 'idle' if idle, 'sleeping' if sleeping, 'cooling' if cooling, 'roasting' if roasting, 'connecting' if in hardware connection phase, 'unknown' otherwise """ value = self._current_state.value if(value == b'\x02\x01'): return 'idle' elif(value == b'\x04\x04'): return 'cooling' elif(value == b'\x08\x01'): return 'sleeping' # handle null bytes as empty strings elif(value == b'\x00\x00' or value == b''): return 'connecting' elif(value == b'\x04\x02'): return 'roasting' else: return 'unknown' def _generate_packet(self): """Generates a packet based upon the current class variables. Note that current temperature is not sent, as the original application sent zeros to the roaster for the current temperature.""" roaster_time = utils.seconds_to_float(self._time_remaining.value) packet = ( self._header.value + self._temp_unit.value + self._flags.value + self._current_state.value + struct.pack(">B", self._fan_speed.value) + struct.pack(">B", int(round(roaster_time * 10.0))) + struct.pack(">B", self._heat_setting.value) + b'\x00\x00' + self._footer) return packet def idle(self): """Sets the current state of the roaster to idle.""" self._current_state.value = b'\x02\x01' def roast(self): """Sets the current state of the roaster to roast and begins roasting.""" self._current_state.value = b'\x04\x02' def cool(self): """Sets the current state of the roaster to cool. The roaster expects that cool will be run after roast, and will not work as expected if ran before.""" self._current_state.value = b'\x04\x04' def sleep(self): """Sets the current state of the roaster to sleep. Different than idle in that this will set double dashes on the roaster display rather than digits.""" self._current_state.value = b'\x08\x01'
Roastero/freshroastsr700
freshroastsr700/__init__.py
freshroastsr700._auto_connect
python
def _auto_connect(self): while not self._teardown.value: try: self._connect() return True except exceptions.RoasterLookupError: time.sleep(.25) return False
Attempts to connect to the roaster every quarter of a second.
train
https://github.com/Roastero/freshroastsr700/blob/49cf4961444c0f56d051d5ac5088ace480b54f02/freshroastsr700/__init__.py#L590-L598
null
class freshroastsr700(object): """A class to interface with a freshroastsr700 coffee roaster. Args: update_data_func (func): A function to call when this object receives new data from the hardware. Defaults to None. state_transition_func (func): A function to call when time_remaining counts down to 0 and the device is either in roasting or cooling state. Defaults to None. thermostat (bool): thermostat mode. if set to True, turns on thermostat mode. In thermostat mode, freshroastsr700 takes control of heat_setting and does software PID control to hit the demanded target_temp. Defaults to False. ext_sw_heater_drive (bool): enable direct control over the internal heat_controller object. Defaults to False. When set to True, the thermostat field is IGNORED, and assumed to be False. Direct control over the software heater_level means that the freshroastsr700's PID controller cannot control the heater. Since thermostat and ext_sw_heater_drive cannot be allowed to both be True, this arg is given precedence over the thermostat arg. Note that (thermostat=False, ext_sw_heater_drive=False), (thermostat=True, ext_sw_heater_drive=False), (thermostat=False, ext_sw_heater_drive=True), are all acceptable arg combinations. Only the (thermostat=True, ext_sw_heater_drive=True), cominbation is not allowed, and this software will set thermostat=False in that case. kp (float): Kp value to use for PID control. Defaults to 0.06. ki (float): Ki value to use for PID control. Defaults to 0.0075. kd (float): Kd value to use for PID control. Defaults to 0.01. heater_segments (int): the pseudo-control range for the internal heat_controller object. Defaults to 8. """ def __init__(self, update_data_func=None, state_transition_func=None, thermostat=False, kp=0.06, ki=0.0075, kd=0.01, heater_segments=8, ext_sw_heater_drive=False): """Create variables used to send in packets to the roaster. The update data function is called when a packet is opened. The state transistion function is used by the timer thread to know what to do next. See wiki for more information on packet structure and fields.""" # constants for protocol decoding self.LOOKING_FOR_HEADER_1 = 0 self.LOOKING_FOR_HEADER_2 = 1 self.PACKET_DATA = 2 self.LOOKING_FOR_FOOTER_2 = 3 # constants for connection state monitoring self.CS_NOT_CONNECTED = -2 self.CS_ATTEMPTING_CONNECT = -1 self.CS_CONNECTING = 0 self.CS_CONNECTED = 1 # constants for connection attempt type self.CA_NONE = 0 self.CA_AUTO = 1 self.CA_SINGLE_SHOT = 2 self._create_update_data_system(update_data_func) self._create_state_transition_system(state_transition_func) self._header = sharedctypes.Array('c', b'\xAA\xAA') self._temp_unit = sharedctypes.Array('c', b'\x61\x74') self._flags = sharedctypes.Array('c', b'\x63') self._current_state = sharedctypes.Array('c', b'\x02\x01') self._footer = b'\xAA\xFA' self._fan_speed = sharedctypes.Value('i', 1) self._heat_setting = sharedctypes.Value('i', 0) self._target_temp = sharedctypes.Value('i', 150) self._current_temp = sharedctypes.Value('i', 150) self._time_remaining = sharedctypes.Value('i', 0) self._total_time = sharedctypes.Value('i', 0) self._disconnect = sharedctypes.Value('i', 0) self._teardown = sharedctypes.Value('i', 0) # for SW PWM heater setting self._heater_level = sharedctypes.Value('i', 0) # the following vars are not process-safe, do not access them # from the comm or timer threads, nor from the callbacks. self._ext_sw_heater_drive = ext_sw_heater_drive if not self._ext_sw_heater_drive: self._thermostat = thermostat else: self._thermostat = False self._pid_kp = kp self._pid_ki = ki self._pid_kd = kd self._heater_bangbang_segments = heater_segments # initialize to 'not connected' self._connected = sharedctypes.Value('i', 0) self._connect_state = sharedctypes.Value('i', self.CS_NOT_CONNECTED) # initialize to 'not trying to connect' self._attempting_connect = sharedctypes.Value('i', self.CA_NONE) # create comm process self.comm_process = mp.Process( target=self._comm, args=( self._thermostat, self._pid_kp, self._pid_ki, self._pid_kd, self._heater_bangbang_segments, self._ext_sw_heater_drive, self.update_data_event,)) self.comm_process.daemon = True self.comm_process.start() # create timer process that counts down time_remaining self.time_process = mp.Process( target=self._timer, args=( self.state_transition_event,)) self.time_process.daemon = True self.time_process.start() def _create_update_data_system( self, update_data_func, setFunc=True, createThread=False): # these callbacks cannot be called from another process in Windows. # Therefore, spawn a thread belonging to the calling process # instead. # the comm and timer processes will set events that the threads # will listen for to initiate the callbacks # only create the mp.Event once - # to mimic create_state_transition_system, for future-proofing # (in this case, currently, this is only called at __init__() time) if not hasattr(self, 'update_data_event'): self.update_data_event = mp.Event() # only create the thread.Event once - this is used to exit # the callback thread if not hasattr(self, 'update_data_callback_kill_event'): self.update_data_callback_kill_event = mp.Event() # destroy an existing thread if we had created one previously if(hasattr(self, 'update_data_thread') and self.update_data_thread is not None): # let's tear this down. To kill it, two events must be set... # in the right sequence! self.update_data_callback_kill_event.set() self.update_data_event.set() self.update_data_thread.join() if setFunc: self.update_data_func = update_data_func if self.update_data_func is not None: if createThread: self.update_data_callback_kill_event.clear() self.update_data_thread = threading.Thread( name='sr700_update_data', target=self.update_data_run, args=(self.update_data_event,), daemon=True ) else: self.update_data_thread = None def _create_state_transition_system( self, state_transition_func, setFunc=True, createThread=False): # these callbacks cannot be called from another process in Windows. # Therefore, spawn a thread belonging to the calling process # instead. # the comm and timer processes will set events that the threads # will listen for to initiate the callbacks # only create the mp.Event once - this fn can get called more # than once, by __init__() and by set_state_transition_func() if not hasattr(self, 'state_transition_event'): self.state_transition_event = mp.Event() # only create the thread.Event once - this is used to exit # the callback thread if not hasattr(self, 'state_transition_callback_kill_event'): self.state_transition_callback_kill_event = mp.Event() # destroy an existing thread if we had created one previously if(hasattr(self, 'state_transition_thread') and self.state_transition_thread is not None): # let's tear this down. To kill it, two events must be set... # in the right sequence! self.state_transition_callback_kill_event.set() self.state_transition_event.set() self.state_transition_thread.join() if setFunc: self.state_transition_func = state_transition_func if self.state_transition_func is not None: if createThread: self.state_transition_callback_kill_event.clear() self.state_transition_thread = threading.Thread( name='sr700_state_transition', target=self.state_transition_run, args=(self.state_transition_event,), daemon=True ) else: self.state_transition_thread = None @property def fan_speed(self): """Get/Set fan speed. Can be 1 to 9 inclusive. Args: Setter: fan_speed (int): fan speed Returns: Getter: (int): fan speed """ return self._fan_speed.value @fan_speed.setter def fan_speed(self, value): """Verifies the value is between 1 and 9 inclusively.""" if value not in range(1, 10): raise exceptions.RoasterValueError self._fan_speed.value = value @property def heat_setting(self): """Get/Set heat setting, 0 to 3 inclusive. 0=off, 3=high. Do not set when running freshroastsr700 in thermostat mode. Args: Setter: heat_setting (int): heat setting Returns: Getter: (int): heat setting """ return self._heat_setting.value @heat_setting.setter def heat_setting(self, value): """Verifies that the heat setting is between 0 and 3.""" if value not in range(0, 4): raise exceptions.RoasterValueError self._heat_setting.value = value @property def target_temp(self): """Get/Set the target temperature for this package's built-in software PID controler. Only used when freshroastsr700 is instantiated with thermostat=True. Args: Setter: value (int): a target temperature in degF between 150 and 551. Returns: Getter: (int) target temperature in degF between 150 and 551 """ return self._target_temp.value @target_temp.setter def target_temp(self, value): if value not in range(150, 551): raise exceptions.RoasterValueError self._target_temp.value = value @property def current_temp(self): """Current temperature of the roast chamber as reported by hardware. Returns: (int) current temperature, in degrees Fahrenheit """ return self._current_temp.value @current_temp.setter def current_temp(self, value): if value not in range(150, 551): raise exceptions.RoasterValueError self._current_temp.value = value @property def time_remaining(self): """The amount of time, in seconds, remaining until a call to the state_transition_func is made. can be set to an arbitrary value up to 600 seconds at any time. When a new value is set, freshroastsr700 will count down from this new value down to 0. time_remaining is decremented to 0 only when in a roasting or cooling state. In other states, the value is not touched. Args: Setter: time_remaining (int): tiem remaining in seconds Returns: Getter: time_remaining(int): time remaining, in seconds """ return self._time_remaining.value @time_remaining.setter def time_remaining(self, value): self._time_remaining.value = value @property def total_time(self): """The total time this instance has been in roasting or cooling state sicne the latest roast began. Returns: total_time (int): time, in seconds """ return self._total_time.value @total_time.setter def total_time(self, value): self._total_time.value = value @property def heater_level(self): """A getter method for _heater_level. When thermostat=True, value is driven by built-in PID controller. When ext_sw_heater_drive=True, value is driven by calls to heater_level(). Min will always be zero, max will be heater_segments (optional instantiation parameter, defaults to 8).""" return self._heater_level.value @heater_level.setter def heater_level(self, value): """Verifies that the heater_level is between 0 and heater_segments. Can only be called when freshroastsr700 object is initialized with ext_sw_heater_drive=True. Will throw RoasterValueError otherwise.""" if self._ext_sw_heater_drive: if value not in range(0, self._heater_bangbang_segments+1): raise exceptions.RoasterValueError self._heater_level.value = value else: raise exceptions.RoasterValueError @property def connected(self): """A getter method for _connected. Indicates that the this software is currently communicating with FreshRoast SR700 hardware.""" return self._connected.value @property def connect_state(self): """A getter method for _connect_state. Indicates the current connection state this software is in for FreshRoast SR700 hardware. Returns: freshroastsr700.CS_NOT_CONNECTED the software is not currenting communicating with hardware, neither was it instructed to do so. A previously failed connection attempt will also result in this state. freshroastsr700.CS_ATTEMPTING_CONNECT A call to auto_connect() or connect() was made, and the software is currently attempting to connect to hardware. freshroastsr700.CS_CONNECTED The hardware was found, and the software is communicating with the hardware. """ return self._connect_state.value def set_state_transition_func(self, func): """THIS FUNCTION MUST BE CALLED BEFORE CALLING freshroastsr700.auto_connect(). Set, or re-set, the state transition function callback. The supplied function will be called from a separate thread within freshroastsr700, triggered by a separate, internal child process. This function will fail if the freshroastsr700 device is already connected to hardware, because by that time, the timer process and thread have already been spawned. Args: state_transition_func (func): the function to call for every state transition. A state transition occurs whenever the freshroastsr700's time_remaining value counts down to 0. Returns: nothing """ if self._connected.value: logging.error("freshroastsr700.set_state_transition_func must be " "called before freshroastsr700.auto_connect()." " Not registering func.") return False # no connection yet. so OK to set func pointer self._create_state_transition_system(func) return True def update_data_run(self, event_to_wait_on): """This is the thread that listens to an event from the comm process to execute the update_data_func callback in the context of the main process. """ # with the daemon=Turue setting, this thread should # quit 'automatically' while event_to_wait_on.wait(): event_to_wait_on.clear() if self.update_data_callback_kill_event.is_set(): return self.update_data_func() def state_transition_run(self, event_to_wait_on): """This is the thread that listens to an event from the timer process to execute the state_transition_func callback in the context of the main process. """ # with the daemon=Turue setting, this thread should # quit 'automatically' while event_to_wait_on.wait(): event_to_wait_on.clear() if self.state_transition_callback_kill_event.is_set(): return self.state_transition_func() def _connect(self): """Do not call this directly - call auto_connect() or connect(), which will call _connect() for you. Connects to the roaster and creates communication thread. Raises a RoasterLokkupError exception if the hardware is not found. """ # the following call raises a RoasterLookupException when the device # is not found. It is port = utils.find_device('1A86:5523') # on some systems, after the device port is added to the device list, # it can take up to 20 seconds after USB insertion for # the port to become available... (!) # let's put a safety timeout in here as a precaution wait_timeout = time.time() + 40.0 # should be PLENTY of time! # let's update the _connect_state while we're at it... self._connect_state.value = self.CS_CONNECTING connect_success = False while time.time() < wait_timeout: try: self._ser = serial.Serial( port=port, baudrate=9600, bytesize=8, parity='N', stopbits=1.5, timeout=0.25, xonxoff=False, rtscts=False, dsrdtr=False) connect_success = True break except serial.SerialException: time.sleep(0.5) if not connect_success: # timeout on attempts raise exceptions.RoasterLookupError self._initialize() def _initialize(self): """Sends the initialization packet to the roaster.""" self._header.value = b'\xAA\x55' self._current_state.value = b'\x00\x00' s = self._generate_packet() self._ser.write(s) self._header.value = b'\xAA\xAA' self._current_state.value = b'\x02\x01' return self._read_existing_recipe() def _write_to_device(self): success = False try: packet = self._generate_packet() logging.debug('WR: ' + str(binascii.hexlify(packet))) self._ser.write(packet) success = True except serial.serialutil.SerialException: logging.error('caught serial exception writing') return success def _read_from_device(self): r = [] footer_reached = False while len(r) < 14 and footer_reached is False: r.append(self._ser.read(1)) if len(r) >= 2 and b''.join(r)[-2:] == self._footer: footer_reached = True logging.debug('RD: ' + str(binascii.hexlify(b''.join(r)))) return b''.join(r) def _read_existing_recipe(self): existing_recipe = [] end_of_recipe = False while not end_of_recipe: bytes_waiting = self._ser.in_waiting if bytes_waiting < 14: # still need to write to device every .25sec it seems time.sleep(0.25) self._write_to_device() else: while (bytes_waiting // 14) > 0: r = self._read_from_device() bytes_waiting = self._ser.in_waiting if len(r) < 14: logging.warn('short packet length') else: existing_recipe.append(r) if r[4:5] == b'\xAF' or r[4:5] == b'\x00': end_of_recipe = True continue return existing_recipe def connect(self): """Attempt to connect to hardware immediately. Will not retry. Check freshroastsr700.connected or freshroastsr700.connect_state to verify result. Raises: freshroastsr700.exeptions.RoasterLookupError No hardware connected to the computer. """ self._start_connect(self.CA_SINGLE_SHOT) while(self._connect_state.value == self.CS_ATTEMPTING_CONNECT or self._connect_state.value == self.CS_CONNECTING): time.sleep(0.1) if self.CS_CONNECTED != self._connect_state.value: raise exceptions.RoasterLookupError def auto_connect(self): """Starts a thread that will automatically connect to the roaster when it is plugged in.""" self._start_connect(self.CA_AUTO) def _start_connect(self, connect_type): """Starts the connection process, as called (internally) from the user context, either from auto_connect() or connect(). Never call this from the _comm() process context. """ if self._connect_state.value != self.CS_NOT_CONNECTED: # already done or in process, assume success return self._connected.value = 0 self._connect_state.value = self.CS_ATTEMPTING_CONNECT # tell comm process to attempt connection self._attempting_connect.value = connect_type # EXTREMELY IMPORTANT - for this to work at all in Windows, # where the above processes are spawned (vs forked in Unix), # the thread objects (as sattributes of this object) must be # assigned to this object AFTER we have spawned the processes. # That way, multiprocessing can pickle the freshroastsr700 # successfully. (It can't pickle thread-related stuff.) if self.update_data_func is not None: # Need to launch the thread that will listen to the event self._create_update_data_system( None, setFunc=False, createThread=True) self.update_data_thread.start() if self.state_transition_func is not None: # Need to launch the thread that will listen to the event self._create_state_transition_system( None, setFunc=False, createThread=True) self.state_transition_thread.start() def disconnect(self): """Stops the communication loop to the roaster. Note that this will not actually stop the roaster itself.""" self._disconnect.value = 1 def terminate(self): """Stops the communication loop to the roaster and closes down all communication processes. Note that this will not actually stop the roaster itself. You will need to instantiate a new freshroastsr700 object after calling this function, in order to re-start communications with the hardware. """ self.disconnect() self._teardown.value = 1 def _comm(self, thermostat=False, kp=0.06, ki=0.0075, kd=0.01, heater_segments=8, ext_sw_heater_drive=False, update_data_event=None): """Do not call this directly - call auto_connect(), which will spawn comm() for you. This is the main communications loop to the roaster. whenever a valid packet is received from the device, if an update_data_event is available, it will be signalled. Args: thermostat (bool): thermostat mode. if set to True, turns on thermostat mode. In thermostat mode, freshroastsr700 takes control of heat_setting and does software PID control to hit the demanded target_temp. ext_sw_heater_drive (bool): enable direct control over the internal heat_controller object. Defaults to False. When set to True, the thermostat field is IGNORED, and assumed to be False. Direct control over the software heater_level means that the PID controller cannot control the heater. Since thermostat and ext_sw_heater_drive cannot be allowed to both be True, this arg is given precedence over the thermostat arg. kp (float): Kp value to use for PID control. Defaults to 0.06. ki (float): Ki value to use for PID control. Defaults to 0.0075. kd (float): Kd value to use for PID control. Defaults to 0.01. heater_segments (int): the pseudo-control range for the internal heat_controller object. Defaults to 8. update_data_event (multiprocessing.Event): If set, allows the comm_process to signal to the parent process that new device data is available. Returns: nothing """ # since this process is started with daemon=True, it should exit # when the owning process terminates. Therefore, safe to loop forever. while not self._teardown.value: # waiting for command to attempt connect # print( "waiting for command to attempt connect") while self._attempting_connect.value == self.CA_NONE: time.sleep(0.25) if self._teardown.value: break # if we're tearing down, bail now. if self._teardown.value: break # we got the command to attempt to connect # change state to 'attempting_connect' self._connect_state.value = self.CS_ATTEMPTING_CONNECT # attempt connection if self.CA_AUTO == self._attempting_connect.value: # this call will block until a connection is achieved # it will also set _connect_state to CS_CONNECTING # if appropriate if self._auto_connect(): # when we unblock, it is an indication of a successful # connection self._connected.value = 1 self._connect_state.value = self.CS_CONNECTED else: # failure, normally due to a timeout self._connected.value = 0 self._connect_state.value = self.CS_NOT_CONNECTED # we failed to connect - start over from the top # reset flag self._attempting_connect.value = self.CA_NONE continue elif self.CA_SINGLE_SHOT == self._attempting_connect.value: # try once, now, if failure, start teh big loop over try: self._connect() self._connected.value = 1 self._connect_state.value = self.CS_CONNECTED except exceptions.RoasterLookupError: self._connected.value = 0 self._connect_state.value = self.CS_NOT_CONNECTED if self._connect_state.value != self.CS_CONNECTED: # we failed to connect - start over from the top # reset flag self._attempting_connect.value = self.CA_NONE continue else: # shouldn't be here # reset flag self._attempting_connect.value = self.CA_NONE continue # We are connected! # print( "We are connected!") # reset flag right away self._attempting_connect.value = self.CA_NONE # Initialize PID controller if thermostat function was specified at # init time pidc = None heater = None if(thermostat): pidc = pid.PID(kp, ki, kd, Output_max=heater_segments, Output_min=0 ) if thermostat or ext_sw_heater_drive: heater = heat_controller(number_of_segments=heater_segments) read_state = self.LOOKING_FOR_HEADER_1 r = [] write_errors = 0 read_errors = 0 while not self._disconnect.value: start = datetime.datetime.now() # write to device if not self._write_to_device(): logging.error('comm - _write_to_device() failed!') write_errors += 1 if write_errors > 3: # it's time to consider the device as being "gone" logging.error('comm - 3 successive write ' 'failures, disconnecting.') self._disconnect.value = 1 continue else: # reset write_errors write_errors = 0 # read from device try: while self._ser.in_waiting: _byte = self._ser.read(1) read_state, r, err = ( self._process_reponse_byte( read_state, _byte, r, update_data_event)) except IOError: # typically happens when device is suddenly unplugged logging.error('comm - read from device failed!') read_errors += 1 if write_errors > 3: # it's time to consider the device as being "gone" logging.error('comm - 3 successive read ' 'failures, disconnecting.') self._disconnect.value = 1 continue else: read_errors = 0 # next, drive SW heater when using # thermostat mode (PID controller calcs) # or in external sw heater drive mode, # when roasting. if thermostat or ext_sw_heater_drive: if 'roasting' == self.get_roaster_state(): if heater.about_to_rollover(): # it's time to use the PID controller value # and set new output level on heater! if ext_sw_heater_drive: # read user-supplied value heater.heat_level = self._heater_level.value else: # thermostat output = pidc.update( self.current_temp, self.target_temp) heater.heat_level = output # make this number visible to other processes... self._heater_level.value = heater.heat_level # read bang-bang heater output array element & apply it if heater.generate_bangbang_output(): # ON self.heat_setting = 3 else: # OFF self.heat_setting = 0 else: # for all other states, heat_level = OFF heater.heat_level = 0 # make this number visible to other processes... self._heater_level.value = heater.heat_level self.heat_setting = 0 # calculate sleep time to stick to 0.25sec period comp_time = datetime.datetime.now() - start sleep_duration = 0.25 - comp_time.total_seconds() if sleep_duration > 0: time.sleep(sleep_duration) self._ser.close() # reset disconnect flag self._disconnect.value = 0 # reset connection values self._connected.value = 0 self._connect_state.value = self.CS_NOT_CONNECTED # print("We are disconnected.") def _process_reponse_byte(self, read_state, _byte, r, update_data_event): err = False if self.LOOKING_FOR_HEADER_1 == read_state: if b'\xAA' == _byte: read_state = self.LOOKING_FOR_HEADER_2 elif self.LOOKING_FOR_HEADER_2 == read_state: if b'\xAA' == _byte: read_state = self.PACKET_DATA # reset packet array now... r = [] else: read_state = self.LOOKING_FOR_HEADER_1 elif self.PACKET_DATA == read_state: if b'\xAA' == _byte: # this could be the start of an end of packet marker read_state = self.LOOKING_FOR_FOOTER_2 else: r.append(_byte) # SR700 FW bug - if current temp is 250 degF (0xFA), # the FW does not transmit the footer at all. # fake the footer here. if(len(r) == 10 and b'\xFA' == _byte): # we will 'fake' a footer to make this decoder work # as intended read_state, r, _ = ( self._process_reponse_byte( read_state, b'\xAA', r, update_data_event)) read_state, r, err = ( self._process_reponse_byte( read_state, b'\xFA', r, update_data_event)) elif self.LOOKING_FOR_FOOTER_2 == read_state: if b'\xFA' == _byte: # OK we have a full packet - PROCESS PACKET err = self._process_response_data(r, update_data_event) read_state = self.LOOKING_FOR_HEADER_1 else: # the last byte was not the beginning of the footer r.append(b'\xAA') read_state = self.PACKET_DATA read_state, r, err = self._process_reponse_byte( read_state, _byte, r, update_data_event) else: # error state, shouldn't happen... logging.error('_process_reponse_byte - invalid read_state %d' % read_state) read_state = self.LOOKING_FOR_HEADER_1 err = True return read_state, r, err def _process_response_data(self, r, update_data_event): err = False if len(r) != 10: logging.warn('read packet data len not 10, got: %d' % len(r)) logging.warn('RD: ' + str(binascii.hexlify(b''.join(r)))) err = True else: temp = struct.unpack(">H", b''.join(r[8:10]))[0] if(temp == 65280): self.current_temp = 150 elif(temp > 550 or temp < 150): logging.warn('temperature out of range: reinitializing...') self._initialize() err = True return else: self.current_temp = temp if(update_data_event is not None): update_data_event.set() return err def _timer(self, state_transition_event=None): """Timer loop used to keep track of the time while roasting or cooling. If the time remaining reaches zero, the roaster will call the supplied state transistion function or the roaster will be set to the idle state.""" while not self._teardown.value: state = self.get_roaster_state() if(state == 'roasting' or state == 'cooling'): time.sleep(1) self.total_time += 1 if(self.time_remaining > 0): self.time_remaining -= 1 else: if(state_transition_event is not None): state_transition_event.set() else: self.idle() else: time.sleep(0.01) def get_roaster_state(self): """Returns a string based upon the current state of the roaster. Will raise an exception if the state is unknown. Returns: 'idle' if idle, 'sleeping' if sleeping, 'cooling' if cooling, 'roasting' if roasting, 'connecting' if in hardware connection phase, 'unknown' otherwise """ value = self._current_state.value if(value == b'\x02\x01'): return 'idle' elif(value == b'\x04\x04'): return 'cooling' elif(value == b'\x08\x01'): return 'sleeping' # handle null bytes as empty strings elif(value == b'\x00\x00' or value == b''): return 'connecting' elif(value == b'\x04\x02'): return 'roasting' else: return 'unknown' def _generate_packet(self): """Generates a packet based upon the current class variables. Note that current temperature is not sent, as the original application sent zeros to the roaster for the current temperature.""" roaster_time = utils.seconds_to_float(self._time_remaining.value) packet = ( self._header.value + self._temp_unit.value + self._flags.value + self._current_state.value + struct.pack(">B", self._fan_speed.value) + struct.pack(">B", int(round(roaster_time * 10.0))) + struct.pack(">B", self._heat_setting.value) + b'\x00\x00' + self._footer) return packet def idle(self): """Sets the current state of the roaster to idle.""" self._current_state.value = b'\x02\x01' def roast(self): """Sets the current state of the roaster to roast and begins roasting.""" self._current_state.value = b'\x04\x02' def cool(self): """Sets the current state of the roaster to cool. The roaster expects that cool will be run after roast, and will not work as expected if ran before.""" self._current_state.value = b'\x04\x04' def sleep(self): """Sets the current state of the roaster to sleep. Different than idle in that this will set double dashes on the roaster display rather than digits.""" self._current_state.value = b'\x08\x01'
Roastero/freshroastsr700
freshroastsr700/__init__.py
freshroastsr700._comm
python
def _comm(self, thermostat=False, kp=0.06, ki=0.0075, kd=0.01, heater_segments=8, ext_sw_heater_drive=False, update_data_event=None): # since this process is started with daemon=True, it should exit # when the owning process terminates. Therefore, safe to loop forever. while not self._teardown.value: # waiting for command to attempt connect # print( "waiting for command to attempt connect") while self._attempting_connect.value == self.CA_NONE: time.sleep(0.25) if self._teardown.value: break # if we're tearing down, bail now. if self._teardown.value: break # we got the command to attempt to connect # change state to 'attempting_connect' self._connect_state.value = self.CS_ATTEMPTING_CONNECT # attempt connection if self.CA_AUTO == self._attempting_connect.value: # this call will block until a connection is achieved # it will also set _connect_state to CS_CONNECTING # if appropriate if self._auto_connect(): # when we unblock, it is an indication of a successful # connection self._connected.value = 1 self._connect_state.value = self.CS_CONNECTED else: # failure, normally due to a timeout self._connected.value = 0 self._connect_state.value = self.CS_NOT_CONNECTED # we failed to connect - start over from the top # reset flag self._attempting_connect.value = self.CA_NONE continue elif self.CA_SINGLE_SHOT == self._attempting_connect.value: # try once, now, if failure, start teh big loop over try: self._connect() self._connected.value = 1 self._connect_state.value = self.CS_CONNECTED except exceptions.RoasterLookupError: self._connected.value = 0 self._connect_state.value = self.CS_NOT_CONNECTED if self._connect_state.value != self.CS_CONNECTED: # we failed to connect - start over from the top # reset flag self._attempting_connect.value = self.CA_NONE continue else: # shouldn't be here # reset flag self._attempting_connect.value = self.CA_NONE continue # We are connected! # print( "We are connected!") # reset flag right away self._attempting_connect.value = self.CA_NONE # Initialize PID controller if thermostat function was specified at # init time pidc = None heater = None if(thermostat): pidc = pid.PID(kp, ki, kd, Output_max=heater_segments, Output_min=0 ) if thermostat or ext_sw_heater_drive: heater = heat_controller(number_of_segments=heater_segments) read_state = self.LOOKING_FOR_HEADER_1 r = [] write_errors = 0 read_errors = 0 while not self._disconnect.value: start = datetime.datetime.now() # write to device if not self._write_to_device(): logging.error('comm - _write_to_device() failed!') write_errors += 1 if write_errors > 3: # it's time to consider the device as being "gone" logging.error('comm - 3 successive write ' 'failures, disconnecting.') self._disconnect.value = 1 continue else: # reset write_errors write_errors = 0 # read from device try: while self._ser.in_waiting: _byte = self._ser.read(1) read_state, r, err = ( self._process_reponse_byte( read_state, _byte, r, update_data_event)) except IOError: # typically happens when device is suddenly unplugged logging.error('comm - read from device failed!') read_errors += 1 if write_errors > 3: # it's time to consider the device as being "gone" logging.error('comm - 3 successive read ' 'failures, disconnecting.') self._disconnect.value = 1 continue else: read_errors = 0 # next, drive SW heater when using # thermostat mode (PID controller calcs) # or in external sw heater drive mode, # when roasting. if thermostat or ext_sw_heater_drive: if 'roasting' == self.get_roaster_state(): if heater.about_to_rollover(): # it's time to use the PID controller value # and set new output level on heater! if ext_sw_heater_drive: # read user-supplied value heater.heat_level = self._heater_level.value else: # thermostat output = pidc.update( self.current_temp, self.target_temp) heater.heat_level = output # make this number visible to other processes... self._heater_level.value = heater.heat_level # read bang-bang heater output array element & apply it if heater.generate_bangbang_output(): # ON self.heat_setting = 3 else: # OFF self.heat_setting = 0 else: # for all other states, heat_level = OFF heater.heat_level = 0 # make this number visible to other processes... self._heater_level.value = heater.heat_level self.heat_setting = 0 # calculate sleep time to stick to 0.25sec period comp_time = datetime.datetime.now() - start sleep_duration = 0.25 - comp_time.total_seconds() if sleep_duration > 0: time.sleep(sleep_duration) self._ser.close() # reset disconnect flag self._disconnect.value = 0 # reset connection values self._connected.value = 0 self._connect_state.value = self.CS_NOT_CONNECTED
Do not call this directly - call auto_connect(), which will spawn comm() for you. This is the main communications loop to the roaster. whenever a valid packet is received from the device, if an update_data_event is available, it will be signalled. Args: thermostat (bool): thermostat mode. if set to True, turns on thermostat mode. In thermostat mode, freshroastsr700 takes control of heat_setting and does software PID control to hit the demanded target_temp. ext_sw_heater_drive (bool): enable direct control over the internal heat_controller object. Defaults to False. When set to True, the thermostat field is IGNORED, and assumed to be False. Direct control over the software heater_level means that the PID controller cannot control the heater. Since thermostat and ext_sw_heater_drive cannot be allowed to both be True, this arg is given precedence over the thermostat arg. kp (float): Kp value to use for PID control. Defaults to 0.06. ki (float): Ki value to use for PID control. Defaults to 0.0075. kd (float): Kd value to use for PID control. Defaults to 0.01. heater_segments (int): the pseudo-control range for the internal heat_controller object. Defaults to 8. update_data_event (multiprocessing.Event): If set, allows the comm_process to signal to the parent process that new device data is available. Returns: nothing
train
https://github.com/Roastero/freshroastsr700/blob/49cf4961444c0f56d051d5ac5088ace480b54f02/freshroastsr700/__init__.py#L616-L814
null
class freshroastsr700(object): """A class to interface with a freshroastsr700 coffee roaster. Args: update_data_func (func): A function to call when this object receives new data from the hardware. Defaults to None. state_transition_func (func): A function to call when time_remaining counts down to 0 and the device is either in roasting or cooling state. Defaults to None. thermostat (bool): thermostat mode. if set to True, turns on thermostat mode. In thermostat mode, freshroastsr700 takes control of heat_setting and does software PID control to hit the demanded target_temp. Defaults to False. ext_sw_heater_drive (bool): enable direct control over the internal heat_controller object. Defaults to False. When set to True, the thermostat field is IGNORED, and assumed to be False. Direct control over the software heater_level means that the freshroastsr700's PID controller cannot control the heater. Since thermostat and ext_sw_heater_drive cannot be allowed to both be True, this arg is given precedence over the thermostat arg. Note that (thermostat=False, ext_sw_heater_drive=False), (thermostat=True, ext_sw_heater_drive=False), (thermostat=False, ext_sw_heater_drive=True), are all acceptable arg combinations. Only the (thermostat=True, ext_sw_heater_drive=True), cominbation is not allowed, and this software will set thermostat=False in that case. kp (float): Kp value to use for PID control. Defaults to 0.06. ki (float): Ki value to use for PID control. Defaults to 0.0075. kd (float): Kd value to use for PID control. Defaults to 0.01. heater_segments (int): the pseudo-control range for the internal heat_controller object. Defaults to 8. """ def __init__(self, update_data_func=None, state_transition_func=None, thermostat=False, kp=0.06, ki=0.0075, kd=0.01, heater_segments=8, ext_sw_heater_drive=False): """Create variables used to send in packets to the roaster. The update data function is called when a packet is opened. The state transistion function is used by the timer thread to know what to do next. See wiki for more information on packet structure and fields.""" # constants for protocol decoding self.LOOKING_FOR_HEADER_1 = 0 self.LOOKING_FOR_HEADER_2 = 1 self.PACKET_DATA = 2 self.LOOKING_FOR_FOOTER_2 = 3 # constants for connection state monitoring self.CS_NOT_CONNECTED = -2 self.CS_ATTEMPTING_CONNECT = -1 self.CS_CONNECTING = 0 self.CS_CONNECTED = 1 # constants for connection attempt type self.CA_NONE = 0 self.CA_AUTO = 1 self.CA_SINGLE_SHOT = 2 self._create_update_data_system(update_data_func) self._create_state_transition_system(state_transition_func) self._header = sharedctypes.Array('c', b'\xAA\xAA') self._temp_unit = sharedctypes.Array('c', b'\x61\x74') self._flags = sharedctypes.Array('c', b'\x63') self._current_state = sharedctypes.Array('c', b'\x02\x01') self._footer = b'\xAA\xFA' self._fan_speed = sharedctypes.Value('i', 1) self._heat_setting = sharedctypes.Value('i', 0) self._target_temp = sharedctypes.Value('i', 150) self._current_temp = sharedctypes.Value('i', 150) self._time_remaining = sharedctypes.Value('i', 0) self._total_time = sharedctypes.Value('i', 0) self._disconnect = sharedctypes.Value('i', 0) self._teardown = sharedctypes.Value('i', 0) # for SW PWM heater setting self._heater_level = sharedctypes.Value('i', 0) # the following vars are not process-safe, do not access them # from the comm or timer threads, nor from the callbacks. self._ext_sw_heater_drive = ext_sw_heater_drive if not self._ext_sw_heater_drive: self._thermostat = thermostat else: self._thermostat = False self._pid_kp = kp self._pid_ki = ki self._pid_kd = kd self._heater_bangbang_segments = heater_segments # initialize to 'not connected' self._connected = sharedctypes.Value('i', 0) self._connect_state = sharedctypes.Value('i', self.CS_NOT_CONNECTED) # initialize to 'not trying to connect' self._attempting_connect = sharedctypes.Value('i', self.CA_NONE) # create comm process self.comm_process = mp.Process( target=self._comm, args=( self._thermostat, self._pid_kp, self._pid_ki, self._pid_kd, self._heater_bangbang_segments, self._ext_sw_heater_drive, self.update_data_event,)) self.comm_process.daemon = True self.comm_process.start() # create timer process that counts down time_remaining self.time_process = mp.Process( target=self._timer, args=( self.state_transition_event,)) self.time_process.daemon = True self.time_process.start() def _create_update_data_system( self, update_data_func, setFunc=True, createThread=False): # these callbacks cannot be called from another process in Windows. # Therefore, spawn a thread belonging to the calling process # instead. # the comm and timer processes will set events that the threads # will listen for to initiate the callbacks # only create the mp.Event once - # to mimic create_state_transition_system, for future-proofing # (in this case, currently, this is only called at __init__() time) if not hasattr(self, 'update_data_event'): self.update_data_event = mp.Event() # only create the thread.Event once - this is used to exit # the callback thread if not hasattr(self, 'update_data_callback_kill_event'): self.update_data_callback_kill_event = mp.Event() # destroy an existing thread if we had created one previously if(hasattr(self, 'update_data_thread') and self.update_data_thread is not None): # let's tear this down. To kill it, two events must be set... # in the right sequence! self.update_data_callback_kill_event.set() self.update_data_event.set() self.update_data_thread.join() if setFunc: self.update_data_func = update_data_func if self.update_data_func is not None: if createThread: self.update_data_callback_kill_event.clear() self.update_data_thread = threading.Thread( name='sr700_update_data', target=self.update_data_run, args=(self.update_data_event,), daemon=True ) else: self.update_data_thread = None def _create_state_transition_system( self, state_transition_func, setFunc=True, createThread=False): # these callbacks cannot be called from another process in Windows. # Therefore, spawn a thread belonging to the calling process # instead. # the comm and timer processes will set events that the threads # will listen for to initiate the callbacks # only create the mp.Event once - this fn can get called more # than once, by __init__() and by set_state_transition_func() if not hasattr(self, 'state_transition_event'): self.state_transition_event = mp.Event() # only create the thread.Event once - this is used to exit # the callback thread if not hasattr(self, 'state_transition_callback_kill_event'): self.state_transition_callback_kill_event = mp.Event() # destroy an existing thread if we had created one previously if(hasattr(self, 'state_transition_thread') and self.state_transition_thread is not None): # let's tear this down. To kill it, two events must be set... # in the right sequence! self.state_transition_callback_kill_event.set() self.state_transition_event.set() self.state_transition_thread.join() if setFunc: self.state_transition_func = state_transition_func if self.state_transition_func is not None: if createThread: self.state_transition_callback_kill_event.clear() self.state_transition_thread = threading.Thread( name='sr700_state_transition', target=self.state_transition_run, args=(self.state_transition_event,), daemon=True ) else: self.state_transition_thread = None @property def fan_speed(self): """Get/Set fan speed. Can be 1 to 9 inclusive. Args: Setter: fan_speed (int): fan speed Returns: Getter: (int): fan speed """ return self._fan_speed.value @fan_speed.setter def fan_speed(self, value): """Verifies the value is between 1 and 9 inclusively.""" if value not in range(1, 10): raise exceptions.RoasterValueError self._fan_speed.value = value @property def heat_setting(self): """Get/Set heat setting, 0 to 3 inclusive. 0=off, 3=high. Do not set when running freshroastsr700 in thermostat mode. Args: Setter: heat_setting (int): heat setting Returns: Getter: (int): heat setting """ return self._heat_setting.value @heat_setting.setter def heat_setting(self, value): """Verifies that the heat setting is between 0 and 3.""" if value not in range(0, 4): raise exceptions.RoasterValueError self._heat_setting.value = value @property def target_temp(self): """Get/Set the target temperature for this package's built-in software PID controler. Only used when freshroastsr700 is instantiated with thermostat=True. Args: Setter: value (int): a target temperature in degF between 150 and 551. Returns: Getter: (int) target temperature in degF between 150 and 551 """ return self._target_temp.value @target_temp.setter def target_temp(self, value): if value not in range(150, 551): raise exceptions.RoasterValueError self._target_temp.value = value @property def current_temp(self): """Current temperature of the roast chamber as reported by hardware. Returns: (int) current temperature, in degrees Fahrenheit """ return self._current_temp.value @current_temp.setter def current_temp(self, value): if value not in range(150, 551): raise exceptions.RoasterValueError self._current_temp.value = value @property def time_remaining(self): """The amount of time, in seconds, remaining until a call to the state_transition_func is made. can be set to an arbitrary value up to 600 seconds at any time. When a new value is set, freshroastsr700 will count down from this new value down to 0. time_remaining is decremented to 0 only when in a roasting or cooling state. In other states, the value is not touched. Args: Setter: time_remaining (int): tiem remaining in seconds Returns: Getter: time_remaining(int): time remaining, in seconds """ return self._time_remaining.value @time_remaining.setter def time_remaining(self, value): self._time_remaining.value = value @property def total_time(self): """The total time this instance has been in roasting or cooling state sicne the latest roast began. Returns: total_time (int): time, in seconds """ return self._total_time.value @total_time.setter def total_time(self, value): self._total_time.value = value @property def heater_level(self): """A getter method for _heater_level. When thermostat=True, value is driven by built-in PID controller. When ext_sw_heater_drive=True, value is driven by calls to heater_level(). Min will always be zero, max will be heater_segments (optional instantiation parameter, defaults to 8).""" return self._heater_level.value @heater_level.setter def heater_level(self, value): """Verifies that the heater_level is between 0 and heater_segments. Can only be called when freshroastsr700 object is initialized with ext_sw_heater_drive=True. Will throw RoasterValueError otherwise.""" if self._ext_sw_heater_drive: if value not in range(0, self._heater_bangbang_segments+1): raise exceptions.RoasterValueError self._heater_level.value = value else: raise exceptions.RoasterValueError @property def connected(self): """A getter method for _connected. Indicates that the this software is currently communicating with FreshRoast SR700 hardware.""" return self._connected.value @property def connect_state(self): """A getter method for _connect_state. Indicates the current connection state this software is in for FreshRoast SR700 hardware. Returns: freshroastsr700.CS_NOT_CONNECTED the software is not currenting communicating with hardware, neither was it instructed to do so. A previously failed connection attempt will also result in this state. freshroastsr700.CS_ATTEMPTING_CONNECT A call to auto_connect() or connect() was made, and the software is currently attempting to connect to hardware. freshroastsr700.CS_CONNECTED The hardware was found, and the software is communicating with the hardware. """ return self._connect_state.value def set_state_transition_func(self, func): """THIS FUNCTION MUST BE CALLED BEFORE CALLING freshroastsr700.auto_connect(). Set, or re-set, the state transition function callback. The supplied function will be called from a separate thread within freshroastsr700, triggered by a separate, internal child process. This function will fail if the freshroastsr700 device is already connected to hardware, because by that time, the timer process and thread have already been spawned. Args: state_transition_func (func): the function to call for every state transition. A state transition occurs whenever the freshroastsr700's time_remaining value counts down to 0. Returns: nothing """ if self._connected.value: logging.error("freshroastsr700.set_state_transition_func must be " "called before freshroastsr700.auto_connect()." " Not registering func.") return False # no connection yet. so OK to set func pointer self._create_state_transition_system(func) return True def update_data_run(self, event_to_wait_on): """This is the thread that listens to an event from the comm process to execute the update_data_func callback in the context of the main process. """ # with the daemon=Turue setting, this thread should # quit 'automatically' while event_to_wait_on.wait(): event_to_wait_on.clear() if self.update_data_callback_kill_event.is_set(): return self.update_data_func() def state_transition_run(self, event_to_wait_on): """This is the thread that listens to an event from the timer process to execute the state_transition_func callback in the context of the main process. """ # with the daemon=Turue setting, this thread should # quit 'automatically' while event_to_wait_on.wait(): event_to_wait_on.clear() if self.state_transition_callback_kill_event.is_set(): return self.state_transition_func() def _connect(self): """Do not call this directly - call auto_connect() or connect(), which will call _connect() for you. Connects to the roaster and creates communication thread. Raises a RoasterLokkupError exception if the hardware is not found. """ # the following call raises a RoasterLookupException when the device # is not found. It is port = utils.find_device('1A86:5523') # on some systems, after the device port is added to the device list, # it can take up to 20 seconds after USB insertion for # the port to become available... (!) # let's put a safety timeout in here as a precaution wait_timeout = time.time() + 40.0 # should be PLENTY of time! # let's update the _connect_state while we're at it... self._connect_state.value = self.CS_CONNECTING connect_success = False while time.time() < wait_timeout: try: self._ser = serial.Serial( port=port, baudrate=9600, bytesize=8, parity='N', stopbits=1.5, timeout=0.25, xonxoff=False, rtscts=False, dsrdtr=False) connect_success = True break except serial.SerialException: time.sleep(0.5) if not connect_success: # timeout on attempts raise exceptions.RoasterLookupError self._initialize() def _initialize(self): """Sends the initialization packet to the roaster.""" self._header.value = b'\xAA\x55' self._current_state.value = b'\x00\x00' s = self._generate_packet() self._ser.write(s) self._header.value = b'\xAA\xAA' self._current_state.value = b'\x02\x01' return self._read_existing_recipe() def _write_to_device(self): success = False try: packet = self._generate_packet() logging.debug('WR: ' + str(binascii.hexlify(packet))) self._ser.write(packet) success = True except serial.serialutil.SerialException: logging.error('caught serial exception writing') return success def _read_from_device(self): r = [] footer_reached = False while len(r) < 14 and footer_reached is False: r.append(self._ser.read(1)) if len(r) >= 2 and b''.join(r)[-2:] == self._footer: footer_reached = True logging.debug('RD: ' + str(binascii.hexlify(b''.join(r)))) return b''.join(r) def _read_existing_recipe(self): existing_recipe = [] end_of_recipe = False while not end_of_recipe: bytes_waiting = self._ser.in_waiting if bytes_waiting < 14: # still need to write to device every .25sec it seems time.sleep(0.25) self._write_to_device() else: while (bytes_waiting // 14) > 0: r = self._read_from_device() bytes_waiting = self._ser.in_waiting if len(r) < 14: logging.warn('short packet length') else: existing_recipe.append(r) if r[4:5] == b'\xAF' or r[4:5] == b'\x00': end_of_recipe = True continue return existing_recipe def connect(self): """Attempt to connect to hardware immediately. Will not retry. Check freshroastsr700.connected or freshroastsr700.connect_state to verify result. Raises: freshroastsr700.exeptions.RoasterLookupError No hardware connected to the computer. """ self._start_connect(self.CA_SINGLE_SHOT) while(self._connect_state.value == self.CS_ATTEMPTING_CONNECT or self._connect_state.value == self.CS_CONNECTING): time.sleep(0.1) if self.CS_CONNECTED != self._connect_state.value: raise exceptions.RoasterLookupError def auto_connect(self): """Starts a thread that will automatically connect to the roaster when it is plugged in.""" self._start_connect(self.CA_AUTO) def _start_connect(self, connect_type): """Starts the connection process, as called (internally) from the user context, either from auto_connect() or connect(). Never call this from the _comm() process context. """ if self._connect_state.value != self.CS_NOT_CONNECTED: # already done or in process, assume success return self._connected.value = 0 self._connect_state.value = self.CS_ATTEMPTING_CONNECT # tell comm process to attempt connection self._attempting_connect.value = connect_type # EXTREMELY IMPORTANT - for this to work at all in Windows, # where the above processes are spawned (vs forked in Unix), # the thread objects (as sattributes of this object) must be # assigned to this object AFTER we have spawned the processes. # That way, multiprocessing can pickle the freshroastsr700 # successfully. (It can't pickle thread-related stuff.) if self.update_data_func is not None: # Need to launch the thread that will listen to the event self._create_update_data_system( None, setFunc=False, createThread=True) self.update_data_thread.start() if self.state_transition_func is not None: # Need to launch the thread that will listen to the event self._create_state_transition_system( None, setFunc=False, createThread=True) self.state_transition_thread.start() def _auto_connect(self): """Attempts to connect to the roaster every quarter of a second.""" while not self._teardown.value: try: self._connect() return True except exceptions.RoasterLookupError: time.sleep(.25) return False def disconnect(self): """Stops the communication loop to the roaster. Note that this will not actually stop the roaster itself.""" self._disconnect.value = 1 def terminate(self): """Stops the communication loop to the roaster and closes down all communication processes. Note that this will not actually stop the roaster itself. You will need to instantiate a new freshroastsr700 object after calling this function, in order to re-start communications with the hardware. """ self.disconnect() self._teardown.value = 1 # print("We are disconnected.") def _process_reponse_byte(self, read_state, _byte, r, update_data_event): err = False if self.LOOKING_FOR_HEADER_1 == read_state: if b'\xAA' == _byte: read_state = self.LOOKING_FOR_HEADER_2 elif self.LOOKING_FOR_HEADER_2 == read_state: if b'\xAA' == _byte: read_state = self.PACKET_DATA # reset packet array now... r = [] else: read_state = self.LOOKING_FOR_HEADER_1 elif self.PACKET_DATA == read_state: if b'\xAA' == _byte: # this could be the start of an end of packet marker read_state = self.LOOKING_FOR_FOOTER_2 else: r.append(_byte) # SR700 FW bug - if current temp is 250 degF (0xFA), # the FW does not transmit the footer at all. # fake the footer here. if(len(r) == 10 and b'\xFA' == _byte): # we will 'fake' a footer to make this decoder work # as intended read_state, r, _ = ( self._process_reponse_byte( read_state, b'\xAA', r, update_data_event)) read_state, r, err = ( self._process_reponse_byte( read_state, b'\xFA', r, update_data_event)) elif self.LOOKING_FOR_FOOTER_2 == read_state: if b'\xFA' == _byte: # OK we have a full packet - PROCESS PACKET err = self._process_response_data(r, update_data_event) read_state = self.LOOKING_FOR_HEADER_1 else: # the last byte was not the beginning of the footer r.append(b'\xAA') read_state = self.PACKET_DATA read_state, r, err = self._process_reponse_byte( read_state, _byte, r, update_data_event) else: # error state, shouldn't happen... logging.error('_process_reponse_byte - invalid read_state %d' % read_state) read_state = self.LOOKING_FOR_HEADER_1 err = True return read_state, r, err def _process_response_data(self, r, update_data_event): err = False if len(r) != 10: logging.warn('read packet data len not 10, got: %d' % len(r)) logging.warn('RD: ' + str(binascii.hexlify(b''.join(r)))) err = True else: temp = struct.unpack(">H", b''.join(r[8:10]))[0] if(temp == 65280): self.current_temp = 150 elif(temp > 550 or temp < 150): logging.warn('temperature out of range: reinitializing...') self._initialize() err = True return else: self.current_temp = temp if(update_data_event is not None): update_data_event.set() return err def _timer(self, state_transition_event=None): """Timer loop used to keep track of the time while roasting or cooling. If the time remaining reaches zero, the roaster will call the supplied state transistion function or the roaster will be set to the idle state.""" while not self._teardown.value: state = self.get_roaster_state() if(state == 'roasting' or state == 'cooling'): time.sleep(1) self.total_time += 1 if(self.time_remaining > 0): self.time_remaining -= 1 else: if(state_transition_event is not None): state_transition_event.set() else: self.idle() else: time.sleep(0.01) def get_roaster_state(self): """Returns a string based upon the current state of the roaster. Will raise an exception if the state is unknown. Returns: 'idle' if idle, 'sleeping' if sleeping, 'cooling' if cooling, 'roasting' if roasting, 'connecting' if in hardware connection phase, 'unknown' otherwise """ value = self._current_state.value if(value == b'\x02\x01'): return 'idle' elif(value == b'\x04\x04'): return 'cooling' elif(value == b'\x08\x01'): return 'sleeping' # handle null bytes as empty strings elif(value == b'\x00\x00' or value == b''): return 'connecting' elif(value == b'\x04\x02'): return 'roasting' else: return 'unknown' def _generate_packet(self): """Generates a packet based upon the current class variables. Note that current temperature is not sent, as the original application sent zeros to the roaster for the current temperature.""" roaster_time = utils.seconds_to_float(self._time_remaining.value) packet = ( self._header.value + self._temp_unit.value + self._flags.value + self._current_state.value + struct.pack(">B", self._fan_speed.value) + struct.pack(">B", int(round(roaster_time * 10.0))) + struct.pack(">B", self._heat_setting.value) + b'\x00\x00' + self._footer) return packet def idle(self): """Sets the current state of the roaster to idle.""" self._current_state.value = b'\x02\x01' def roast(self): """Sets the current state of the roaster to roast and begins roasting.""" self._current_state.value = b'\x04\x02' def cool(self): """Sets the current state of the roaster to cool. The roaster expects that cool will be run after roast, and will not work as expected if ran before.""" self._current_state.value = b'\x04\x04' def sleep(self): """Sets the current state of the roaster to sleep. Different than idle in that this will set double dashes on the roaster display rather than digits.""" self._current_state.value = b'\x08\x01'
Roastero/freshroastsr700
freshroastsr700/__init__.py
freshroastsr700._timer
python
def _timer(self, state_transition_event=None): while not self._teardown.value: state = self.get_roaster_state() if(state == 'roasting' or state == 'cooling'): time.sleep(1) self.total_time += 1 if(self.time_remaining > 0): self.time_remaining -= 1 else: if(state_transition_event is not None): state_transition_event.set() else: self.idle() else: time.sleep(0.01)
Timer loop used to keep track of the time while roasting or cooling. If the time remaining reaches zero, the roaster will call the supplied state transistion function or the roaster will be set to the idle state.
train
https://github.com/Roastero/freshroastsr700/blob/49cf4961444c0f56d051d5ac5088ace480b54f02/freshroastsr700/__init__.py#L889-L907
null
class freshroastsr700(object): """A class to interface with a freshroastsr700 coffee roaster. Args: update_data_func (func): A function to call when this object receives new data from the hardware. Defaults to None. state_transition_func (func): A function to call when time_remaining counts down to 0 and the device is either in roasting or cooling state. Defaults to None. thermostat (bool): thermostat mode. if set to True, turns on thermostat mode. In thermostat mode, freshroastsr700 takes control of heat_setting and does software PID control to hit the demanded target_temp. Defaults to False. ext_sw_heater_drive (bool): enable direct control over the internal heat_controller object. Defaults to False. When set to True, the thermostat field is IGNORED, and assumed to be False. Direct control over the software heater_level means that the freshroastsr700's PID controller cannot control the heater. Since thermostat and ext_sw_heater_drive cannot be allowed to both be True, this arg is given precedence over the thermostat arg. Note that (thermostat=False, ext_sw_heater_drive=False), (thermostat=True, ext_sw_heater_drive=False), (thermostat=False, ext_sw_heater_drive=True), are all acceptable arg combinations. Only the (thermostat=True, ext_sw_heater_drive=True), cominbation is not allowed, and this software will set thermostat=False in that case. kp (float): Kp value to use for PID control. Defaults to 0.06. ki (float): Ki value to use for PID control. Defaults to 0.0075. kd (float): Kd value to use for PID control. Defaults to 0.01. heater_segments (int): the pseudo-control range for the internal heat_controller object. Defaults to 8. """ def __init__(self, update_data_func=None, state_transition_func=None, thermostat=False, kp=0.06, ki=0.0075, kd=0.01, heater_segments=8, ext_sw_heater_drive=False): """Create variables used to send in packets to the roaster. The update data function is called when a packet is opened. The state transistion function is used by the timer thread to know what to do next. See wiki for more information on packet structure and fields.""" # constants for protocol decoding self.LOOKING_FOR_HEADER_1 = 0 self.LOOKING_FOR_HEADER_2 = 1 self.PACKET_DATA = 2 self.LOOKING_FOR_FOOTER_2 = 3 # constants for connection state monitoring self.CS_NOT_CONNECTED = -2 self.CS_ATTEMPTING_CONNECT = -1 self.CS_CONNECTING = 0 self.CS_CONNECTED = 1 # constants for connection attempt type self.CA_NONE = 0 self.CA_AUTO = 1 self.CA_SINGLE_SHOT = 2 self._create_update_data_system(update_data_func) self._create_state_transition_system(state_transition_func) self._header = sharedctypes.Array('c', b'\xAA\xAA') self._temp_unit = sharedctypes.Array('c', b'\x61\x74') self._flags = sharedctypes.Array('c', b'\x63') self._current_state = sharedctypes.Array('c', b'\x02\x01') self._footer = b'\xAA\xFA' self._fan_speed = sharedctypes.Value('i', 1) self._heat_setting = sharedctypes.Value('i', 0) self._target_temp = sharedctypes.Value('i', 150) self._current_temp = sharedctypes.Value('i', 150) self._time_remaining = sharedctypes.Value('i', 0) self._total_time = sharedctypes.Value('i', 0) self._disconnect = sharedctypes.Value('i', 0) self._teardown = sharedctypes.Value('i', 0) # for SW PWM heater setting self._heater_level = sharedctypes.Value('i', 0) # the following vars are not process-safe, do not access them # from the comm or timer threads, nor from the callbacks. self._ext_sw_heater_drive = ext_sw_heater_drive if not self._ext_sw_heater_drive: self._thermostat = thermostat else: self._thermostat = False self._pid_kp = kp self._pid_ki = ki self._pid_kd = kd self._heater_bangbang_segments = heater_segments # initialize to 'not connected' self._connected = sharedctypes.Value('i', 0) self._connect_state = sharedctypes.Value('i', self.CS_NOT_CONNECTED) # initialize to 'not trying to connect' self._attempting_connect = sharedctypes.Value('i', self.CA_NONE) # create comm process self.comm_process = mp.Process( target=self._comm, args=( self._thermostat, self._pid_kp, self._pid_ki, self._pid_kd, self._heater_bangbang_segments, self._ext_sw_heater_drive, self.update_data_event,)) self.comm_process.daemon = True self.comm_process.start() # create timer process that counts down time_remaining self.time_process = mp.Process( target=self._timer, args=( self.state_transition_event,)) self.time_process.daemon = True self.time_process.start() def _create_update_data_system( self, update_data_func, setFunc=True, createThread=False): # these callbacks cannot be called from another process in Windows. # Therefore, spawn a thread belonging to the calling process # instead. # the comm and timer processes will set events that the threads # will listen for to initiate the callbacks # only create the mp.Event once - # to mimic create_state_transition_system, for future-proofing # (in this case, currently, this is only called at __init__() time) if not hasattr(self, 'update_data_event'): self.update_data_event = mp.Event() # only create the thread.Event once - this is used to exit # the callback thread if not hasattr(self, 'update_data_callback_kill_event'): self.update_data_callback_kill_event = mp.Event() # destroy an existing thread if we had created one previously if(hasattr(self, 'update_data_thread') and self.update_data_thread is not None): # let's tear this down. To kill it, two events must be set... # in the right sequence! self.update_data_callback_kill_event.set() self.update_data_event.set() self.update_data_thread.join() if setFunc: self.update_data_func = update_data_func if self.update_data_func is not None: if createThread: self.update_data_callback_kill_event.clear() self.update_data_thread = threading.Thread( name='sr700_update_data', target=self.update_data_run, args=(self.update_data_event,), daemon=True ) else: self.update_data_thread = None def _create_state_transition_system( self, state_transition_func, setFunc=True, createThread=False): # these callbacks cannot be called from another process in Windows. # Therefore, spawn a thread belonging to the calling process # instead. # the comm and timer processes will set events that the threads # will listen for to initiate the callbacks # only create the mp.Event once - this fn can get called more # than once, by __init__() and by set_state_transition_func() if not hasattr(self, 'state_transition_event'): self.state_transition_event = mp.Event() # only create the thread.Event once - this is used to exit # the callback thread if not hasattr(self, 'state_transition_callback_kill_event'): self.state_transition_callback_kill_event = mp.Event() # destroy an existing thread if we had created one previously if(hasattr(self, 'state_transition_thread') and self.state_transition_thread is not None): # let's tear this down. To kill it, two events must be set... # in the right sequence! self.state_transition_callback_kill_event.set() self.state_transition_event.set() self.state_transition_thread.join() if setFunc: self.state_transition_func = state_transition_func if self.state_transition_func is not None: if createThread: self.state_transition_callback_kill_event.clear() self.state_transition_thread = threading.Thread( name='sr700_state_transition', target=self.state_transition_run, args=(self.state_transition_event,), daemon=True ) else: self.state_transition_thread = None @property def fan_speed(self): """Get/Set fan speed. Can be 1 to 9 inclusive. Args: Setter: fan_speed (int): fan speed Returns: Getter: (int): fan speed """ return self._fan_speed.value @fan_speed.setter def fan_speed(self, value): """Verifies the value is between 1 and 9 inclusively.""" if value not in range(1, 10): raise exceptions.RoasterValueError self._fan_speed.value = value @property def heat_setting(self): """Get/Set heat setting, 0 to 3 inclusive. 0=off, 3=high. Do not set when running freshroastsr700 in thermostat mode. Args: Setter: heat_setting (int): heat setting Returns: Getter: (int): heat setting """ return self._heat_setting.value @heat_setting.setter def heat_setting(self, value): """Verifies that the heat setting is between 0 and 3.""" if value not in range(0, 4): raise exceptions.RoasterValueError self._heat_setting.value = value @property def target_temp(self): """Get/Set the target temperature for this package's built-in software PID controler. Only used when freshroastsr700 is instantiated with thermostat=True. Args: Setter: value (int): a target temperature in degF between 150 and 551. Returns: Getter: (int) target temperature in degF between 150 and 551 """ return self._target_temp.value @target_temp.setter def target_temp(self, value): if value not in range(150, 551): raise exceptions.RoasterValueError self._target_temp.value = value @property def current_temp(self): """Current temperature of the roast chamber as reported by hardware. Returns: (int) current temperature, in degrees Fahrenheit """ return self._current_temp.value @current_temp.setter def current_temp(self, value): if value not in range(150, 551): raise exceptions.RoasterValueError self._current_temp.value = value @property def time_remaining(self): """The amount of time, in seconds, remaining until a call to the state_transition_func is made. can be set to an arbitrary value up to 600 seconds at any time. When a new value is set, freshroastsr700 will count down from this new value down to 0. time_remaining is decremented to 0 only when in a roasting or cooling state. In other states, the value is not touched. Args: Setter: time_remaining (int): tiem remaining in seconds Returns: Getter: time_remaining(int): time remaining, in seconds """ return self._time_remaining.value @time_remaining.setter def time_remaining(self, value): self._time_remaining.value = value @property def total_time(self): """The total time this instance has been in roasting or cooling state sicne the latest roast began. Returns: total_time (int): time, in seconds """ return self._total_time.value @total_time.setter def total_time(self, value): self._total_time.value = value @property def heater_level(self): """A getter method for _heater_level. When thermostat=True, value is driven by built-in PID controller. When ext_sw_heater_drive=True, value is driven by calls to heater_level(). Min will always be zero, max will be heater_segments (optional instantiation parameter, defaults to 8).""" return self._heater_level.value @heater_level.setter def heater_level(self, value): """Verifies that the heater_level is between 0 and heater_segments. Can only be called when freshroastsr700 object is initialized with ext_sw_heater_drive=True. Will throw RoasterValueError otherwise.""" if self._ext_sw_heater_drive: if value not in range(0, self._heater_bangbang_segments+1): raise exceptions.RoasterValueError self._heater_level.value = value else: raise exceptions.RoasterValueError @property def connected(self): """A getter method for _connected. Indicates that the this software is currently communicating with FreshRoast SR700 hardware.""" return self._connected.value @property def connect_state(self): """A getter method for _connect_state. Indicates the current connection state this software is in for FreshRoast SR700 hardware. Returns: freshroastsr700.CS_NOT_CONNECTED the software is not currenting communicating with hardware, neither was it instructed to do so. A previously failed connection attempt will also result in this state. freshroastsr700.CS_ATTEMPTING_CONNECT A call to auto_connect() or connect() was made, and the software is currently attempting to connect to hardware. freshroastsr700.CS_CONNECTED The hardware was found, and the software is communicating with the hardware. """ return self._connect_state.value def set_state_transition_func(self, func): """THIS FUNCTION MUST BE CALLED BEFORE CALLING freshroastsr700.auto_connect(). Set, or re-set, the state transition function callback. The supplied function will be called from a separate thread within freshroastsr700, triggered by a separate, internal child process. This function will fail if the freshroastsr700 device is already connected to hardware, because by that time, the timer process and thread have already been spawned. Args: state_transition_func (func): the function to call for every state transition. A state transition occurs whenever the freshroastsr700's time_remaining value counts down to 0. Returns: nothing """ if self._connected.value: logging.error("freshroastsr700.set_state_transition_func must be " "called before freshroastsr700.auto_connect()." " Not registering func.") return False # no connection yet. so OK to set func pointer self._create_state_transition_system(func) return True def update_data_run(self, event_to_wait_on): """This is the thread that listens to an event from the comm process to execute the update_data_func callback in the context of the main process. """ # with the daemon=Turue setting, this thread should # quit 'automatically' while event_to_wait_on.wait(): event_to_wait_on.clear() if self.update_data_callback_kill_event.is_set(): return self.update_data_func() def state_transition_run(self, event_to_wait_on): """This is the thread that listens to an event from the timer process to execute the state_transition_func callback in the context of the main process. """ # with the daemon=Turue setting, this thread should # quit 'automatically' while event_to_wait_on.wait(): event_to_wait_on.clear() if self.state_transition_callback_kill_event.is_set(): return self.state_transition_func() def _connect(self): """Do not call this directly - call auto_connect() or connect(), which will call _connect() for you. Connects to the roaster and creates communication thread. Raises a RoasterLokkupError exception if the hardware is not found. """ # the following call raises a RoasterLookupException when the device # is not found. It is port = utils.find_device('1A86:5523') # on some systems, after the device port is added to the device list, # it can take up to 20 seconds after USB insertion for # the port to become available... (!) # let's put a safety timeout in here as a precaution wait_timeout = time.time() + 40.0 # should be PLENTY of time! # let's update the _connect_state while we're at it... self._connect_state.value = self.CS_CONNECTING connect_success = False while time.time() < wait_timeout: try: self._ser = serial.Serial( port=port, baudrate=9600, bytesize=8, parity='N', stopbits=1.5, timeout=0.25, xonxoff=False, rtscts=False, dsrdtr=False) connect_success = True break except serial.SerialException: time.sleep(0.5) if not connect_success: # timeout on attempts raise exceptions.RoasterLookupError self._initialize() def _initialize(self): """Sends the initialization packet to the roaster.""" self._header.value = b'\xAA\x55' self._current_state.value = b'\x00\x00' s = self._generate_packet() self._ser.write(s) self._header.value = b'\xAA\xAA' self._current_state.value = b'\x02\x01' return self._read_existing_recipe() def _write_to_device(self): success = False try: packet = self._generate_packet() logging.debug('WR: ' + str(binascii.hexlify(packet))) self._ser.write(packet) success = True except serial.serialutil.SerialException: logging.error('caught serial exception writing') return success def _read_from_device(self): r = [] footer_reached = False while len(r) < 14 and footer_reached is False: r.append(self._ser.read(1)) if len(r) >= 2 and b''.join(r)[-2:] == self._footer: footer_reached = True logging.debug('RD: ' + str(binascii.hexlify(b''.join(r)))) return b''.join(r) def _read_existing_recipe(self): existing_recipe = [] end_of_recipe = False while not end_of_recipe: bytes_waiting = self._ser.in_waiting if bytes_waiting < 14: # still need to write to device every .25sec it seems time.sleep(0.25) self._write_to_device() else: while (bytes_waiting // 14) > 0: r = self._read_from_device() bytes_waiting = self._ser.in_waiting if len(r) < 14: logging.warn('short packet length') else: existing_recipe.append(r) if r[4:5] == b'\xAF' or r[4:5] == b'\x00': end_of_recipe = True continue return existing_recipe def connect(self): """Attempt to connect to hardware immediately. Will not retry. Check freshroastsr700.connected or freshroastsr700.connect_state to verify result. Raises: freshroastsr700.exeptions.RoasterLookupError No hardware connected to the computer. """ self._start_connect(self.CA_SINGLE_SHOT) while(self._connect_state.value == self.CS_ATTEMPTING_CONNECT or self._connect_state.value == self.CS_CONNECTING): time.sleep(0.1) if self.CS_CONNECTED != self._connect_state.value: raise exceptions.RoasterLookupError def auto_connect(self): """Starts a thread that will automatically connect to the roaster when it is plugged in.""" self._start_connect(self.CA_AUTO) def _start_connect(self, connect_type): """Starts the connection process, as called (internally) from the user context, either from auto_connect() or connect(). Never call this from the _comm() process context. """ if self._connect_state.value != self.CS_NOT_CONNECTED: # already done or in process, assume success return self._connected.value = 0 self._connect_state.value = self.CS_ATTEMPTING_CONNECT # tell comm process to attempt connection self._attempting_connect.value = connect_type # EXTREMELY IMPORTANT - for this to work at all in Windows, # where the above processes are spawned (vs forked in Unix), # the thread objects (as sattributes of this object) must be # assigned to this object AFTER we have spawned the processes. # That way, multiprocessing can pickle the freshroastsr700 # successfully. (It can't pickle thread-related stuff.) if self.update_data_func is not None: # Need to launch the thread that will listen to the event self._create_update_data_system( None, setFunc=False, createThread=True) self.update_data_thread.start() if self.state_transition_func is not None: # Need to launch the thread that will listen to the event self._create_state_transition_system( None, setFunc=False, createThread=True) self.state_transition_thread.start() def _auto_connect(self): """Attempts to connect to the roaster every quarter of a second.""" while not self._teardown.value: try: self._connect() return True except exceptions.RoasterLookupError: time.sleep(.25) return False def disconnect(self): """Stops the communication loop to the roaster. Note that this will not actually stop the roaster itself.""" self._disconnect.value = 1 def terminate(self): """Stops the communication loop to the roaster and closes down all communication processes. Note that this will not actually stop the roaster itself. You will need to instantiate a new freshroastsr700 object after calling this function, in order to re-start communications with the hardware. """ self.disconnect() self._teardown.value = 1 def _comm(self, thermostat=False, kp=0.06, ki=0.0075, kd=0.01, heater_segments=8, ext_sw_heater_drive=False, update_data_event=None): """Do not call this directly - call auto_connect(), which will spawn comm() for you. This is the main communications loop to the roaster. whenever a valid packet is received from the device, if an update_data_event is available, it will be signalled. Args: thermostat (bool): thermostat mode. if set to True, turns on thermostat mode. In thermostat mode, freshroastsr700 takes control of heat_setting and does software PID control to hit the demanded target_temp. ext_sw_heater_drive (bool): enable direct control over the internal heat_controller object. Defaults to False. When set to True, the thermostat field is IGNORED, and assumed to be False. Direct control over the software heater_level means that the PID controller cannot control the heater. Since thermostat and ext_sw_heater_drive cannot be allowed to both be True, this arg is given precedence over the thermostat arg. kp (float): Kp value to use for PID control. Defaults to 0.06. ki (float): Ki value to use for PID control. Defaults to 0.0075. kd (float): Kd value to use for PID control. Defaults to 0.01. heater_segments (int): the pseudo-control range for the internal heat_controller object. Defaults to 8. update_data_event (multiprocessing.Event): If set, allows the comm_process to signal to the parent process that new device data is available. Returns: nothing """ # since this process is started with daemon=True, it should exit # when the owning process terminates. Therefore, safe to loop forever. while not self._teardown.value: # waiting for command to attempt connect # print( "waiting for command to attempt connect") while self._attempting_connect.value == self.CA_NONE: time.sleep(0.25) if self._teardown.value: break # if we're tearing down, bail now. if self._teardown.value: break # we got the command to attempt to connect # change state to 'attempting_connect' self._connect_state.value = self.CS_ATTEMPTING_CONNECT # attempt connection if self.CA_AUTO == self._attempting_connect.value: # this call will block until a connection is achieved # it will also set _connect_state to CS_CONNECTING # if appropriate if self._auto_connect(): # when we unblock, it is an indication of a successful # connection self._connected.value = 1 self._connect_state.value = self.CS_CONNECTED else: # failure, normally due to a timeout self._connected.value = 0 self._connect_state.value = self.CS_NOT_CONNECTED # we failed to connect - start over from the top # reset flag self._attempting_connect.value = self.CA_NONE continue elif self.CA_SINGLE_SHOT == self._attempting_connect.value: # try once, now, if failure, start teh big loop over try: self._connect() self._connected.value = 1 self._connect_state.value = self.CS_CONNECTED except exceptions.RoasterLookupError: self._connected.value = 0 self._connect_state.value = self.CS_NOT_CONNECTED if self._connect_state.value != self.CS_CONNECTED: # we failed to connect - start over from the top # reset flag self._attempting_connect.value = self.CA_NONE continue else: # shouldn't be here # reset flag self._attempting_connect.value = self.CA_NONE continue # We are connected! # print( "We are connected!") # reset flag right away self._attempting_connect.value = self.CA_NONE # Initialize PID controller if thermostat function was specified at # init time pidc = None heater = None if(thermostat): pidc = pid.PID(kp, ki, kd, Output_max=heater_segments, Output_min=0 ) if thermostat or ext_sw_heater_drive: heater = heat_controller(number_of_segments=heater_segments) read_state = self.LOOKING_FOR_HEADER_1 r = [] write_errors = 0 read_errors = 0 while not self._disconnect.value: start = datetime.datetime.now() # write to device if not self._write_to_device(): logging.error('comm - _write_to_device() failed!') write_errors += 1 if write_errors > 3: # it's time to consider the device as being "gone" logging.error('comm - 3 successive write ' 'failures, disconnecting.') self._disconnect.value = 1 continue else: # reset write_errors write_errors = 0 # read from device try: while self._ser.in_waiting: _byte = self._ser.read(1) read_state, r, err = ( self._process_reponse_byte( read_state, _byte, r, update_data_event)) except IOError: # typically happens when device is suddenly unplugged logging.error('comm - read from device failed!') read_errors += 1 if write_errors > 3: # it's time to consider the device as being "gone" logging.error('comm - 3 successive read ' 'failures, disconnecting.') self._disconnect.value = 1 continue else: read_errors = 0 # next, drive SW heater when using # thermostat mode (PID controller calcs) # or in external sw heater drive mode, # when roasting. if thermostat or ext_sw_heater_drive: if 'roasting' == self.get_roaster_state(): if heater.about_to_rollover(): # it's time to use the PID controller value # and set new output level on heater! if ext_sw_heater_drive: # read user-supplied value heater.heat_level = self._heater_level.value else: # thermostat output = pidc.update( self.current_temp, self.target_temp) heater.heat_level = output # make this number visible to other processes... self._heater_level.value = heater.heat_level # read bang-bang heater output array element & apply it if heater.generate_bangbang_output(): # ON self.heat_setting = 3 else: # OFF self.heat_setting = 0 else: # for all other states, heat_level = OFF heater.heat_level = 0 # make this number visible to other processes... self._heater_level.value = heater.heat_level self.heat_setting = 0 # calculate sleep time to stick to 0.25sec period comp_time = datetime.datetime.now() - start sleep_duration = 0.25 - comp_time.total_seconds() if sleep_duration > 0: time.sleep(sleep_duration) self._ser.close() # reset disconnect flag self._disconnect.value = 0 # reset connection values self._connected.value = 0 self._connect_state.value = self.CS_NOT_CONNECTED # print("We are disconnected.") def _process_reponse_byte(self, read_state, _byte, r, update_data_event): err = False if self.LOOKING_FOR_HEADER_1 == read_state: if b'\xAA' == _byte: read_state = self.LOOKING_FOR_HEADER_2 elif self.LOOKING_FOR_HEADER_2 == read_state: if b'\xAA' == _byte: read_state = self.PACKET_DATA # reset packet array now... r = [] else: read_state = self.LOOKING_FOR_HEADER_1 elif self.PACKET_DATA == read_state: if b'\xAA' == _byte: # this could be the start of an end of packet marker read_state = self.LOOKING_FOR_FOOTER_2 else: r.append(_byte) # SR700 FW bug - if current temp is 250 degF (0xFA), # the FW does not transmit the footer at all. # fake the footer here. if(len(r) == 10 and b'\xFA' == _byte): # we will 'fake' a footer to make this decoder work # as intended read_state, r, _ = ( self._process_reponse_byte( read_state, b'\xAA', r, update_data_event)) read_state, r, err = ( self._process_reponse_byte( read_state, b'\xFA', r, update_data_event)) elif self.LOOKING_FOR_FOOTER_2 == read_state: if b'\xFA' == _byte: # OK we have a full packet - PROCESS PACKET err = self._process_response_data(r, update_data_event) read_state = self.LOOKING_FOR_HEADER_1 else: # the last byte was not the beginning of the footer r.append(b'\xAA') read_state = self.PACKET_DATA read_state, r, err = self._process_reponse_byte( read_state, _byte, r, update_data_event) else: # error state, shouldn't happen... logging.error('_process_reponse_byte - invalid read_state %d' % read_state) read_state = self.LOOKING_FOR_HEADER_1 err = True return read_state, r, err def _process_response_data(self, r, update_data_event): err = False if len(r) != 10: logging.warn('read packet data len not 10, got: %d' % len(r)) logging.warn('RD: ' + str(binascii.hexlify(b''.join(r)))) err = True else: temp = struct.unpack(">H", b''.join(r[8:10]))[0] if(temp == 65280): self.current_temp = 150 elif(temp > 550 or temp < 150): logging.warn('temperature out of range: reinitializing...') self._initialize() err = True return else: self.current_temp = temp if(update_data_event is not None): update_data_event.set() return err def get_roaster_state(self): """Returns a string based upon the current state of the roaster. Will raise an exception if the state is unknown. Returns: 'idle' if idle, 'sleeping' if sleeping, 'cooling' if cooling, 'roasting' if roasting, 'connecting' if in hardware connection phase, 'unknown' otherwise """ value = self._current_state.value if(value == b'\x02\x01'): return 'idle' elif(value == b'\x04\x04'): return 'cooling' elif(value == b'\x08\x01'): return 'sleeping' # handle null bytes as empty strings elif(value == b'\x00\x00' or value == b''): return 'connecting' elif(value == b'\x04\x02'): return 'roasting' else: return 'unknown' def _generate_packet(self): """Generates a packet based upon the current class variables. Note that current temperature is not sent, as the original application sent zeros to the roaster for the current temperature.""" roaster_time = utils.seconds_to_float(self._time_remaining.value) packet = ( self._header.value + self._temp_unit.value + self._flags.value + self._current_state.value + struct.pack(">B", self._fan_speed.value) + struct.pack(">B", int(round(roaster_time * 10.0))) + struct.pack(">B", self._heat_setting.value) + b'\x00\x00' + self._footer) return packet def idle(self): """Sets the current state of the roaster to idle.""" self._current_state.value = b'\x02\x01' def roast(self): """Sets the current state of the roaster to roast and begins roasting.""" self._current_state.value = b'\x04\x02' def cool(self): """Sets the current state of the roaster to cool. The roaster expects that cool will be run after roast, and will not work as expected if ran before.""" self._current_state.value = b'\x04\x04' def sleep(self): """Sets the current state of the roaster to sleep. Different than idle in that this will set double dashes on the roaster display rather than digits.""" self._current_state.value = b'\x08\x01'
Roastero/freshroastsr700
freshroastsr700/__init__.py
freshroastsr700.get_roaster_state
python
def get_roaster_state(self): value = self._current_state.value if(value == b'\x02\x01'): return 'idle' elif(value == b'\x04\x04'): return 'cooling' elif(value == b'\x08\x01'): return 'sleeping' # handle null bytes as empty strings elif(value == b'\x00\x00' or value == b''): return 'connecting' elif(value == b'\x04\x02'): return 'roasting' else: return 'unknown'
Returns a string based upon the current state of the roaster. Will raise an exception if the state is unknown. Returns: 'idle' if idle, 'sleeping' if sleeping, 'cooling' if cooling, 'roasting' if roasting, 'connecting' if in hardware connection phase, 'unknown' otherwise
train
https://github.com/Roastero/freshroastsr700/blob/49cf4961444c0f56d051d5ac5088ace480b54f02/freshroastsr700/__init__.py#L909-L934
null
class freshroastsr700(object): """A class to interface with a freshroastsr700 coffee roaster. Args: update_data_func (func): A function to call when this object receives new data from the hardware. Defaults to None. state_transition_func (func): A function to call when time_remaining counts down to 0 and the device is either in roasting or cooling state. Defaults to None. thermostat (bool): thermostat mode. if set to True, turns on thermostat mode. In thermostat mode, freshroastsr700 takes control of heat_setting and does software PID control to hit the demanded target_temp. Defaults to False. ext_sw_heater_drive (bool): enable direct control over the internal heat_controller object. Defaults to False. When set to True, the thermostat field is IGNORED, and assumed to be False. Direct control over the software heater_level means that the freshroastsr700's PID controller cannot control the heater. Since thermostat and ext_sw_heater_drive cannot be allowed to both be True, this arg is given precedence over the thermostat arg. Note that (thermostat=False, ext_sw_heater_drive=False), (thermostat=True, ext_sw_heater_drive=False), (thermostat=False, ext_sw_heater_drive=True), are all acceptable arg combinations. Only the (thermostat=True, ext_sw_heater_drive=True), cominbation is not allowed, and this software will set thermostat=False in that case. kp (float): Kp value to use for PID control. Defaults to 0.06. ki (float): Ki value to use for PID control. Defaults to 0.0075. kd (float): Kd value to use for PID control. Defaults to 0.01. heater_segments (int): the pseudo-control range for the internal heat_controller object. Defaults to 8. """ def __init__(self, update_data_func=None, state_transition_func=None, thermostat=False, kp=0.06, ki=0.0075, kd=0.01, heater_segments=8, ext_sw_heater_drive=False): """Create variables used to send in packets to the roaster. The update data function is called when a packet is opened. The state transistion function is used by the timer thread to know what to do next. See wiki for more information on packet structure and fields.""" # constants for protocol decoding self.LOOKING_FOR_HEADER_1 = 0 self.LOOKING_FOR_HEADER_2 = 1 self.PACKET_DATA = 2 self.LOOKING_FOR_FOOTER_2 = 3 # constants for connection state monitoring self.CS_NOT_CONNECTED = -2 self.CS_ATTEMPTING_CONNECT = -1 self.CS_CONNECTING = 0 self.CS_CONNECTED = 1 # constants for connection attempt type self.CA_NONE = 0 self.CA_AUTO = 1 self.CA_SINGLE_SHOT = 2 self._create_update_data_system(update_data_func) self._create_state_transition_system(state_transition_func) self._header = sharedctypes.Array('c', b'\xAA\xAA') self._temp_unit = sharedctypes.Array('c', b'\x61\x74') self._flags = sharedctypes.Array('c', b'\x63') self._current_state = sharedctypes.Array('c', b'\x02\x01') self._footer = b'\xAA\xFA' self._fan_speed = sharedctypes.Value('i', 1) self._heat_setting = sharedctypes.Value('i', 0) self._target_temp = sharedctypes.Value('i', 150) self._current_temp = sharedctypes.Value('i', 150) self._time_remaining = sharedctypes.Value('i', 0) self._total_time = sharedctypes.Value('i', 0) self._disconnect = sharedctypes.Value('i', 0) self._teardown = sharedctypes.Value('i', 0) # for SW PWM heater setting self._heater_level = sharedctypes.Value('i', 0) # the following vars are not process-safe, do not access them # from the comm or timer threads, nor from the callbacks. self._ext_sw_heater_drive = ext_sw_heater_drive if not self._ext_sw_heater_drive: self._thermostat = thermostat else: self._thermostat = False self._pid_kp = kp self._pid_ki = ki self._pid_kd = kd self._heater_bangbang_segments = heater_segments # initialize to 'not connected' self._connected = sharedctypes.Value('i', 0) self._connect_state = sharedctypes.Value('i', self.CS_NOT_CONNECTED) # initialize to 'not trying to connect' self._attempting_connect = sharedctypes.Value('i', self.CA_NONE) # create comm process self.comm_process = mp.Process( target=self._comm, args=( self._thermostat, self._pid_kp, self._pid_ki, self._pid_kd, self._heater_bangbang_segments, self._ext_sw_heater_drive, self.update_data_event,)) self.comm_process.daemon = True self.comm_process.start() # create timer process that counts down time_remaining self.time_process = mp.Process( target=self._timer, args=( self.state_transition_event,)) self.time_process.daemon = True self.time_process.start() def _create_update_data_system( self, update_data_func, setFunc=True, createThread=False): # these callbacks cannot be called from another process in Windows. # Therefore, spawn a thread belonging to the calling process # instead. # the comm and timer processes will set events that the threads # will listen for to initiate the callbacks # only create the mp.Event once - # to mimic create_state_transition_system, for future-proofing # (in this case, currently, this is only called at __init__() time) if not hasattr(self, 'update_data_event'): self.update_data_event = mp.Event() # only create the thread.Event once - this is used to exit # the callback thread if not hasattr(self, 'update_data_callback_kill_event'): self.update_data_callback_kill_event = mp.Event() # destroy an existing thread if we had created one previously if(hasattr(self, 'update_data_thread') and self.update_data_thread is not None): # let's tear this down. To kill it, two events must be set... # in the right sequence! self.update_data_callback_kill_event.set() self.update_data_event.set() self.update_data_thread.join() if setFunc: self.update_data_func = update_data_func if self.update_data_func is not None: if createThread: self.update_data_callback_kill_event.clear() self.update_data_thread = threading.Thread( name='sr700_update_data', target=self.update_data_run, args=(self.update_data_event,), daemon=True ) else: self.update_data_thread = None def _create_state_transition_system( self, state_transition_func, setFunc=True, createThread=False): # these callbacks cannot be called from another process in Windows. # Therefore, spawn a thread belonging to the calling process # instead. # the comm and timer processes will set events that the threads # will listen for to initiate the callbacks # only create the mp.Event once - this fn can get called more # than once, by __init__() and by set_state_transition_func() if not hasattr(self, 'state_transition_event'): self.state_transition_event = mp.Event() # only create the thread.Event once - this is used to exit # the callback thread if not hasattr(self, 'state_transition_callback_kill_event'): self.state_transition_callback_kill_event = mp.Event() # destroy an existing thread if we had created one previously if(hasattr(self, 'state_transition_thread') and self.state_transition_thread is not None): # let's tear this down. To kill it, two events must be set... # in the right sequence! self.state_transition_callback_kill_event.set() self.state_transition_event.set() self.state_transition_thread.join() if setFunc: self.state_transition_func = state_transition_func if self.state_transition_func is not None: if createThread: self.state_transition_callback_kill_event.clear() self.state_transition_thread = threading.Thread( name='sr700_state_transition', target=self.state_transition_run, args=(self.state_transition_event,), daemon=True ) else: self.state_transition_thread = None @property def fan_speed(self): """Get/Set fan speed. Can be 1 to 9 inclusive. Args: Setter: fan_speed (int): fan speed Returns: Getter: (int): fan speed """ return self._fan_speed.value @fan_speed.setter def fan_speed(self, value): """Verifies the value is between 1 and 9 inclusively.""" if value not in range(1, 10): raise exceptions.RoasterValueError self._fan_speed.value = value @property def heat_setting(self): """Get/Set heat setting, 0 to 3 inclusive. 0=off, 3=high. Do not set when running freshroastsr700 in thermostat mode. Args: Setter: heat_setting (int): heat setting Returns: Getter: (int): heat setting """ return self._heat_setting.value @heat_setting.setter def heat_setting(self, value): """Verifies that the heat setting is between 0 and 3.""" if value not in range(0, 4): raise exceptions.RoasterValueError self._heat_setting.value = value @property def target_temp(self): """Get/Set the target temperature for this package's built-in software PID controler. Only used when freshroastsr700 is instantiated with thermostat=True. Args: Setter: value (int): a target temperature in degF between 150 and 551. Returns: Getter: (int) target temperature in degF between 150 and 551 """ return self._target_temp.value @target_temp.setter def target_temp(self, value): if value not in range(150, 551): raise exceptions.RoasterValueError self._target_temp.value = value @property def current_temp(self): """Current temperature of the roast chamber as reported by hardware. Returns: (int) current temperature, in degrees Fahrenheit """ return self._current_temp.value @current_temp.setter def current_temp(self, value): if value not in range(150, 551): raise exceptions.RoasterValueError self._current_temp.value = value @property def time_remaining(self): """The amount of time, in seconds, remaining until a call to the state_transition_func is made. can be set to an arbitrary value up to 600 seconds at any time. When a new value is set, freshroastsr700 will count down from this new value down to 0. time_remaining is decremented to 0 only when in a roasting or cooling state. In other states, the value is not touched. Args: Setter: time_remaining (int): tiem remaining in seconds Returns: Getter: time_remaining(int): time remaining, in seconds """ return self._time_remaining.value @time_remaining.setter def time_remaining(self, value): self._time_remaining.value = value @property def total_time(self): """The total time this instance has been in roasting or cooling state sicne the latest roast began. Returns: total_time (int): time, in seconds """ return self._total_time.value @total_time.setter def total_time(self, value): self._total_time.value = value @property def heater_level(self): """A getter method for _heater_level. When thermostat=True, value is driven by built-in PID controller. When ext_sw_heater_drive=True, value is driven by calls to heater_level(). Min will always be zero, max will be heater_segments (optional instantiation parameter, defaults to 8).""" return self._heater_level.value @heater_level.setter def heater_level(self, value): """Verifies that the heater_level is between 0 and heater_segments. Can only be called when freshroastsr700 object is initialized with ext_sw_heater_drive=True. Will throw RoasterValueError otherwise.""" if self._ext_sw_heater_drive: if value not in range(0, self._heater_bangbang_segments+1): raise exceptions.RoasterValueError self._heater_level.value = value else: raise exceptions.RoasterValueError @property def connected(self): """A getter method for _connected. Indicates that the this software is currently communicating with FreshRoast SR700 hardware.""" return self._connected.value @property def connect_state(self): """A getter method for _connect_state. Indicates the current connection state this software is in for FreshRoast SR700 hardware. Returns: freshroastsr700.CS_NOT_CONNECTED the software is not currenting communicating with hardware, neither was it instructed to do so. A previously failed connection attempt will also result in this state. freshroastsr700.CS_ATTEMPTING_CONNECT A call to auto_connect() or connect() was made, and the software is currently attempting to connect to hardware. freshroastsr700.CS_CONNECTED The hardware was found, and the software is communicating with the hardware. """ return self._connect_state.value def set_state_transition_func(self, func): """THIS FUNCTION MUST BE CALLED BEFORE CALLING freshroastsr700.auto_connect(). Set, or re-set, the state transition function callback. The supplied function will be called from a separate thread within freshroastsr700, triggered by a separate, internal child process. This function will fail if the freshroastsr700 device is already connected to hardware, because by that time, the timer process and thread have already been spawned. Args: state_transition_func (func): the function to call for every state transition. A state transition occurs whenever the freshroastsr700's time_remaining value counts down to 0. Returns: nothing """ if self._connected.value: logging.error("freshroastsr700.set_state_transition_func must be " "called before freshroastsr700.auto_connect()." " Not registering func.") return False # no connection yet. so OK to set func pointer self._create_state_transition_system(func) return True def update_data_run(self, event_to_wait_on): """This is the thread that listens to an event from the comm process to execute the update_data_func callback in the context of the main process. """ # with the daemon=Turue setting, this thread should # quit 'automatically' while event_to_wait_on.wait(): event_to_wait_on.clear() if self.update_data_callback_kill_event.is_set(): return self.update_data_func() def state_transition_run(self, event_to_wait_on): """This is the thread that listens to an event from the timer process to execute the state_transition_func callback in the context of the main process. """ # with the daemon=Turue setting, this thread should # quit 'automatically' while event_to_wait_on.wait(): event_to_wait_on.clear() if self.state_transition_callback_kill_event.is_set(): return self.state_transition_func() def _connect(self): """Do not call this directly - call auto_connect() or connect(), which will call _connect() for you. Connects to the roaster and creates communication thread. Raises a RoasterLokkupError exception if the hardware is not found. """ # the following call raises a RoasterLookupException when the device # is not found. It is port = utils.find_device('1A86:5523') # on some systems, after the device port is added to the device list, # it can take up to 20 seconds after USB insertion for # the port to become available... (!) # let's put a safety timeout in here as a precaution wait_timeout = time.time() + 40.0 # should be PLENTY of time! # let's update the _connect_state while we're at it... self._connect_state.value = self.CS_CONNECTING connect_success = False while time.time() < wait_timeout: try: self._ser = serial.Serial( port=port, baudrate=9600, bytesize=8, parity='N', stopbits=1.5, timeout=0.25, xonxoff=False, rtscts=False, dsrdtr=False) connect_success = True break except serial.SerialException: time.sleep(0.5) if not connect_success: # timeout on attempts raise exceptions.RoasterLookupError self._initialize() def _initialize(self): """Sends the initialization packet to the roaster.""" self._header.value = b'\xAA\x55' self._current_state.value = b'\x00\x00' s = self._generate_packet() self._ser.write(s) self._header.value = b'\xAA\xAA' self._current_state.value = b'\x02\x01' return self._read_existing_recipe() def _write_to_device(self): success = False try: packet = self._generate_packet() logging.debug('WR: ' + str(binascii.hexlify(packet))) self._ser.write(packet) success = True except serial.serialutil.SerialException: logging.error('caught serial exception writing') return success def _read_from_device(self): r = [] footer_reached = False while len(r) < 14 and footer_reached is False: r.append(self._ser.read(1)) if len(r) >= 2 and b''.join(r)[-2:] == self._footer: footer_reached = True logging.debug('RD: ' + str(binascii.hexlify(b''.join(r)))) return b''.join(r) def _read_existing_recipe(self): existing_recipe = [] end_of_recipe = False while not end_of_recipe: bytes_waiting = self._ser.in_waiting if bytes_waiting < 14: # still need to write to device every .25sec it seems time.sleep(0.25) self._write_to_device() else: while (bytes_waiting // 14) > 0: r = self._read_from_device() bytes_waiting = self._ser.in_waiting if len(r) < 14: logging.warn('short packet length') else: existing_recipe.append(r) if r[4:5] == b'\xAF' or r[4:5] == b'\x00': end_of_recipe = True continue return existing_recipe def connect(self): """Attempt to connect to hardware immediately. Will not retry. Check freshroastsr700.connected or freshroastsr700.connect_state to verify result. Raises: freshroastsr700.exeptions.RoasterLookupError No hardware connected to the computer. """ self._start_connect(self.CA_SINGLE_SHOT) while(self._connect_state.value == self.CS_ATTEMPTING_CONNECT or self._connect_state.value == self.CS_CONNECTING): time.sleep(0.1) if self.CS_CONNECTED != self._connect_state.value: raise exceptions.RoasterLookupError def auto_connect(self): """Starts a thread that will automatically connect to the roaster when it is plugged in.""" self._start_connect(self.CA_AUTO) def _start_connect(self, connect_type): """Starts the connection process, as called (internally) from the user context, either from auto_connect() or connect(). Never call this from the _comm() process context. """ if self._connect_state.value != self.CS_NOT_CONNECTED: # already done or in process, assume success return self._connected.value = 0 self._connect_state.value = self.CS_ATTEMPTING_CONNECT # tell comm process to attempt connection self._attempting_connect.value = connect_type # EXTREMELY IMPORTANT - for this to work at all in Windows, # where the above processes are spawned (vs forked in Unix), # the thread objects (as sattributes of this object) must be # assigned to this object AFTER we have spawned the processes. # That way, multiprocessing can pickle the freshroastsr700 # successfully. (It can't pickle thread-related stuff.) if self.update_data_func is not None: # Need to launch the thread that will listen to the event self._create_update_data_system( None, setFunc=False, createThread=True) self.update_data_thread.start() if self.state_transition_func is not None: # Need to launch the thread that will listen to the event self._create_state_transition_system( None, setFunc=False, createThread=True) self.state_transition_thread.start() def _auto_connect(self): """Attempts to connect to the roaster every quarter of a second.""" while not self._teardown.value: try: self._connect() return True except exceptions.RoasterLookupError: time.sleep(.25) return False def disconnect(self): """Stops the communication loop to the roaster. Note that this will not actually stop the roaster itself.""" self._disconnect.value = 1 def terminate(self): """Stops the communication loop to the roaster and closes down all communication processes. Note that this will not actually stop the roaster itself. You will need to instantiate a new freshroastsr700 object after calling this function, in order to re-start communications with the hardware. """ self.disconnect() self._teardown.value = 1 def _comm(self, thermostat=False, kp=0.06, ki=0.0075, kd=0.01, heater_segments=8, ext_sw_heater_drive=False, update_data_event=None): """Do not call this directly - call auto_connect(), which will spawn comm() for you. This is the main communications loop to the roaster. whenever a valid packet is received from the device, if an update_data_event is available, it will be signalled. Args: thermostat (bool): thermostat mode. if set to True, turns on thermostat mode. In thermostat mode, freshroastsr700 takes control of heat_setting and does software PID control to hit the demanded target_temp. ext_sw_heater_drive (bool): enable direct control over the internal heat_controller object. Defaults to False. When set to True, the thermostat field is IGNORED, and assumed to be False. Direct control over the software heater_level means that the PID controller cannot control the heater. Since thermostat and ext_sw_heater_drive cannot be allowed to both be True, this arg is given precedence over the thermostat arg. kp (float): Kp value to use for PID control. Defaults to 0.06. ki (float): Ki value to use for PID control. Defaults to 0.0075. kd (float): Kd value to use for PID control. Defaults to 0.01. heater_segments (int): the pseudo-control range for the internal heat_controller object. Defaults to 8. update_data_event (multiprocessing.Event): If set, allows the comm_process to signal to the parent process that new device data is available. Returns: nothing """ # since this process is started with daemon=True, it should exit # when the owning process terminates. Therefore, safe to loop forever. while not self._teardown.value: # waiting for command to attempt connect # print( "waiting for command to attempt connect") while self._attempting_connect.value == self.CA_NONE: time.sleep(0.25) if self._teardown.value: break # if we're tearing down, bail now. if self._teardown.value: break # we got the command to attempt to connect # change state to 'attempting_connect' self._connect_state.value = self.CS_ATTEMPTING_CONNECT # attempt connection if self.CA_AUTO == self._attempting_connect.value: # this call will block until a connection is achieved # it will also set _connect_state to CS_CONNECTING # if appropriate if self._auto_connect(): # when we unblock, it is an indication of a successful # connection self._connected.value = 1 self._connect_state.value = self.CS_CONNECTED else: # failure, normally due to a timeout self._connected.value = 0 self._connect_state.value = self.CS_NOT_CONNECTED # we failed to connect - start over from the top # reset flag self._attempting_connect.value = self.CA_NONE continue elif self.CA_SINGLE_SHOT == self._attempting_connect.value: # try once, now, if failure, start teh big loop over try: self._connect() self._connected.value = 1 self._connect_state.value = self.CS_CONNECTED except exceptions.RoasterLookupError: self._connected.value = 0 self._connect_state.value = self.CS_NOT_CONNECTED if self._connect_state.value != self.CS_CONNECTED: # we failed to connect - start over from the top # reset flag self._attempting_connect.value = self.CA_NONE continue else: # shouldn't be here # reset flag self._attempting_connect.value = self.CA_NONE continue # We are connected! # print( "We are connected!") # reset flag right away self._attempting_connect.value = self.CA_NONE # Initialize PID controller if thermostat function was specified at # init time pidc = None heater = None if(thermostat): pidc = pid.PID(kp, ki, kd, Output_max=heater_segments, Output_min=0 ) if thermostat or ext_sw_heater_drive: heater = heat_controller(number_of_segments=heater_segments) read_state = self.LOOKING_FOR_HEADER_1 r = [] write_errors = 0 read_errors = 0 while not self._disconnect.value: start = datetime.datetime.now() # write to device if not self._write_to_device(): logging.error('comm - _write_to_device() failed!') write_errors += 1 if write_errors > 3: # it's time to consider the device as being "gone" logging.error('comm - 3 successive write ' 'failures, disconnecting.') self._disconnect.value = 1 continue else: # reset write_errors write_errors = 0 # read from device try: while self._ser.in_waiting: _byte = self._ser.read(1) read_state, r, err = ( self._process_reponse_byte( read_state, _byte, r, update_data_event)) except IOError: # typically happens when device is suddenly unplugged logging.error('comm - read from device failed!') read_errors += 1 if write_errors > 3: # it's time to consider the device as being "gone" logging.error('comm - 3 successive read ' 'failures, disconnecting.') self._disconnect.value = 1 continue else: read_errors = 0 # next, drive SW heater when using # thermostat mode (PID controller calcs) # or in external sw heater drive mode, # when roasting. if thermostat or ext_sw_heater_drive: if 'roasting' == self.get_roaster_state(): if heater.about_to_rollover(): # it's time to use the PID controller value # and set new output level on heater! if ext_sw_heater_drive: # read user-supplied value heater.heat_level = self._heater_level.value else: # thermostat output = pidc.update( self.current_temp, self.target_temp) heater.heat_level = output # make this number visible to other processes... self._heater_level.value = heater.heat_level # read bang-bang heater output array element & apply it if heater.generate_bangbang_output(): # ON self.heat_setting = 3 else: # OFF self.heat_setting = 0 else: # for all other states, heat_level = OFF heater.heat_level = 0 # make this number visible to other processes... self._heater_level.value = heater.heat_level self.heat_setting = 0 # calculate sleep time to stick to 0.25sec period comp_time = datetime.datetime.now() - start sleep_duration = 0.25 - comp_time.total_seconds() if sleep_duration > 0: time.sleep(sleep_duration) self._ser.close() # reset disconnect flag self._disconnect.value = 0 # reset connection values self._connected.value = 0 self._connect_state.value = self.CS_NOT_CONNECTED # print("We are disconnected.") def _process_reponse_byte(self, read_state, _byte, r, update_data_event): err = False if self.LOOKING_FOR_HEADER_1 == read_state: if b'\xAA' == _byte: read_state = self.LOOKING_FOR_HEADER_2 elif self.LOOKING_FOR_HEADER_2 == read_state: if b'\xAA' == _byte: read_state = self.PACKET_DATA # reset packet array now... r = [] else: read_state = self.LOOKING_FOR_HEADER_1 elif self.PACKET_DATA == read_state: if b'\xAA' == _byte: # this could be the start of an end of packet marker read_state = self.LOOKING_FOR_FOOTER_2 else: r.append(_byte) # SR700 FW bug - if current temp is 250 degF (0xFA), # the FW does not transmit the footer at all. # fake the footer here. if(len(r) == 10 and b'\xFA' == _byte): # we will 'fake' a footer to make this decoder work # as intended read_state, r, _ = ( self._process_reponse_byte( read_state, b'\xAA', r, update_data_event)) read_state, r, err = ( self._process_reponse_byte( read_state, b'\xFA', r, update_data_event)) elif self.LOOKING_FOR_FOOTER_2 == read_state: if b'\xFA' == _byte: # OK we have a full packet - PROCESS PACKET err = self._process_response_data(r, update_data_event) read_state = self.LOOKING_FOR_HEADER_1 else: # the last byte was not the beginning of the footer r.append(b'\xAA') read_state = self.PACKET_DATA read_state, r, err = self._process_reponse_byte( read_state, _byte, r, update_data_event) else: # error state, shouldn't happen... logging.error('_process_reponse_byte - invalid read_state %d' % read_state) read_state = self.LOOKING_FOR_HEADER_1 err = True return read_state, r, err def _process_response_data(self, r, update_data_event): err = False if len(r) != 10: logging.warn('read packet data len not 10, got: %d' % len(r)) logging.warn('RD: ' + str(binascii.hexlify(b''.join(r)))) err = True else: temp = struct.unpack(">H", b''.join(r[8:10]))[0] if(temp == 65280): self.current_temp = 150 elif(temp > 550 or temp < 150): logging.warn('temperature out of range: reinitializing...') self._initialize() err = True return else: self.current_temp = temp if(update_data_event is not None): update_data_event.set() return err def _timer(self, state_transition_event=None): """Timer loop used to keep track of the time while roasting or cooling. If the time remaining reaches zero, the roaster will call the supplied state transistion function or the roaster will be set to the idle state.""" while not self._teardown.value: state = self.get_roaster_state() if(state == 'roasting' or state == 'cooling'): time.sleep(1) self.total_time += 1 if(self.time_remaining > 0): self.time_remaining -= 1 else: if(state_transition_event is not None): state_transition_event.set() else: self.idle() else: time.sleep(0.01) def _generate_packet(self): """Generates a packet based upon the current class variables. Note that current temperature is not sent, as the original application sent zeros to the roaster for the current temperature.""" roaster_time = utils.seconds_to_float(self._time_remaining.value) packet = ( self._header.value + self._temp_unit.value + self._flags.value + self._current_state.value + struct.pack(">B", self._fan_speed.value) + struct.pack(">B", int(round(roaster_time * 10.0))) + struct.pack(">B", self._heat_setting.value) + b'\x00\x00' + self._footer) return packet def idle(self): """Sets the current state of the roaster to idle.""" self._current_state.value = b'\x02\x01' def roast(self): """Sets the current state of the roaster to roast and begins roasting.""" self._current_state.value = b'\x04\x02' def cool(self): """Sets the current state of the roaster to cool. The roaster expects that cool will be run after roast, and will not work as expected if ran before.""" self._current_state.value = b'\x04\x04' def sleep(self): """Sets the current state of the roaster to sleep. Different than idle in that this will set double dashes on the roaster display rather than digits.""" self._current_state.value = b'\x08\x01'
Roastero/freshroastsr700
freshroastsr700/__init__.py
freshroastsr700._generate_packet
python
def _generate_packet(self): roaster_time = utils.seconds_to_float(self._time_remaining.value) packet = ( self._header.value + self._temp_unit.value + self._flags.value + self._current_state.value + struct.pack(">B", self._fan_speed.value) + struct.pack(">B", int(round(roaster_time * 10.0))) + struct.pack(">B", self._heat_setting.value) + b'\x00\x00' + self._footer) return packet
Generates a packet based upon the current class variables. Note that current temperature is not sent, as the original application sent zeros to the roaster for the current temperature.
train
https://github.com/Roastero/freshroastsr700/blob/49cf4961444c0f56d051d5ac5088ace480b54f02/freshroastsr700/__init__.py#L936-L952
null
class freshroastsr700(object): """A class to interface with a freshroastsr700 coffee roaster. Args: update_data_func (func): A function to call when this object receives new data from the hardware. Defaults to None. state_transition_func (func): A function to call when time_remaining counts down to 0 and the device is either in roasting or cooling state. Defaults to None. thermostat (bool): thermostat mode. if set to True, turns on thermostat mode. In thermostat mode, freshroastsr700 takes control of heat_setting and does software PID control to hit the demanded target_temp. Defaults to False. ext_sw_heater_drive (bool): enable direct control over the internal heat_controller object. Defaults to False. When set to True, the thermostat field is IGNORED, and assumed to be False. Direct control over the software heater_level means that the freshroastsr700's PID controller cannot control the heater. Since thermostat and ext_sw_heater_drive cannot be allowed to both be True, this arg is given precedence over the thermostat arg. Note that (thermostat=False, ext_sw_heater_drive=False), (thermostat=True, ext_sw_heater_drive=False), (thermostat=False, ext_sw_heater_drive=True), are all acceptable arg combinations. Only the (thermostat=True, ext_sw_heater_drive=True), cominbation is not allowed, and this software will set thermostat=False in that case. kp (float): Kp value to use for PID control. Defaults to 0.06. ki (float): Ki value to use for PID control. Defaults to 0.0075. kd (float): Kd value to use for PID control. Defaults to 0.01. heater_segments (int): the pseudo-control range for the internal heat_controller object. Defaults to 8. """ def __init__(self, update_data_func=None, state_transition_func=None, thermostat=False, kp=0.06, ki=0.0075, kd=0.01, heater_segments=8, ext_sw_heater_drive=False): """Create variables used to send in packets to the roaster. The update data function is called when a packet is opened. The state transistion function is used by the timer thread to know what to do next. See wiki for more information on packet structure and fields.""" # constants for protocol decoding self.LOOKING_FOR_HEADER_1 = 0 self.LOOKING_FOR_HEADER_2 = 1 self.PACKET_DATA = 2 self.LOOKING_FOR_FOOTER_2 = 3 # constants for connection state monitoring self.CS_NOT_CONNECTED = -2 self.CS_ATTEMPTING_CONNECT = -1 self.CS_CONNECTING = 0 self.CS_CONNECTED = 1 # constants for connection attempt type self.CA_NONE = 0 self.CA_AUTO = 1 self.CA_SINGLE_SHOT = 2 self._create_update_data_system(update_data_func) self._create_state_transition_system(state_transition_func) self._header = sharedctypes.Array('c', b'\xAA\xAA') self._temp_unit = sharedctypes.Array('c', b'\x61\x74') self._flags = sharedctypes.Array('c', b'\x63') self._current_state = sharedctypes.Array('c', b'\x02\x01') self._footer = b'\xAA\xFA' self._fan_speed = sharedctypes.Value('i', 1) self._heat_setting = sharedctypes.Value('i', 0) self._target_temp = sharedctypes.Value('i', 150) self._current_temp = sharedctypes.Value('i', 150) self._time_remaining = sharedctypes.Value('i', 0) self._total_time = sharedctypes.Value('i', 0) self._disconnect = sharedctypes.Value('i', 0) self._teardown = sharedctypes.Value('i', 0) # for SW PWM heater setting self._heater_level = sharedctypes.Value('i', 0) # the following vars are not process-safe, do not access them # from the comm or timer threads, nor from the callbacks. self._ext_sw_heater_drive = ext_sw_heater_drive if not self._ext_sw_heater_drive: self._thermostat = thermostat else: self._thermostat = False self._pid_kp = kp self._pid_ki = ki self._pid_kd = kd self._heater_bangbang_segments = heater_segments # initialize to 'not connected' self._connected = sharedctypes.Value('i', 0) self._connect_state = sharedctypes.Value('i', self.CS_NOT_CONNECTED) # initialize to 'not trying to connect' self._attempting_connect = sharedctypes.Value('i', self.CA_NONE) # create comm process self.comm_process = mp.Process( target=self._comm, args=( self._thermostat, self._pid_kp, self._pid_ki, self._pid_kd, self._heater_bangbang_segments, self._ext_sw_heater_drive, self.update_data_event,)) self.comm_process.daemon = True self.comm_process.start() # create timer process that counts down time_remaining self.time_process = mp.Process( target=self._timer, args=( self.state_transition_event,)) self.time_process.daemon = True self.time_process.start() def _create_update_data_system( self, update_data_func, setFunc=True, createThread=False): # these callbacks cannot be called from another process in Windows. # Therefore, spawn a thread belonging to the calling process # instead. # the comm and timer processes will set events that the threads # will listen for to initiate the callbacks # only create the mp.Event once - # to mimic create_state_transition_system, for future-proofing # (in this case, currently, this is only called at __init__() time) if not hasattr(self, 'update_data_event'): self.update_data_event = mp.Event() # only create the thread.Event once - this is used to exit # the callback thread if not hasattr(self, 'update_data_callback_kill_event'): self.update_data_callback_kill_event = mp.Event() # destroy an existing thread if we had created one previously if(hasattr(self, 'update_data_thread') and self.update_data_thread is not None): # let's tear this down. To kill it, two events must be set... # in the right sequence! self.update_data_callback_kill_event.set() self.update_data_event.set() self.update_data_thread.join() if setFunc: self.update_data_func = update_data_func if self.update_data_func is not None: if createThread: self.update_data_callback_kill_event.clear() self.update_data_thread = threading.Thread( name='sr700_update_data', target=self.update_data_run, args=(self.update_data_event,), daemon=True ) else: self.update_data_thread = None def _create_state_transition_system( self, state_transition_func, setFunc=True, createThread=False): # these callbacks cannot be called from another process in Windows. # Therefore, spawn a thread belonging to the calling process # instead. # the comm and timer processes will set events that the threads # will listen for to initiate the callbacks # only create the mp.Event once - this fn can get called more # than once, by __init__() and by set_state_transition_func() if not hasattr(self, 'state_transition_event'): self.state_transition_event = mp.Event() # only create the thread.Event once - this is used to exit # the callback thread if not hasattr(self, 'state_transition_callback_kill_event'): self.state_transition_callback_kill_event = mp.Event() # destroy an existing thread if we had created one previously if(hasattr(self, 'state_transition_thread') and self.state_transition_thread is not None): # let's tear this down. To kill it, two events must be set... # in the right sequence! self.state_transition_callback_kill_event.set() self.state_transition_event.set() self.state_transition_thread.join() if setFunc: self.state_transition_func = state_transition_func if self.state_transition_func is not None: if createThread: self.state_transition_callback_kill_event.clear() self.state_transition_thread = threading.Thread( name='sr700_state_transition', target=self.state_transition_run, args=(self.state_transition_event,), daemon=True ) else: self.state_transition_thread = None @property def fan_speed(self): """Get/Set fan speed. Can be 1 to 9 inclusive. Args: Setter: fan_speed (int): fan speed Returns: Getter: (int): fan speed """ return self._fan_speed.value @fan_speed.setter def fan_speed(self, value): """Verifies the value is between 1 and 9 inclusively.""" if value not in range(1, 10): raise exceptions.RoasterValueError self._fan_speed.value = value @property def heat_setting(self): """Get/Set heat setting, 0 to 3 inclusive. 0=off, 3=high. Do not set when running freshroastsr700 in thermostat mode. Args: Setter: heat_setting (int): heat setting Returns: Getter: (int): heat setting """ return self._heat_setting.value @heat_setting.setter def heat_setting(self, value): """Verifies that the heat setting is between 0 and 3.""" if value not in range(0, 4): raise exceptions.RoasterValueError self._heat_setting.value = value @property def target_temp(self): """Get/Set the target temperature for this package's built-in software PID controler. Only used when freshroastsr700 is instantiated with thermostat=True. Args: Setter: value (int): a target temperature in degF between 150 and 551. Returns: Getter: (int) target temperature in degF between 150 and 551 """ return self._target_temp.value @target_temp.setter def target_temp(self, value): if value not in range(150, 551): raise exceptions.RoasterValueError self._target_temp.value = value @property def current_temp(self): """Current temperature of the roast chamber as reported by hardware. Returns: (int) current temperature, in degrees Fahrenheit """ return self._current_temp.value @current_temp.setter def current_temp(self, value): if value not in range(150, 551): raise exceptions.RoasterValueError self._current_temp.value = value @property def time_remaining(self): """The amount of time, in seconds, remaining until a call to the state_transition_func is made. can be set to an arbitrary value up to 600 seconds at any time. When a new value is set, freshroastsr700 will count down from this new value down to 0. time_remaining is decremented to 0 only when in a roasting or cooling state. In other states, the value is not touched. Args: Setter: time_remaining (int): tiem remaining in seconds Returns: Getter: time_remaining(int): time remaining, in seconds """ return self._time_remaining.value @time_remaining.setter def time_remaining(self, value): self._time_remaining.value = value @property def total_time(self): """The total time this instance has been in roasting or cooling state sicne the latest roast began. Returns: total_time (int): time, in seconds """ return self._total_time.value @total_time.setter def total_time(self, value): self._total_time.value = value @property def heater_level(self): """A getter method for _heater_level. When thermostat=True, value is driven by built-in PID controller. When ext_sw_heater_drive=True, value is driven by calls to heater_level(). Min will always be zero, max will be heater_segments (optional instantiation parameter, defaults to 8).""" return self._heater_level.value @heater_level.setter def heater_level(self, value): """Verifies that the heater_level is between 0 and heater_segments. Can only be called when freshroastsr700 object is initialized with ext_sw_heater_drive=True. Will throw RoasterValueError otherwise.""" if self._ext_sw_heater_drive: if value not in range(0, self._heater_bangbang_segments+1): raise exceptions.RoasterValueError self._heater_level.value = value else: raise exceptions.RoasterValueError @property def connected(self): """A getter method for _connected. Indicates that the this software is currently communicating with FreshRoast SR700 hardware.""" return self._connected.value @property def connect_state(self): """A getter method for _connect_state. Indicates the current connection state this software is in for FreshRoast SR700 hardware. Returns: freshroastsr700.CS_NOT_CONNECTED the software is not currenting communicating with hardware, neither was it instructed to do so. A previously failed connection attempt will also result in this state. freshroastsr700.CS_ATTEMPTING_CONNECT A call to auto_connect() or connect() was made, and the software is currently attempting to connect to hardware. freshroastsr700.CS_CONNECTED The hardware was found, and the software is communicating with the hardware. """ return self._connect_state.value def set_state_transition_func(self, func): """THIS FUNCTION MUST BE CALLED BEFORE CALLING freshroastsr700.auto_connect(). Set, or re-set, the state transition function callback. The supplied function will be called from a separate thread within freshroastsr700, triggered by a separate, internal child process. This function will fail if the freshroastsr700 device is already connected to hardware, because by that time, the timer process and thread have already been spawned. Args: state_transition_func (func): the function to call for every state transition. A state transition occurs whenever the freshroastsr700's time_remaining value counts down to 0. Returns: nothing """ if self._connected.value: logging.error("freshroastsr700.set_state_transition_func must be " "called before freshroastsr700.auto_connect()." " Not registering func.") return False # no connection yet. so OK to set func pointer self._create_state_transition_system(func) return True def update_data_run(self, event_to_wait_on): """This is the thread that listens to an event from the comm process to execute the update_data_func callback in the context of the main process. """ # with the daemon=Turue setting, this thread should # quit 'automatically' while event_to_wait_on.wait(): event_to_wait_on.clear() if self.update_data_callback_kill_event.is_set(): return self.update_data_func() def state_transition_run(self, event_to_wait_on): """This is the thread that listens to an event from the timer process to execute the state_transition_func callback in the context of the main process. """ # with the daemon=Turue setting, this thread should # quit 'automatically' while event_to_wait_on.wait(): event_to_wait_on.clear() if self.state_transition_callback_kill_event.is_set(): return self.state_transition_func() def _connect(self): """Do not call this directly - call auto_connect() or connect(), which will call _connect() for you. Connects to the roaster and creates communication thread. Raises a RoasterLokkupError exception if the hardware is not found. """ # the following call raises a RoasterLookupException when the device # is not found. It is port = utils.find_device('1A86:5523') # on some systems, after the device port is added to the device list, # it can take up to 20 seconds after USB insertion for # the port to become available... (!) # let's put a safety timeout in here as a precaution wait_timeout = time.time() + 40.0 # should be PLENTY of time! # let's update the _connect_state while we're at it... self._connect_state.value = self.CS_CONNECTING connect_success = False while time.time() < wait_timeout: try: self._ser = serial.Serial( port=port, baudrate=9600, bytesize=8, parity='N', stopbits=1.5, timeout=0.25, xonxoff=False, rtscts=False, dsrdtr=False) connect_success = True break except serial.SerialException: time.sleep(0.5) if not connect_success: # timeout on attempts raise exceptions.RoasterLookupError self._initialize() def _initialize(self): """Sends the initialization packet to the roaster.""" self._header.value = b'\xAA\x55' self._current_state.value = b'\x00\x00' s = self._generate_packet() self._ser.write(s) self._header.value = b'\xAA\xAA' self._current_state.value = b'\x02\x01' return self._read_existing_recipe() def _write_to_device(self): success = False try: packet = self._generate_packet() logging.debug('WR: ' + str(binascii.hexlify(packet))) self._ser.write(packet) success = True except serial.serialutil.SerialException: logging.error('caught serial exception writing') return success def _read_from_device(self): r = [] footer_reached = False while len(r) < 14 and footer_reached is False: r.append(self._ser.read(1)) if len(r) >= 2 and b''.join(r)[-2:] == self._footer: footer_reached = True logging.debug('RD: ' + str(binascii.hexlify(b''.join(r)))) return b''.join(r) def _read_existing_recipe(self): existing_recipe = [] end_of_recipe = False while not end_of_recipe: bytes_waiting = self._ser.in_waiting if bytes_waiting < 14: # still need to write to device every .25sec it seems time.sleep(0.25) self._write_to_device() else: while (bytes_waiting // 14) > 0: r = self._read_from_device() bytes_waiting = self._ser.in_waiting if len(r) < 14: logging.warn('short packet length') else: existing_recipe.append(r) if r[4:5] == b'\xAF' or r[4:5] == b'\x00': end_of_recipe = True continue return existing_recipe def connect(self): """Attempt to connect to hardware immediately. Will not retry. Check freshroastsr700.connected or freshroastsr700.connect_state to verify result. Raises: freshroastsr700.exeptions.RoasterLookupError No hardware connected to the computer. """ self._start_connect(self.CA_SINGLE_SHOT) while(self._connect_state.value == self.CS_ATTEMPTING_CONNECT or self._connect_state.value == self.CS_CONNECTING): time.sleep(0.1) if self.CS_CONNECTED != self._connect_state.value: raise exceptions.RoasterLookupError def auto_connect(self): """Starts a thread that will automatically connect to the roaster when it is plugged in.""" self._start_connect(self.CA_AUTO) def _start_connect(self, connect_type): """Starts the connection process, as called (internally) from the user context, either from auto_connect() or connect(). Never call this from the _comm() process context. """ if self._connect_state.value != self.CS_NOT_CONNECTED: # already done or in process, assume success return self._connected.value = 0 self._connect_state.value = self.CS_ATTEMPTING_CONNECT # tell comm process to attempt connection self._attempting_connect.value = connect_type # EXTREMELY IMPORTANT - for this to work at all in Windows, # where the above processes are spawned (vs forked in Unix), # the thread objects (as sattributes of this object) must be # assigned to this object AFTER we have spawned the processes. # That way, multiprocessing can pickle the freshroastsr700 # successfully. (It can't pickle thread-related stuff.) if self.update_data_func is not None: # Need to launch the thread that will listen to the event self._create_update_data_system( None, setFunc=False, createThread=True) self.update_data_thread.start() if self.state_transition_func is not None: # Need to launch the thread that will listen to the event self._create_state_transition_system( None, setFunc=False, createThread=True) self.state_transition_thread.start() def _auto_connect(self): """Attempts to connect to the roaster every quarter of a second.""" while not self._teardown.value: try: self._connect() return True except exceptions.RoasterLookupError: time.sleep(.25) return False def disconnect(self): """Stops the communication loop to the roaster. Note that this will not actually stop the roaster itself.""" self._disconnect.value = 1 def terminate(self): """Stops the communication loop to the roaster and closes down all communication processes. Note that this will not actually stop the roaster itself. You will need to instantiate a new freshroastsr700 object after calling this function, in order to re-start communications with the hardware. """ self.disconnect() self._teardown.value = 1 def _comm(self, thermostat=False, kp=0.06, ki=0.0075, kd=0.01, heater_segments=8, ext_sw_heater_drive=False, update_data_event=None): """Do not call this directly - call auto_connect(), which will spawn comm() for you. This is the main communications loop to the roaster. whenever a valid packet is received from the device, if an update_data_event is available, it will be signalled. Args: thermostat (bool): thermostat mode. if set to True, turns on thermostat mode. In thermostat mode, freshroastsr700 takes control of heat_setting and does software PID control to hit the demanded target_temp. ext_sw_heater_drive (bool): enable direct control over the internal heat_controller object. Defaults to False. When set to True, the thermostat field is IGNORED, and assumed to be False. Direct control over the software heater_level means that the PID controller cannot control the heater. Since thermostat and ext_sw_heater_drive cannot be allowed to both be True, this arg is given precedence over the thermostat arg. kp (float): Kp value to use for PID control. Defaults to 0.06. ki (float): Ki value to use for PID control. Defaults to 0.0075. kd (float): Kd value to use for PID control. Defaults to 0.01. heater_segments (int): the pseudo-control range for the internal heat_controller object. Defaults to 8. update_data_event (multiprocessing.Event): If set, allows the comm_process to signal to the parent process that new device data is available. Returns: nothing """ # since this process is started with daemon=True, it should exit # when the owning process terminates. Therefore, safe to loop forever. while not self._teardown.value: # waiting for command to attempt connect # print( "waiting for command to attempt connect") while self._attempting_connect.value == self.CA_NONE: time.sleep(0.25) if self._teardown.value: break # if we're tearing down, bail now. if self._teardown.value: break # we got the command to attempt to connect # change state to 'attempting_connect' self._connect_state.value = self.CS_ATTEMPTING_CONNECT # attempt connection if self.CA_AUTO == self._attempting_connect.value: # this call will block until a connection is achieved # it will also set _connect_state to CS_CONNECTING # if appropriate if self._auto_connect(): # when we unblock, it is an indication of a successful # connection self._connected.value = 1 self._connect_state.value = self.CS_CONNECTED else: # failure, normally due to a timeout self._connected.value = 0 self._connect_state.value = self.CS_NOT_CONNECTED # we failed to connect - start over from the top # reset flag self._attempting_connect.value = self.CA_NONE continue elif self.CA_SINGLE_SHOT == self._attempting_connect.value: # try once, now, if failure, start teh big loop over try: self._connect() self._connected.value = 1 self._connect_state.value = self.CS_CONNECTED except exceptions.RoasterLookupError: self._connected.value = 0 self._connect_state.value = self.CS_NOT_CONNECTED if self._connect_state.value != self.CS_CONNECTED: # we failed to connect - start over from the top # reset flag self._attempting_connect.value = self.CA_NONE continue else: # shouldn't be here # reset flag self._attempting_connect.value = self.CA_NONE continue # We are connected! # print( "We are connected!") # reset flag right away self._attempting_connect.value = self.CA_NONE # Initialize PID controller if thermostat function was specified at # init time pidc = None heater = None if(thermostat): pidc = pid.PID(kp, ki, kd, Output_max=heater_segments, Output_min=0 ) if thermostat or ext_sw_heater_drive: heater = heat_controller(number_of_segments=heater_segments) read_state = self.LOOKING_FOR_HEADER_1 r = [] write_errors = 0 read_errors = 0 while not self._disconnect.value: start = datetime.datetime.now() # write to device if not self._write_to_device(): logging.error('comm - _write_to_device() failed!') write_errors += 1 if write_errors > 3: # it's time to consider the device as being "gone" logging.error('comm - 3 successive write ' 'failures, disconnecting.') self._disconnect.value = 1 continue else: # reset write_errors write_errors = 0 # read from device try: while self._ser.in_waiting: _byte = self._ser.read(1) read_state, r, err = ( self._process_reponse_byte( read_state, _byte, r, update_data_event)) except IOError: # typically happens when device is suddenly unplugged logging.error('comm - read from device failed!') read_errors += 1 if write_errors > 3: # it's time to consider the device as being "gone" logging.error('comm - 3 successive read ' 'failures, disconnecting.') self._disconnect.value = 1 continue else: read_errors = 0 # next, drive SW heater when using # thermostat mode (PID controller calcs) # or in external sw heater drive mode, # when roasting. if thermostat or ext_sw_heater_drive: if 'roasting' == self.get_roaster_state(): if heater.about_to_rollover(): # it's time to use the PID controller value # and set new output level on heater! if ext_sw_heater_drive: # read user-supplied value heater.heat_level = self._heater_level.value else: # thermostat output = pidc.update( self.current_temp, self.target_temp) heater.heat_level = output # make this number visible to other processes... self._heater_level.value = heater.heat_level # read bang-bang heater output array element & apply it if heater.generate_bangbang_output(): # ON self.heat_setting = 3 else: # OFF self.heat_setting = 0 else: # for all other states, heat_level = OFF heater.heat_level = 0 # make this number visible to other processes... self._heater_level.value = heater.heat_level self.heat_setting = 0 # calculate sleep time to stick to 0.25sec period comp_time = datetime.datetime.now() - start sleep_duration = 0.25 - comp_time.total_seconds() if sleep_duration > 0: time.sleep(sleep_duration) self._ser.close() # reset disconnect flag self._disconnect.value = 0 # reset connection values self._connected.value = 0 self._connect_state.value = self.CS_NOT_CONNECTED # print("We are disconnected.") def _process_reponse_byte(self, read_state, _byte, r, update_data_event): err = False if self.LOOKING_FOR_HEADER_1 == read_state: if b'\xAA' == _byte: read_state = self.LOOKING_FOR_HEADER_2 elif self.LOOKING_FOR_HEADER_2 == read_state: if b'\xAA' == _byte: read_state = self.PACKET_DATA # reset packet array now... r = [] else: read_state = self.LOOKING_FOR_HEADER_1 elif self.PACKET_DATA == read_state: if b'\xAA' == _byte: # this could be the start of an end of packet marker read_state = self.LOOKING_FOR_FOOTER_2 else: r.append(_byte) # SR700 FW bug - if current temp is 250 degF (0xFA), # the FW does not transmit the footer at all. # fake the footer here. if(len(r) == 10 and b'\xFA' == _byte): # we will 'fake' a footer to make this decoder work # as intended read_state, r, _ = ( self._process_reponse_byte( read_state, b'\xAA', r, update_data_event)) read_state, r, err = ( self._process_reponse_byte( read_state, b'\xFA', r, update_data_event)) elif self.LOOKING_FOR_FOOTER_2 == read_state: if b'\xFA' == _byte: # OK we have a full packet - PROCESS PACKET err = self._process_response_data(r, update_data_event) read_state = self.LOOKING_FOR_HEADER_1 else: # the last byte was not the beginning of the footer r.append(b'\xAA') read_state = self.PACKET_DATA read_state, r, err = self._process_reponse_byte( read_state, _byte, r, update_data_event) else: # error state, shouldn't happen... logging.error('_process_reponse_byte - invalid read_state %d' % read_state) read_state = self.LOOKING_FOR_HEADER_1 err = True return read_state, r, err def _process_response_data(self, r, update_data_event): err = False if len(r) != 10: logging.warn('read packet data len not 10, got: %d' % len(r)) logging.warn('RD: ' + str(binascii.hexlify(b''.join(r)))) err = True else: temp = struct.unpack(">H", b''.join(r[8:10]))[0] if(temp == 65280): self.current_temp = 150 elif(temp > 550 or temp < 150): logging.warn('temperature out of range: reinitializing...') self._initialize() err = True return else: self.current_temp = temp if(update_data_event is not None): update_data_event.set() return err def _timer(self, state_transition_event=None): """Timer loop used to keep track of the time while roasting or cooling. If the time remaining reaches zero, the roaster will call the supplied state transistion function or the roaster will be set to the idle state.""" while not self._teardown.value: state = self.get_roaster_state() if(state == 'roasting' or state == 'cooling'): time.sleep(1) self.total_time += 1 if(self.time_remaining > 0): self.time_remaining -= 1 else: if(state_transition_event is not None): state_transition_event.set() else: self.idle() else: time.sleep(0.01) def get_roaster_state(self): """Returns a string based upon the current state of the roaster. Will raise an exception if the state is unknown. Returns: 'idle' if idle, 'sleeping' if sleeping, 'cooling' if cooling, 'roasting' if roasting, 'connecting' if in hardware connection phase, 'unknown' otherwise """ value = self._current_state.value if(value == b'\x02\x01'): return 'idle' elif(value == b'\x04\x04'): return 'cooling' elif(value == b'\x08\x01'): return 'sleeping' # handle null bytes as empty strings elif(value == b'\x00\x00' or value == b''): return 'connecting' elif(value == b'\x04\x02'): return 'roasting' else: return 'unknown' def idle(self): """Sets the current state of the roaster to idle.""" self._current_state.value = b'\x02\x01' def roast(self): """Sets the current state of the roaster to roast and begins roasting.""" self._current_state.value = b'\x04\x02' def cool(self): """Sets the current state of the roaster to cool. The roaster expects that cool will be run after roast, and will not work as expected if ran before.""" self._current_state.value = b'\x04\x04' def sleep(self): """Sets the current state of the roaster to sleep. Different than idle in that this will set double dashes on the roaster display rather than digits.""" self._current_state.value = b'\x08\x01'
Roastero/freshroastsr700
freshroastsr700/__init__.py
heat_controller.heat_level
python
def heat_level(self, value): if value < 0: self._heat_level = 0 elif round(value) > self._num_segments: self._heat_level = self._num_segments else: self._heat_level = int(round(value))
Set the desired output level. Must be between 0 and number_of_segments inclusive.
train
https://github.com/Roastero/freshroastsr700/blob/49cf4961444c0f56d051d5ac5088ace480b54f02/freshroastsr700/__init__.py#L1061-L1069
null
class heat_controller(object): """A class to do gross-level pulse modulation on a bang-bang interface. Args: number_of_segments (int): the resolution of the heat_controller. Defaults to 8. for number_of_segments=N, creates a heat_controller that varies the heat between 0..N inclusive, in integer increments, where 0 is no heat, and N is full heat. The bigger the number, the less often the heat value can be changed, because this object is designed to be called at a regular time interval to output N binary values before rolling over or picking up the latest commanded heat value. """ def __init__(self, number_of_segments=8): # num_segments determines how many time samples are used to produce # the output. This effectively translates to a number of output # levels on the bang-bang controller. If number_of_segments == 8, # for example, then, possible output 'levels' are 0,1,2,...8. # Depending on the output # rate and the load's time constant, the result could be perceived # as discrete lumps rather than an effective average output. # higer rate of output is better than slower. # This code does not attempt to control the rate of output, # that is left to the caller. self._num_segments = number_of_segments self._output_array = [[0 for x in range(self._num_segments)] for x in range(1+self._num_segments)] # I'm sure there's a great way to do this algorithmically for # all possible num_segments... if 4 == self._num_segments: self._output_array[0] = [False, False, False, False] self._output_array[1] = [True, False, False, False] self._output_array[2] = [True, False, True, False] self._output_array[3] = [True, True, True, False] self._output_array[4] = [True, True, True, True] elif 8 == self._num_segments: self._output_array[0] = [False, False, False, False, False, False, False, False] self._output_array[1] = [True, False, False, False, False, False, False, False] self._output_array[2] = [True, False, False, False, True, False, False, False] self._output_array[3] = [True, False, False, True, False, False, True, False] self._output_array[4] = [True, False, True, False, True, False, True, False] self._output_array[5] = [True, True, False, True, True, False, True, False] self._output_array[6] = [True, True, True, False, True, True, True, False] self._output_array[7] = [True, True, True, True, True, True, True, False] self._output_array[8] = [True, True, True, True, True, True, True, True] else: # note that the most effective pulse modulation is one where # ones and zeroes are as temporarily spread as possible. # Example, for a 4-segment output, # [1,1,0,0] is not as effective as/lumpier than # [1,0,1,0], even though they supply the same energy. # If the output rate is much greater than the load's time constant, # this difference will not be percpetible. # Here, we're just stuffing early slots with ones... lumpier for i in range(1+self._num_segments): for j in range(self._num_segments): self._output_array[i][j] = j < i # prepare for output self._heat_level = 0 self._heat_level_now = 0 self._current_index = 0 @property def heat_level(self): """Set/Get the current desired output level. Must be between 0 and number_of_segments inclusive. Args: Setter: value (int): heat_level value, between 0 and number_of_segments inclusive. Returns: Getter (int): heat level""" return self._heat_level @heat_level.setter def generate_bangbang_output(self): """Generates the latest on or off pulse in the string of on (True) or off (False) pulses according to the desired heat_level setting. Successive calls to this function will return the next value in the on/off array series. Call this at control loop rate to obtain the necessary on/off pulse train. This system will not work if the caller expects to be able to specify a new heat_level at every control loop iteration. Only the value set at every number_of_segments iterations will be picked up for output! Call about_to_rollover to determine if it's time to set a new heat_level, if a new level is desired.""" if self._current_index >= self._num_segments: # we're due to switch over to the next # commanded heat_level self._heat_level_now = self._heat_level # reset array index self._current_index = 0 # return output out = self._output_array[self._heat_level_now][self._current_index] self._current_index += 1 return out def about_to_rollover(self): """This method indicates that the next call to generate_bangbang_output is a wraparound read. Use this to determine if it's time to pick up the latest commanded heat_level value and run a PID controller iteration.""" return self._current_index >= self._num_segments
Roastero/freshroastsr700
freshroastsr700/__init__.py
heat_controller.generate_bangbang_output
python
def generate_bangbang_output(self): if self._current_index >= self._num_segments: # we're due to switch over to the next # commanded heat_level self._heat_level_now = self._heat_level # reset array index self._current_index = 0 # return output out = self._output_array[self._heat_level_now][self._current_index] self._current_index += 1 return out
Generates the latest on or off pulse in the string of on (True) or off (False) pulses according to the desired heat_level setting. Successive calls to this function will return the next value in the on/off array series. Call this at control loop rate to obtain the necessary on/off pulse train. This system will not work if the caller expects to be able to specify a new heat_level at every control loop iteration. Only the value set at every number_of_segments iterations will be picked up for output! Call about_to_rollover to determine if it's time to set a new heat_level, if a new level is desired.
train
https://github.com/Roastero/freshroastsr700/blob/49cf4961444c0f56d051d5ac5088ace480b54f02/freshroastsr700/__init__.py#L1071-L1092
null
class heat_controller(object): """A class to do gross-level pulse modulation on a bang-bang interface. Args: number_of_segments (int): the resolution of the heat_controller. Defaults to 8. for number_of_segments=N, creates a heat_controller that varies the heat between 0..N inclusive, in integer increments, where 0 is no heat, and N is full heat. The bigger the number, the less often the heat value can be changed, because this object is designed to be called at a regular time interval to output N binary values before rolling over or picking up the latest commanded heat value. """ def __init__(self, number_of_segments=8): # num_segments determines how many time samples are used to produce # the output. This effectively translates to a number of output # levels on the bang-bang controller. If number_of_segments == 8, # for example, then, possible output 'levels' are 0,1,2,...8. # Depending on the output # rate and the load's time constant, the result could be perceived # as discrete lumps rather than an effective average output. # higer rate of output is better than slower. # This code does not attempt to control the rate of output, # that is left to the caller. self._num_segments = number_of_segments self._output_array = [[0 for x in range(self._num_segments)] for x in range(1+self._num_segments)] # I'm sure there's a great way to do this algorithmically for # all possible num_segments... if 4 == self._num_segments: self._output_array[0] = [False, False, False, False] self._output_array[1] = [True, False, False, False] self._output_array[2] = [True, False, True, False] self._output_array[3] = [True, True, True, False] self._output_array[4] = [True, True, True, True] elif 8 == self._num_segments: self._output_array[0] = [False, False, False, False, False, False, False, False] self._output_array[1] = [True, False, False, False, False, False, False, False] self._output_array[2] = [True, False, False, False, True, False, False, False] self._output_array[3] = [True, False, False, True, False, False, True, False] self._output_array[4] = [True, False, True, False, True, False, True, False] self._output_array[5] = [True, True, False, True, True, False, True, False] self._output_array[6] = [True, True, True, False, True, True, True, False] self._output_array[7] = [True, True, True, True, True, True, True, False] self._output_array[8] = [True, True, True, True, True, True, True, True] else: # note that the most effective pulse modulation is one where # ones and zeroes are as temporarily spread as possible. # Example, for a 4-segment output, # [1,1,0,0] is not as effective as/lumpier than # [1,0,1,0], even though they supply the same energy. # If the output rate is much greater than the load's time constant, # this difference will not be percpetible. # Here, we're just stuffing early slots with ones... lumpier for i in range(1+self._num_segments): for j in range(self._num_segments): self._output_array[i][j] = j < i # prepare for output self._heat_level = 0 self._heat_level_now = 0 self._current_index = 0 @property def heat_level(self): """Set/Get the current desired output level. Must be between 0 and number_of_segments inclusive. Args: Setter: value (int): heat_level value, between 0 and number_of_segments inclusive. Returns: Getter (int): heat level""" return self._heat_level @heat_level.setter def heat_level(self, value): """Set the desired output level. Must be between 0 and number_of_segments inclusive.""" if value < 0: self._heat_level = 0 elif round(value) > self._num_segments: self._heat_level = self._num_segments else: self._heat_level = int(round(value)) def about_to_rollover(self): """This method indicates that the next call to generate_bangbang_output is a wraparound read. Use this to determine if it's time to pick up the latest commanded heat_level value and run a PID controller iteration.""" return self._current_index >= self._num_segments
Roastero/freshroastsr700
examples/pid_tune_aid.py
Roaster.update_data
python
def update_data(self): time_elapsed = datetime.datetime.now() - self.start_time crntTemp = self.roaster.current_temp targetTemp = self.roaster.target_temp heaterLevel = self.roaster.heater_level # print( # "Time: %4.6f, crntTemp: %d, targetTemp: %d, heaterLevel: %d" % # (time_elapsed.total_seconds(), crntTemp, targetTemp, heaterLevel)) self.file.write( "%4.6f,%d,%d,%d\n" % (time_elapsed.total_seconds(), crntTemp, targetTemp, heaterLevel))
This is a method that will be called every time a packet is opened from the roaster.
train
https://github.com/Roastero/freshroastsr700/blob/49cf4961444c0f56d051d5ac5088ace480b54f02/examples/pid_tune_aid.py#L122-L134
null
class Roaster(object): def __init__(self, kp=0.06, ki=0.0075, kd=0.01): """Creates a freshroastsr700 object passing in methods included in this class. Set the PID values above to set them in the freshroastsr700 object.""" self.roaster = freshroastsr700.freshroastsr700( self.update_data, self.next_state, thermostat=True, kp=kp, ki=ki, kd=kd) # test vector for driving sr700 # quick recipe simulation # self.recipe = [ # { # 'time_remaining': 60, # 'target_temp': 350, # 'fan_speed': 9, # 'state': 'roasting' # }, # { # 'time_remaining': 60, # 'target_temp': 390, # 'fan_speed': 5, # 'state': 'roasting' # }, # { # 'time_remaining': 30, # 'target_temp': 420, # 'fan_speed': 5, # 'state': 'roasting' # }, # { # 'time_remaining': 60, # 'target_temp': 450, # 'fan_speed': 5, # 'state': 'roasting' # }, # { # 'time_remaining': 60, # 'target_temp': 480, # 'fan_speed': 3, # 'state': 'roasting' # }, # { # 'time_remaining': 60, # 'target_temp': 500, # 'fan_speed': 3, # 'state': 'roasting' # }, # { # 'time_remaining': 60, # 'target_temp': 150, # 'fan_speed': 9, # 'state': 'cooling' # }, # { # 'time_remaining': 1, # 'target_temp': 150, # 'fan_speed': 1, # 'state': 'idle' # } # ] # for dialing in pid params - 3 min. short cycle self.recipe = [ { 'time_remaining': 60, 'target_temp': 300, 'fan_speed': 9, 'state': 'roasting' }, { 'time_remaining': 60, 'target_temp': 350, 'fan_speed': 5, 'state': 'roasting' }, { 'time_remaining': 60, 'target_temp': 400, 'fan_speed': 5, 'state': 'roasting' }, { 'time_remaining': 60, 'target_temp': 450, 'fan_speed': 4, 'state': 'roasting' }, { 'time_remaining': 30, 'target_temp': 150, 'fan_speed': 9, 'state': 'cooling' }, { 'time_remaining': 1, 'target_temp': 150, 'fan_speed': 1, 'state': 'idle' } ] # to set up process to begin, call next state to load first state self.active_recipe_item = -1 # open file to write temps in CSV format self.file = open("sr700_pid_tune.csv", "w") self.file.write("Time,crntTemp,targetTemp,heaterLevel\n") # get start timestamp self.start_time = datetime.datetime.now() def __del__(self): self.file.close() def next_state(self): """This is a method that will be called when the time remaining ends. The current state can be: roasting, cooling, idle, sleeping, connecting, or unkown.""" self.active_recipe_item += 1 if self.active_recipe_item >= len(self.recipe): # we're done! return # show state step on screen print("--------------------------------------------") print("Setting next process step: %d" % self.active_recipe_item) print("time:%d, target: %ddegF, fan: %d, state: %s" % (self.recipe[self.active_recipe_item]['time_remaining'], self.recipe[self.active_recipe_item]['target_temp'], self.recipe[self.active_recipe_item]['fan_speed'], self.recipe[self.active_recipe_item]['state'] )) print("--------------------------------------------") # set values for next state self.roaster.time_remaining = ( self.recipe[self.active_recipe_item]['time_remaining']) self.roaster.target_temp = ( self.recipe[self.active_recipe_item]['target_temp']) self.roaster.fan_speed = ( self.recipe[self.active_recipe_item]['fan_speed']) # set state if(self.recipe[self.active_recipe_item]['state'] == 'roasting'): self.roaster.roast() elif(self.recipe[self.active_recipe_item]['state'] == 'cooling'): self.roaster.cool() elif(self.recipe[self.active_recipe_item]['state'] == 'idle'): self.roaster.idle() elif(self.recipe[self.active_recipe_item]['state'] == 'cooling'): self.roaster.sleep() def recipe_total_time(self): total_time = 0 for step in self.recipe: total_time += step['time_remaining'] return total_time
Roastero/freshroastsr700
examples/pid_tune_aid.py
Roaster.next_state
python
def next_state(self): self.active_recipe_item += 1 if self.active_recipe_item >= len(self.recipe): # we're done! return # show state step on screen print("--------------------------------------------") print("Setting next process step: %d" % self.active_recipe_item) print("time:%d, target: %ddegF, fan: %d, state: %s" % (self.recipe[self.active_recipe_item]['time_remaining'], self.recipe[self.active_recipe_item]['target_temp'], self.recipe[self.active_recipe_item]['fan_speed'], self.recipe[self.active_recipe_item]['state'] )) print("--------------------------------------------") # set values for next state self.roaster.time_remaining = ( self.recipe[self.active_recipe_item]['time_remaining']) self.roaster.target_temp = ( self.recipe[self.active_recipe_item]['target_temp']) self.roaster.fan_speed = ( self.recipe[self.active_recipe_item]['fan_speed']) # set state if(self.recipe[self.active_recipe_item]['state'] == 'roasting'): self.roaster.roast() elif(self.recipe[self.active_recipe_item]['state'] == 'cooling'): self.roaster.cool() elif(self.recipe[self.active_recipe_item]['state'] == 'idle'): self.roaster.idle() elif(self.recipe[self.active_recipe_item]['state'] == 'cooling'): self.roaster.sleep()
This is a method that will be called when the time remaining ends. The current state can be: roasting, cooling, idle, sleeping, connecting, or unkown.
train
https://github.com/Roastero/freshroastsr700/blob/49cf4961444c0f56d051d5ac5088ace480b54f02/examples/pid_tune_aid.py#L136-L169
null
class Roaster(object): def __init__(self, kp=0.06, ki=0.0075, kd=0.01): """Creates a freshroastsr700 object passing in methods included in this class. Set the PID values above to set them in the freshroastsr700 object.""" self.roaster = freshroastsr700.freshroastsr700( self.update_data, self.next_state, thermostat=True, kp=kp, ki=ki, kd=kd) # test vector for driving sr700 # quick recipe simulation # self.recipe = [ # { # 'time_remaining': 60, # 'target_temp': 350, # 'fan_speed': 9, # 'state': 'roasting' # }, # { # 'time_remaining': 60, # 'target_temp': 390, # 'fan_speed': 5, # 'state': 'roasting' # }, # { # 'time_remaining': 30, # 'target_temp': 420, # 'fan_speed': 5, # 'state': 'roasting' # }, # { # 'time_remaining': 60, # 'target_temp': 450, # 'fan_speed': 5, # 'state': 'roasting' # }, # { # 'time_remaining': 60, # 'target_temp': 480, # 'fan_speed': 3, # 'state': 'roasting' # }, # { # 'time_remaining': 60, # 'target_temp': 500, # 'fan_speed': 3, # 'state': 'roasting' # }, # { # 'time_remaining': 60, # 'target_temp': 150, # 'fan_speed': 9, # 'state': 'cooling' # }, # { # 'time_remaining': 1, # 'target_temp': 150, # 'fan_speed': 1, # 'state': 'idle' # } # ] # for dialing in pid params - 3 min. short cycle self.recipe = [ { 'time_remaining': 60, 'target_temp': 300, 'fan_speed': 9, 'state': 'roasting' }, { 'time_remaining': 60, 'target_temp': 350, 'fan_speed': 5, 'state': 'roasting' }, { 'time_remaining': 60, 'target_temp': 400, 'fan_speed': 5, 'state': 'roasting' }, { 'time_remaining': 60, 'target_temp': 450, 'fan_speed': 4, 'state': 'roasting' }, { 'time_remaining': 30, 'target_temp': 150, 'fan_speed': 9, 'state': 'cooling' }, { 'time_remaining': 1, 'target_temp': 150, 'fan_speed': 1, 'state': 'idle' } ] # to set up process to begin, call next state to load first state self.active_recipe_item = -1 # open file to write temps in CSV format self.file = open("sr700_pid_tune.csv", "w") self.file.write("Time,crntTemp,targetTemp,heaterLevel\n") # get start timestamp self.start_time = datetime.datetime.now() def __del__(self): self.file.close() def update_data(self): """This is a method that will be called every time a packet is opened from the roaster.""" time_elapsed = datetime.datetime.now() - self.start_time crntTemp = self.roaster.current_temp targetTemp = self.roaster.target_temp heaterLevel = self.roaster.heater_level # print( # "Time: %4.6f, crntTemp: %d, targetTemp: %d, heaterLevel: %d" % # (time_elapsed.total_seconds(), crntTemp, targetTemp, heaterLevel)) self.file.write( "%4.6f,%d,%d,%d\n" % (time_elapsed.total_seconds(), crntTemp, targetTemp, heaterLevel)) def recipe_total_time(self): total_time = 0 for step in self.recipe: total_time += step['time_remaining'] return total_time
Roastero/freshroastsr700
freshroastsr700/utils.py
frange
python
def frange(start, stop, step, precision): value = start while round(value, precision) < stop: yield round(value, precision) value += step
A generator that will generate a range of floats.
train
https://github.com/Roastero/freshroastsr700/blob/49cf4961444c0f56d051d5ac5088ace480b54f02/freshroastsr700/utils.py#L11-L16
null
# -*- coding: utf-8 -*- # Copyright (c) 2015-2016 Mark Spicer # Made available under the MIT license. import re from serial.tools import list_ports from freshroastsr700 import exceptions def find_device(vidpid): """Finds a connected device with the given VID:PID. Returns the serial port url.""" for port in list_ports.comports(): if re.search(vidpid, port[2], flags=re.IGNORECASE): return port[0] raise exceptions.RoasterLookupError def seconds_to_float(time_in_seconds): """Converts seconds to float rounded to one digit. Will cap the float at 9.9 or 594 seconds.""" if(time_in_seconds <= 594): return round((float(time_in_seconds) / 60.0), 1) return 9.9
Roastero/freshroastsr700
freshroastsr700/utils.py
find_device
python
def find_device(vidpid): for port in list_ports.comports(): if re.search(vidpid, port[2], flags=re.IGNORECASE): return port[0] raise exceptions.RoasterLookupError
Finds a connected device with the given VID:PID. Returns the serial port url.
train
https://github.com/Roastero/freshroastsr700/blob/49cf4961444c0f56d051d5ac5088ace480b54f02/freshroastsr700/utils.py#L19-L26
null
# -*- coding: utf-8 -*- # Copyright (c) 2015-2016 Mark Spicer # Made available under the MIT license. import re from serial.tools import list_ports from freshroastsr700 import exceptions def frange(start, stop, step, precision): """A generator that will generate a range of floats.""" value = start while round(value, precision) < stop: yield round(value, precision) value += step def seconds_to_float(time_in_seconds): """Converts seconds to float rounded to one digit. Will cap the float at 9.9 or 594 seconds.""" if(time_in_seconds <= 594): return round((float(time_in_seconds) / 60.0), 1) return 9.9
Roastero/freshroastsr700
freshroastsr700/pid.py
PID.update
python
def update(self, currentTemp, targetTemp): # in this implementation, ki includes the dt multiplier term, # and kd includes the dt divisor term. This is typical practice in # industry. self.targetTemp = targetTemp self.error = targetTemp - currentTemp self.P_value = self.Kp * self.error # it is common practice to compute derivative term against PV, # instead of de/dt. This is because de/dt spikes # when the set point changes. # PV version with no dPV/dt filter - note 'previous'-'current', # that's desired, how the math works out self.D_value = self.Kd * (self.Derivator - currentTemp) self.Derivator = currentTemp self.Integrator = self.Integrator + self.error if self.Integrator > self.Integrator_max: self.Integrator = self.Integrator_max elif self.Integrator < self.Integrator_min: self.Integrator = self.Integrator_min self.I_value = self.Integrator * self.Ki output = self.P_value + self.I_value + self.D_value if output > self.Output_max: output = self.Output_max if output < self.Output_min: output = self.Output_min return(output)
Calculate PID output value for given reference input and feedback.
train
https://github.com/Roastero/freshroastsr700/blob/49cf4961444c0f56d051d5ac5088ace480b54f02/freshroastsr700/pid.py#L28-L59
null
class PID(object): """Discrete PID control.""" def __init__(self, P, I, D, Derivator=0, Integrator=0, Output_max=8, Output_min=0): self.Kp = P self.Ki = I self.Kd = D self.Derivator = Derivator self.Integrator = Integrator self.Output_max = Output_max self.Output_min = Output_min if(I > 0.0): self.Integrator_max = Output_max / I self.Integrator_min = Output_min / I else: self.Integrator_max = 0.0 self.Integrator_min = 0.0 self.targetTemp = 0 self.error = 0.0 def setPoint(self, targetTemp): """Initilize the setpoint of PID.""" self.targetTemp = targetTemp self.Integrator = 0 self.Derivator = 0 def setIntegrator(self, Integrator): self.Integrator = Integrator def setDerivator(self, Derivator): self.Derivator = Derivator def setKp(self, P): self.Kp = P def setKi(self, I): self.Ki = I def setKd(self, D): self.Kd = D def getPoint(self): return self.targetTemp def getError(self): return self.error def getIntegrator(self): return self.Integrator def getDerivator(self): return self.Derivator def update_p(self, p): self.Kp = p def update_i(self, i): self.Ki = i def update_d(self, d): self.Kd = d
Roastero/freshroastsr700
freshroastsr700/pid.py
PID.setPoint
python
def setPoint(self, targetTemp): self.targetTemp = targetTemp self.Integrator = 0 self.Derivator = 0
Initilize the setpoint of PID.
train
https://github.com/Roastero/freshroastsr700/blob/49cf4961444c0f56d051d5ac5088ace480b54f02/freshroastsr700/pid.py#L61-L65
null
class PID(object): """Discrete PID control.""" def __init__(self, P, I, D, Derivator=0, Integrator=0, Output_max=8, Output_min=0): self.Kp = P self.Ki = I self.Kd = D self.Derivator = Derivator self.Integrator = Integrator self.Output_max = Output_max self.Output_min = Output_min if(I > 0.0): self.Integrator_max = Output_max / I self.Integrator_min = Output_min / I else: self.Integrator_max = 0.0 self.Integrator_min = 0.0 self.targetTemp = 0 self.error = 0.0 def update(self, currentTemp, targetTemp): """Calculate PID output value for given reference input and feedback.""" # in this implementation, ki includes the dt multiplier term, # and kd includes the dt divisor term. This is typical practice in # industry. self.targetTemp = targetTemp self.error = targetTemp - currentTemp self.P_value = self.Kp * self.error # it is common practice to compute derivative term against PV, # instead of de/dt. This is because de/dt spikes # when the set point changes. # PV version with no dPV/dt filter - note 'previous'-'current', # that's desired, how the math works out self.D_value = self.Kd * (self.Derivator - currentTemp) self.Derivator = currentTemp self.Integrator = self.Integrator + self.error if self.Integrator > self.Integrator_max: self.Integrator = self.Integrator_max elif self.Integrator < self.Integrator_min: self.Integrator = self.Integrator_min self.I_value = self.Integrator * self.Ki output = self.P_value + self.I_value + self.D_value if output > self.Output_max: output = self.Output_max if output < self.Output_min: output = self.Output_min return(output) def setIntegrator(self, Integrator): self.Integrator = Integrator def setDerivator(self, Derivator): self.Derivator = Derivator def setKp(self, P): self.Kp = P def setKi(self, I): self.Ki = I def setKd(self, D): self.Kd = D def getPoint(self): return self.targetTemp def getError(self): return self.error def getIntegrator(self): return self.Integrator def getDerivator(self): return self.Derivator def update_p(self, p): self.Kp = p def update_i(self, i): self.Ki = i def update_d(self, d): self.Kd = d
Roastero/freshroastsr700
examples/advanced.py
Roaster.next_state
python
def next_state(self): if(self.roaster.get_roaster_state() == 'roasting'): self.roaster.time_remaining = 20 self.roaster.cool() elif(self.roaster.get_roaster_state() == 'cooling'): self.roaster.idle()
This is a method that will be called when the time remaining ends. The current state can be: roasting, cooling, idle, sleeping, connecting, or unkown.
train
https://github.com/Roastero/freshroastsr700/blob/49cf4961444c0f56d051d5ac5088ace480b54f02/examples/advanced.py#L21-L29
null
class Roaster(object): def __init__(self): """Creates a freshroastsr700 object passing in methods included in this class.""" self.roaster = freshroastsr700.freshroastsr700( self.update_data, self.next_state, thermostat=True) def update_data(self): """This is a method that will be called every time a packet is opened from the roaster.""" print("Current Temperature:", self.roaster.current_temp)
KnorrFG/pyparadigm
pyparadigm/extras.py
_normalize
python
def _normalize(mat: np.ndarray): return ((mat - mat.min()) * (255 / mat.max())).astype(np.uint8)
rescales a numpy array, so that min is 0 and max is 255
train
https://github.com/KnorrFG/pyparadigm/blob/69944cdf3ce2f6414ae1aa1d27a0d8c6e5fb3fd3/pyparadigm/extras.py#L15-L17
null
"""Using functionality from this file requires extra dependencies.""" import warnings try: import numpy as np from matplotlib import cm except ImportError: warnings.warn("This module requires numpy and matplotlib, which seem to be missing.") import contextlib with contextlib.redirect_stdout(None): import pygame def to_24bit_gray(mat: np.ndarray): """returns a matrix that contains RGB channels, and colors scaled from 0 to 255""" return np.repeat(np.expand_dims(_normalize(mat), axis=2), 3, axis=2) def apply_color_map(name: str, mat: np.ndarray = None): """returns an RGB matrix scaled by a matplotlib color map""" def apply_map(mat): return (cm.get_cmap(name)(_normalize(mat))[:, :, :3] * 255).astype(np.uint8) return apply_map if mat is None else apply_map(mat) def mat_to_surface(mat: np.ndarray, transformer=to_24bit_gray): """Can be used to create a pygame.Surface from a 2d numpy array. By default a grey image with scaled colors is returned, but using the transformer argument any transformation can be used. :param mat: the matrix to create the surface of. :type mat: np.ndarray :param transformer: function that transforms the matrix to a valid color matrix, i.e. it must have 3dimension, were the 3rd dimension are the color channels. For each channel a value between 0 and 255 is allowed :type transformer: Callable[np.ndarray[np.ndarray]]""" return pygame.pixelcopy.make_surface(transformer(mat.transpose()) if transformer is not None else mat.transpose())
KnorrFG/pyparadigm
pyparadigm/extras.py
to_24bit_gray
python
def to_24bit_gray(mat: np.ndarray): return np.repeat(np.expand_dims(_normalize(mat), axis=2), 3, axis=2)
returns a matrix that contains RGB channels, and colors scaled from 0 to 255
train
https://github.com/KnorrFG/pyparadigm/blob/69944cdf3ce2f6414ae1aa1d27a0d8c6e5fb3fd3/pyparadigm/extras.py#L20-L23
[ "def _normalize(mat: np.ndarray):\n \"\"\"rescales a numpy array, so that min is 0 and max is 255\"\"\"\n return ((mat - mat.min()) * (255 / mat.max())).astype(np.uint8)\n" ]
"""Using functionality from this file requires extra dependencies.""" import warnings try: import numpy as np from matplotlib import cm except ImportError: warnings.warn("This module requires numpy and matplotlib, which seem to be missing.") import contextlib with contextlib.redirect_stdout(None): import pygame def _normalize(mat: np.ndarray): """rescales a numpy array, so that min is 0 and max is 255""" return ((mat - mat.min()) * (255 / mat.max())).astype(np.uint8) def apply_color_map(name: str, mat: np.ndarray = None): """returns an RGB matrix scaled by a matplotlib color map""" def apply_map(mat): return (cm.get_cmap(name)(_normalize(mat))[:, :, :3] * 255).astype(np.uint8) return apply_map if mat is None else apply_map(mat) def mat_to_surface(mat: np.ndarray, transformer=to_24bit_gray): """Can be used to create a pygame.Surface from a 2d numpy array. By default a grey image with scaled colors is returned, but using the transformer argument any transformation can be used. :param mat: the matrix to create the surface of. :type mat: np.ndarray :param transformer: function that transforms the matrix to a valid color matrix, i.e. it must have 3dimension, were the 3rd dimension are the color channels. For each channel a value between 0 and 255 is allowed :type transformer: Callable[np.ndarray[np.ndarray]]""" return pygame.pixelcopy.make_surface(transformer(mat.transpose()) if transformer is not None else mat.transpose())
KnorrFG/pyparadigm
pyparadigm/extras.py
apply_color_map
python
def apply_color_map(name: str, mat: np.ndarray = None): def apply_map(mat): return (cm.get_cmap(name)(_normalize(mat))[:, :, :3] * 255).astype(np.uint8) return apply_map if mat is None else apply_map(mat)
returns an RGB matrix scaled by a matplotlib color map
train
https://github.com/KnorrFG/pyparadigm/blob/69944cdf3ce2f6414ae1aa1d27a0d8c6e5fb3fd3/pyparadigm/extras.py#L26-L31
[ "def apply_map(mat):\n return (cm.get_cmap(name)(_normalize(mat))[:, :, :3] * 255).astype(np.uint8)\n" ]
"""Using functionality from this file requires extra dependencies.""" import warnings try: import numpy as np from matplotlib import cm except ImportError: warnings.warn("This module requires numpy and matplotlib, which seem to be missing.") import contextlib with contextlib.redirect_stdout(None): import pygame def _normalize(mat: np.ndarray): """rescales a numpy array, so that min is 0 and max is 255""" return ((mat - mat.min()) * (255 / mat.max())).astype(np.uint8) def to_24bit_gray(mat: np.ndarray): """returns a matrix that contains RGB channels, and colors scaled from 0 to 255""" return np.repeat(np.expand_dims(_normalize(mat), axis=2), 3, axis=2) def apply_color_map(name: str, mat: np.ndarray = None): """returns an RGB matrix scaled by a matplotlib color map""" def apply_map(mat): return (cm.get_cmap(name)(_normalize(mat))[:, :, :3] * 255).astype(np.uint8) return apply_map if mat is None else apply_map(mat) def mat_to_surface(mat: np.ndarray, transformer=to_24bit_gray): """Can be used to create a pygame.Surface from a 2d numpy array. By default a grey image with scaled colors is returned, but using the transformer argument any transformation can be used. :param mat: the matrix to create the surface of. :type mat: np.ndarray :param transformer: function that transforms the matrix to a valid color matrix, i.e. it must have 3dimension, were the 3rd dimension are the color channels. For each channel a value between 0 and 255 is allowed :type transformer: Callable[np.ndarray[np.ndarray]]""" return pygame.pixelcopy.make_surface(transformer(mat.transpose()) if transformer is not None else mat.transpose())
KnorrFG/pyparadigm
pyparadigm/extras.py
mat_to_surface
python
def mat_to_surface(mat: np.ndarray, transformer=to_24bit_gray): return pygame.pixelcopy.make_surface(transformer(mat.transpose()) if transformer is not None else mat.transpose())
Can be used to create a pygame.Surface from a 2d numpy array. By default a grey image with scaled colors is returned, but using the transformer argument any transformation can be used. :param mat: the matrix to create the surface of. :type mat: np.ndarray :param transformer: function that transforms the matrix to a valid color matrix, i.e. it must have 3dimension, were the 3rd dimension are the color channels. For each channel a value between 0 and 255 is allowed :type transformer: Callable[np.ndarray[np.ndarray]]
train
https://github.com/KnorrFG/pyparadigm/blob/69944cdf3ce2f6414ae1aa1d27a0d8c6e5fb3fd3/pyparadigm/extras.py#L34-L49
[ "def to_24bit_gray(mat: np.ndarray):\n \"\"\"returns a matrix that contains RGB channels, and colors scaled\n from 0 to 255\"\"\"\n return np.repeat(np.expand_dims(_normalize(mat), axis=2), 3, axis=2)\n" ]
"""Using functionality from this file requires extra dependencies.""" import warnings try: import numpy as np from matplotlib import cm except ImportError: warnings.warn("This module requires numpy and matplotlib, which seem to be missing.") import contextlib with contextlib.redirect_stdout(None): import pygame def _normalize(mat: np.ndarray): """rescales a numpy array, so that min is 0 and max is 255""" return ((mat - mat.min()) * (255 / mat.max())).astype(np.uint8) def to_24bit_gray(mat: np.ndarray): """returns a matrix that contains RGB channels, and colors scaled from 0 to 255""" return np.repeat(np.expand_dims(_normalize(mat), axis=2), 3, axis=2) def apply_color_map(name: str, mat: np.ndarray = None): """returns an RGB matrix scaled by a matplotlib color map""" def apply_map(mat): return (cm.get_cmap(name)(_normalize(mat))[:, :, :3] * 255).astype(np.uint8) return apply_map if mat is None else apply_map(mat)
KnorrFG/pyparadigm
pyparadigm/eventlistener.py
Handler.key_press
python
def key_press(keys): return lambda e: e.key if e.type == pygame.KEYDOWN \ and e.key in keys else EventConsumerInfo.DONT_CARE
returns a handler that can be used with EventListener.listen() and returns when a key in keys is pressed
train
https://github.com/KnorrFG/pyparadigm/blob/69944cdf3ce2f6414ae1aa1d27a0d8c6e5fb3fd3/pyparadigm/eventlistener.py#L70-L74
null
class Handler: @staticmethod @staticmethod def unicode_char(ignored_chars=None): """returns a handler that listens for unicode characters""" return lambda e: e.unicode if e.type == pygame.KEYDOWN \ and ((ignored_chars is None) or (e.unicode not in ignored_chars))\ else EventConsumerInfo.DONT_CARE
KnorrFG/pyparadigm
pyparadigm/eventlistener.py
Handler.unicode_char
python
def unicode_char(ignored_chars=None): return lambda e: e.unicode if e.type == pygame.KEYDOWN \ and ((ignored_chars is None) or (e.unicode not in ignored_chars))\ else EventConsumerInfo.DONT_CARE
returns a handler that listens for unicode characters
train
https://github.com/KnorrFG/pyparadigm/blob/69944cdf3ce2f6414ae1aa1d27a0d8c6e5fb3fd3/pyparadigm/eventlistener.py#L77-L82
null
class Handler: @staticmethod def key_press(keys): """returns a handler that can be used with EventListener.listen() and returns when a key in keys is pressed""" return lambda e: e.key if e.type == pygame.KEYDOWN \ and e.key in keys else EventConsumerInfo.DONT_CARE @staticmethod
KnorrFG/pyparadigm
pyparadigm/eventlistener.py
EventListener.mouse_area
python
def mouse_area(self, handler, group=0, ident=None): key = ident or id(handler) if key not in self.mouse_proxies[group]: self.mouse_proxies[group][key] = MouseProxy(handler, ident) return self.mouse_proxies[group][key]
Adds a new MouseProxy for the given group to the EventListener.mouse_proxies dict if it is not in there yet, and returns the (new) MouseProxy. In listen() all entries in the current group of mouse_proxies are used.
train
https://github.com/KnorrFG/pyparadigm/blob/69944cdf3ce2f6414ae1aa1d27a0d8c6e5fb3fd3/pyparadigm/eventlistener.py#L167-L175
null
class EventListener(object): """ :param permanent_handlers: iterable of permanent handlers :type permanent_handlers: iterable :param use_ctrl_c_handler: specifies whether a handler that quits the script when ctrl + c is pressed should be used :type use_ctrl_c_handler: Bool """ _mod_keys = {KMOD_LSHIFT, KMOD_RSHIFT, KMOD_SHIFT, KMOD_CAPS, KMOD_LCTRL, KMOD_RCTRL, KMOD_CTRL, KMOD_LALT, KMOD_RALT, KMOD_ALT, KMOD_LMETA, KMOD_RMETA, KMOD_META, KMOD_NUM, KMOD_MODE} @staticmethod def _contained_modifiers(mods, mods_of_interes=_mod_keys): return frozenset(mod for mod in mods_of_interes if mod & mods) @staticmethod def _exit_on_ctrl_c(event): if event.type == pygame.KEYDOWN \ and event.key == pygame.K_c \ and pygame.key.get_mods() & pygame.KMOD_CTRL: pygame.quit() exit(1) else: return EventConsumerInfo.DONT_CARE def __init__(self, permanent_handlers=None, use_ctrl_c_handler=True): self._current_q = [] self.mouse_proxies = defaultdict(dict) self.proxy_group = 0 if use_ctrl_c_handler: self.permanent_handlers = ( EventListener._exit_on_ctrl_c, ) if permanent_handlers: self.permanent_handlers += permanent_handlers else: self.permanent_handlers = permanent_handlers or [] def _get_q(self): self._current_q = itt.chain(self._current_q, pygame.event.get()) return self._current_q def group(self, group): """sets current mouse proxy group and returns self. Enables lines like el.group(1).wait_for_keys(...)""" self.proxy_group = group return self def listen(self, *temporary_handlers): """When listen() is called all queued pygame.Events will be passed to all registered listeners. There are two ways to register a listener: 1. as a permanent listener, that is always executed for every event. These are registered by passing the handler-functions during construction 2. as a temporary listener, that will only be executed during the current call to listen(). These are registered by passing the handler functions as arguments to listen() When a handler is called it can provoke three different reactions through its return value. 1. It can return EventConsumerInfo.DONT_CARE in which case the EventListener will pass the event to the next handler in line, or go to the next event, if the last handler was called. 2. It can return EventConsumerInfo.CONSUMED in which case the event will not be passed to following handlers, and the next event in line will be processed. 3. It can return anything else (including None, which will be returned if no return value is specified) in this case the listen()-method will return the result of the handler. Therefore all permanent handlers should usually return EventConsumerInfo.DONT_CARE """ funcs = tuple(itt.chain(self.permanent_handlers, (proxy.listener for proxy in self.mouse_proxies[self.proxy_group].values()), temporary_handlers)) for event in self._get_q(): for func in funcs: ret = func(event) if ret == EventConsumerInfo.CONSUMED: break if ret == EventConsumerInfo.DONT_CARE: continue else: return ret def listen_until_return(self, *temporary_handlers, timeout=0): """Calls listen repeatedly until listen returns something else than None. Then returns listen's result. If timeout is not zero listen_until_return stops after timeout seconds and returns None.""" start = time.time() while timeout == 0 or time.time() - start < timeout: res = self.listen(*temporary_handlers) if res is not None: return res def wait_for_n_keypresses(self, key, n=1): """Waits till one key was pressed n times. :param key: the key to be pressed as defined by pygame. E.g. pygame.K_LEFT for the left arrow key :type key: int :param n: number of repetitions till the function returns :type n: int """ my_const = "key_consumed" counter = 0 def keypress_listener(e): return my_const \ if e.type == pygame.KEYDOWN and e.key == key \ else EventConsumerInfo.DONT_CARE while counter < n: if self.listen(keypress_listener) == my_const: counter += 1 def wait_for_keys(self, *keys, timeout=0): """Waits until one of the specified keys was pressed, and returns which key was pressed. :param keys: iterable of integers of pygame-keycodes, or simply multiple keys passed via multiple arguments :type keys: iterable :param timeout: number of seconds to wait till the function returns :type timeout: float :returns: The keycode of the pressed key, or None in case of timeout :rtype: int """ if len(keys) == 1 and _is_iterable(keys[0]): keys = keys[0] return self.listen_until_return(Handler.key_press(keys), timeout=timeout) def wait_for_keys_modified(self, *keys, modifiers_to_check=_mod_keys, timeout=0): """The same as wait_for_keys, but returns a frozen_set which contains the pressed key, and the modifier keys. :param modifiers_to_check: iterable of modifiers for which the function will check whether they are pressed :type modifiers: Iterable[int]""" set_mods = pygame.key.get_mods() return frozenset.union( frozenset([self.wait_for_keys(*keys, timeout=timeout)]), EventListener._contained_modifiers(set_mods, modifiers_to_check)) def wait_for_seconds(self, seconds): """basically time.sleep() but in the mean-time the permanent handlers are executed""" self.listen_until_return(timeout=seconds) def wait_for_unicode_char(self, ignored_chars=None, timeout=0): """Returns a str that contains the single character that was pressed. This already respects modifier keys and keyboard layouts. If timeout is not none and no key is pressed within the specified timeout, None is returned. If a key is ingnored_chars it will be ignored. As argument for irgnored_chars any object that has a __contains__ method can be used, e.g. a string, a set, a list, etc""" return self.listen_until_return(Handler.unicode_char(ignored_chars), timeout=timeout)
KnorrFG/pyparadigm
pyparadigm/eventlistener.py
EventListener.listen
python
def listen(self, *temporary_handlers): funcs = tuple(itt.chain(self.permanent_handlers, (proxy.listener for proxy in self.mouse_proxies[self.proxy_group].values()), temporary_handlers)) for event in self._get_q(): for func in funcs: ret = func(event) if ret == EventConsumerInfo.CONSUMED: break if ret == EventConsumerInfo.DONT_CARE: continue else: return ret
When listen() is called all queued pygame.Events will be passed to all registered listeners. There are two ways to register a listener: 1. as a permanent listener, that is always executed for every event. These are registered by passing the handler-functions during construction 2. as a temporary listener, that will only be executed during the current call to listen(). These are registered by passing the handler functions as arguments to listen() When a handler is called it can provoke three different reactions through its return value. 1. It can return EventConsumerInfo.DONT_CARE in which case the EventListener will pass the event to the next handler in line, or go to the next event, if the last handler was called. 2. It can return EventConsumerInfo.CONSUMED in which case the event will not be passed to following handlers, and the next event in line will be processed. 3. It can return anything else (including None, which will be returned if no return value is specified) in this case the listen()-method will return the result of the handler. Therefore all permanent handlers should usually return EventConsumerInfo.DONT_CARE
train
https://github.com/KnorrFG/pyparadigm/blob/69944cdf3ce2f6414ae1aa1d27a0d8c6e5fb3fd3/pyparadigm/eventlistener.py#L183-L225
[ "def _get_q(self):\n self._current_q = itt.chain(self._current_q, pygame.event.get())\n return self._current_q\n" ]
class EventListener(object): """ :param permanent_handlers: iterable of permanent handlers :type permanent_handlers: iterable :param use_ctrl_c_handler: specifies whether a handler that quits the script when ctrl + c is pressed should be used :type use_ctrl_c_handler: Bool """ _mod_keys = {KMOD_LSHIFT, KMOD_RSHIFT, KMOD_SHIFT, KMOD_CAPS, KMOD_LCTRL, KMOD_RCTRL, KMOD_CTRL, KMOD_LALT, KMOD_RALT, KMOD_ALT, KMOD_LMETA, KMOD_RMETA, KMOD_META, KMOD_NUM, KMOD_MODE} @staticmethod def _contained_modifiers(mods, mods_of_interes=_mod_keys): return frozenset(mod for mod in mods_of_interes if mod & mods) @staticmethod def _exit_on_ctrl_c(event): if event.type == pygame.KEYDOWN \ and event.key == pygame.K_c \ and pygame.key.get_mods() & pygame.KMOD_CTRL: pygame.quit() exit(1) else: return EventConsumerInfo.DONT_CARE def __init__(self, permanent_handlers=None, use_ctrl_c_handler=True): self._current_q = [] self.mouse_proxies = defaultdict(dict) self.proxy_group = 0 if use_ctrl_c_handler: self.permanent_handlers = ( EventListener._exit_on_ctrl_c, ) if permanent_handlers: self.permanent_handlers += permanent_handlers else: self.permanent_handlers = permanent_handlers or [] def _get_q(self): self._current_q = itt.chain(self._current_q, pygame.event.get()) return self._current_q def mouse_area(self, handler, group=0, ident=None): """Adds a new MouseProxy for the given group to the EventListener.mouse_proxies dict if it is not in there yet, and returns the (new) MouseProxy. In listen() all entries in the current group of mouse_proxies are used.""" key = ident or id(handler) if key not in self.mouse_proxies[group]: self.mouse_proxies[group][key] = MouseProxy(handler, ident) return self.mouse_proxies[group][key] def group(self, group): """sets current mouse proxy group and returns self. Enables lines like el.group(1).wait_for_keys(...)""" self.proxy_group = group return self def listen_until_return(self, *temporary_handlers, timeout=0): """Calls listen repeatedly until listen returns something else than None. Then returns listen's result. If timeout is not zero listen_until_return stops after timeout seconds and returns None.""" start = time.time() while timeout == 0 or time.time() - start < timeout: res = self.listen(*temporary_handlers) if res is not None: return res def wait_for_n_keypresses(self, key, n=1): """Waits till one key was pressed n times. :param key: the key to be pressed as defined by pygame. E.g. pygame.K_LEFT for the left arrow key :type key: int :param n: number of repetitions till the function returns :type n: int """ my_const = "key_consumed" counter = 0 def keypress_listener(e): return my_const \ if e.type == pygame.KEYDOWN and e.key == key \ else EventConsumerInfo.DONT_CARE while counter < n: if self.listen(keypress_listener) == my_const: counter += 1 def wait_for_keys(self, *keys, timeout=0): """Waits until one of the specified keys was pressed, and returns which key was pressed. :param keys: iterable of integers of pygame-keycodes, or simply multiple keys passed via multiple arguments :type keys: iterable :param timeout: number of seconds to wait till the function returns :type timeout: float :returns: The keycode of the pressed key, or None in case of timeout :rtype: int """ if len(keys) == 1 and _is_iterable(keys[0]): keys = keys[0] return self.listen_until_return(Handler.key_press(keys), timeout=timeout) def wait_for_keys_modified(self, *keys, modifiers_to_check=_mod_keys, timeout=0): """The same as wait_for_keys, but returns a frozen_set which contains the pressed key, and the modifier keys. :param modifiers_to_check: iterable of modifiers for which the function will check whether they are pressed :type modifiers: Iterable[int]""" set_mods = pygame.key.get_mods() return frozenset.union( frozenset([self.wait_for_keys(*keys, timeout=timeout)]), EventListener._contained_modifiers(set_mods, modifiers_to_check)) def wait_for_seconds(self, seconds): """basically time.sleep() but in the mean-time the permanent handlers are executed""" self.listen_until_return(timeout=seconds) def wait_for_unicode_char(self, ignored_chars=None, timeout=0): """Returns a str that contains the single character that was pressed. This already respects modifier keys and keyboard layouts. If timeout is not none and no key is pressed within the specified timeout, None is returned. If a key is ingnored_chars it will be ignored. As argument for irgnored_chars any object that has a __contains__ method can be used, e.g. a string, a set, a list, etc""" return self.listen_until_return(Handler.unicode_char(ignored_chars), timeout=timeout)
KnorrFG/pyparadigm
pyparadigm/eventlistener.py
EventListener.listen_until_return
python
def listen_until_return(self, *temporary_handlers, timeout=0): start = time.time() while timeout == 0 or time.time() - start < timeout: res = self.listen(*temporary_handlers) if res is not None: return res
Calls listen repeatedly until listen returns something else than None. Then returns listen's result. If timeout is not zero listen_until_return stops after timeout seconds and returns None.
train
https://github.com/KnorrFG/pyparadigm/blob/69944cdf3ce2f6414ae1aa1d27a0d8c6e5fb3fd3/pyparadigm/eventlistener.py#L227-L235
[ "def listen(self, *temporary_handlers):\n \"\"\"When listen() is called all queued pygame.Events will be passed to all\n registered listeners. There are two ways to register a listener:\n\n 1. as a permanent listener, that is always executed for every event. These\n are registered by passing the han...
class EventListener(object): """ :param permanent_handlers: iterable of permanent handlers :type permanent_handlers: iterable :param use_ctrl_c_handler: specifies whether a handler that quits the script when ctrl + c is pressed should be used :type use_ctrl_c_handler: Bool """ _mod_keys = {KMOD_LSHIFT, KMOD_RSHIFT, KMOD_SHIFT, KMOD_CAPS, KMOD_LCTRL, KMOD_RCTRL, KMOD_CTRL, KMOD_LALT, KMOD_RALT, KMOD_ALT, KMOD_LMETA, KMOD_RMETA, KMOD_META, KMOD_NUM, KMOD_MODE} @staticmethod def _contained_modifiers(mods, mods_of_interes=_mod_keys): return frozenset(mod for mod in mods_of_interes if mod & mods) @staticmethod def _exit_on_ctrl_c(event): if event.type == pygame.KEYDOWN \ and event.key == pygame.K_c \ and pygame.key.get_mods() & pygame.KMOD_CTRL: pygame.quit() exit(1) else: return EventConsumerInfo.DONT_CARE def __init__(self, permanent_handlers=None, use_ctrl_c_handler=True): self._current_q = [] self.mouse_proxies = defaultdict(dict) self.proxy_group = 0 if use_ctrl_c_handler: self.permanent_handlers = ( EventListener._exit_on_ctrl_c, ) if permanent_handlers: self.permanent_handlers += permanent_handlers else: self.permanent_handlers = permanent_handlers or [] def _get_q(self): self._current_q = itt.chain(self._current_q, pygame.event.get()) return self._current_q def mouse_area(self, handler, group=0, ident=None): """Adds a new MouseProxy for the given group to the EventListener.mouse_proxies dict if it is not in there yet, and returns the (new) MouseProxy. In listen() all entries in the current group of mouse_proxies are used.""" key = ident or id(handler) if key not in self.mouse_proxies[group]: self.mouse_proxies[group][key] = MouseProxy(handler, ident) return self.mouse_proxies[group][key] def group(self, group): """sets current mouse proxy group and returns self. Enables lines like el.group(1).wait_for_keys(...)""" self.proxy_group = group return self def listen(self, *temporary_handlers): """When listen() is called all queued pygame.Events will be passed to all registered listeners. There are two ways to register a listener: 1. as a permanent listener, that is always executed for every event. These are registered by passing the handler-functions during construction 2. as a temporary listener, that will only be executed during the current call to listen(). These are registered by passing the handler functions as arguments to listen() When a handler is called it can provoke three different reactions through its return value. 1. It can return EventConsumerInfo.DONT_CARE in which case the EventListener will pass the event to the next handler in line, or go to the next event, if the last handler was called. 2. It can return EventConsumerInfo.CONSUMED in which case the event will not be passed to following handlers, and the next event in line will be processed. 3. It can return anything else (including None, which will be returned if no return value is specified) in this case the listen()-method will return the result of the handler. Therefore all permanent handlers should usually return EventConsumerInfo.DONT_CARE """ funcs = tuple(itt.chain(self.permanent_handlers, (proxy.listener for proxy in self.mouse_proxies[self.proxy_group].values()), temporary_handlers)) for event in self._get_q(): for func in funcs: ret = func(event) if ret == EventConsumerInfo.CONSUMED: break if ret == EventConsumerInfo.DONT_CARE: continue else: return ret def wait_for_n_keypresses(self, key, n=1): """Waits till one key was pressed n times. :param key: the key to be pressed as defined by pygame. E.g. pygame.K_LEFT for the left arrow key :type key: int :param n: number of repetitions till the function returns :type n: int """ my_const = "key_consumed" counter = 0 def keypress_listener(e): return my_const \ if e.type == pygame.KEYDOWN and e.key == key \ else EventConsumerInfo.DONT_CARE while counter < n: if self.listen(keypress_listener) == my_const: counter += 1 def wait_for_keys(self, *keys, timeout=0): """Waits until one of the specified keys was pressed, and returns which key was pressed. :param keys: iterable of integers of pygame-keycodes, or simply multiple keys passed via multiple arguments :type keys: iterable :param timeout: number of seconds to wait till the function returns :type timeout: float :returns: The keycode of the pressed key, or None in case of timeout :rtype: int """ if len(keys) == 1 and _is_iterable(keys[0]): keys = keys[0] return self.listen_until_return(Handler.key_press(keys), timeout=timeout) def wait_for_keys_modified(self, *keys, modifiers_to_check=_mod_keys, timeout=0): """The same as wait_for_keys, but returns a frozen_set which contains the pressed key, and the modifier keys. :param modifiers_to_check: iterable of modifiers for which the function will check whether they are pressed :type modifiers: Iterable[int]""" set_mods = pygame.key.get_mods() return frozenset.union( frozenset([self.wait_for_keys(*keys, timeout=timeout)]), EventListener._contained_modifiers(set_mods, modifiers_to_check)) def wait_for_seconds(self, seconds): """basically time.sleep() but in the mean-time the permanent handlers are executed""" self.listen_until_return(timeout=seconds) def wait_for_unicode_char(self, ignored_chars=None, timeout=0): """Returns a str that contains the single character that was pressed. This already respects modifier keys and keyboard layouts. If timeout is not none and no key is pressed within the specified timeout, None is returned. If a key is ingnored_chars it will be ignored. As argument for irgnored_chars any object that has a __contains__ method can be used, e.g. a string, a set, a list, etc""" return self.listen_until_return(Handler.unicode_char(ignored_chars), timeout=timeout)
KnorrFG/pyparadigm
pyparadigm/eventlistener.py
EventListener.wait_for_n_keypresses
python
def wait_for_n_keypresses(self, key, n=1): my_const = "key_consumed" counter = 0 def keypress_listener(e): return my_const \ if e.type == pygame.KEYDOWN and e.key == key \ else EventConsumerInfo.DONT_CARE while counter < n: if self.listen(keypress_listener) == my_const: counter += 1
Waits till one key was pressed n times. :param key: the key to be pressed as defined by pygame. E.g. pygame.K_LEFT for the left arrow key :type key: int :param n: number of repetitions till the function returns :type n: int
train
https://github.com/KnorrFG/pyparadigm/blob/69944cdf3ce2f6414ae1aa1d27a0d8c6e5fb3fd3/pyparadigm/eventlistener.py#L237-L255
[ "def listen(self, *temporary_handlers):\n \"\"\"When listen() is called all queued pygame.Events will be passed to all\n registered listeners. There are two ways to register a listener:\n\n 1. as a permanent listener, that is always executed for every event. These\n are registered by passing the han...
class EventListener(object): """ :param permanent_handlers: iterable of permanent handlers :type permanent_handlers: iterable :param use_ctrl_c_handler: specifies whether a handler that quits the script when ctrl + c is pressed should be used :type use_ctrl_c_handler: Bool """ _mod_keys = {KMOD_LSHIFT, KMOD_RSHIFT, KMOD_SHIFT, KMOD_CAPS, KMOD_LCTRL, KMOD_RCTRL, KMOD_CTRL, KMOD_LALT, KMOD_RALT, KMOD_ALT, KMOD_LMETA, KMOD_RMETA, KMOD_META, KMOD_NUM, KMOD_MODE} @staticmethod def _contained_modifiers(mods, mods_of_interes=_mod_keys): return frozenset(mod for mod in mods_of_interes if mod & mods) @staticmethod def _exit_on_ctrl_c(event): if event.type == pygame.KEYDOWN \ and event.key == pygame.K_c \ and pygame.key.get_mods() & pygame.KMOD_CTRL: pygame.quit() exit(1) else: return EventConsumerInfo.DONT_CARE def __init__(self, permanent_handlers=None, use_ctrl_c_handler=True): self._current_q = [] self.mouse_proxies = defaultdict(dict) self.proxy_group = 0 if use_ctrl_c_handler: self.permanent_handlers = ( EventListener._exit_on_ctrl_c, ) if permanent_handlers: self.permanent_handlers += permanent_handlers else: self.permanent_handlers = permanent_handlers or [] def _get_q(self): self._current_q = itt.chain(self._current_q, pygame.event.get()) return self._current_q def mouse_area(self, handler, group=0, ident=None): """Adds a new MouseProxy for the given group to the EventListener.mouse_proxies dict if it is not in there yet, and returns the (new) MouseProxy. In listen() all entries in the current group of mouse_proxies are used.""" key = ident or id(handler) if key not in self.mouse_proxies[group]: self.mouse_proxies[group][key] = MouseProxy(handler, ident) return self.mouse_proxies[group][key] def group(self, group): """sets current mouse proxy group and returns self. Enables lines like el.group(1).wait_for_keys(...)""" self.proxy_group = group return self def listen(self, *temporary_handlers): """When listen() is called all queued pygame.Events will be passed to all registered listeners. There are two ways to register a listener: 1. as a permanent listener, that is always executed for every event. These are registered by passing the handler-functions during construction 2. as a temporary listener, that will only be executed during the current call to listen(). These are registered by passing the handler functions as arguments to listen() When a handler is called it can provoke three different reactions through its return value. 1. It can return EventConsumerInfo.DONT_CARE in which case the EventListener will pass the event to the next handler in line, or go to the next event, if the last handler was called. 2. It can return EventConsumerInfo.CONSUMED in which case the event will not be passed to following handlers, and the next event in line will be processed. 3. It can return anything else (including None, which will be returned if no return value is specified) in this case the listen()-method will return the result of the handler. Therefore all permanent handlers should usually return EventConsumerInfo.DONT_CARE """ funcs = tuple(itt.chain(self.permanent_handlers, (proxy.listener for proxy in self.mouse_proxies[self.proxy_group].values()), temporary_handlers)) for event in self._get_q(): for func in funcs: ret = func(event) if ret == EventConsumerInfo.CONSUMED: break if ret == EventConsumerInfo.DONT_CARE: continue else: return ret def listen_until_return(self, *temporary_handlers, timeout=0): """Calls listen repeatedly until listen returns something else than None. Then returns listen's result. If timeout is not zero listen_until_return stops after timeout seconds and returns None.""" start = time.time() while timeout == 0 or time.time() - start < timeout: res = self.listen(*temporary_handlers) if res is not None: return res def wait_for_keys(self, *keys, timeout=0): """Waits until one of the specified keys was pressed, and returns which key was pressed. :param keys: iterable of integers of pygame-keycodes, or simply multiple keys passed via multiple arguments :type keys: iterable :param timeout: number of seconds to wait till the function returns :type timeout: float :returns: The keycode of the pressed key, or None in case of timeout :rtype: int """ if len(keys) == 1 and _is_iterable(keys[0]): keys = keys[0] return self.listen_until_return(Handler.key_press(keys), timeout=timeout) def wait_for_keys_modified(self, *keys, modifiers_to_check=_mod_keys, timeout=0): """The same as wait_for_keys, but returns a frozen_set which contains the pressed key, and the modifier keys. :param modifiers_to_check: iterable of modifiers for which the function will check whether they are pressed :type modifiers: Iterable[int]""" set_mods = pygame.key.get_mods() return frozenset.union( frozenset([self.wait_for_keys(*keys, timeout=timeout)]), EventListener._contained_modifiers(set_mods, modifiers_to_check)) def wait_for_seconds(self, seconds): """basically time.sleep() but in the mean-time the permanent handlers are executed""" self.listen_until_return(timeout=seconds) def wait_for_unicode_char(self, ignored_chars=None, timeout=0): """Returns a str that contains the single character that was pressed. This already respects modifier keys and keyboard layouts. If timeout is not none and no key is pressed within the specified timeout, None is returned. If a key is ingnored_chars it will be ignored. As argument for irgnored_chars any object that has a __contains__ method can be used, e.g. a string, a set, a list, etc""" return self.listen_until_return(Handler.unicode_char(ignored_chars), timeout=timeout)
KnorrFG/pyparadigm
pyparadigm/eventlistener.py
EventListener.wait_for_keys
python
def wait_for_keys(self, *keys, timeout=0): if len(keys) == 1 and _is_iterable(keys[0]): keys = keys[0] return self.listen_until_return(Handler.key_press(keys), timeout=timeout)
Waits until one of the specified keys was pressed, and returns which key was pressed. :param keys: iterable of integers of pygame-keycodes, or simply multiple keys passed via multiple arguments :type keys: iterable :param timeout: number of seconds to wait till the function returns :type timeout: float :returns: The keycode of the pressed key, or None in case of timeout :rtype: int
train
https://github.com/KnorrFG/pyparadigm/blob/69944cdf3ce2f6414ae1aa1d27a0d8c6e5fb3fd3/pyparadigm/eventlistener.py#L257-L273
[ "def _is_iterable(val):\n try:\n some_object_iterator = iter(val)\n return True\n except TypeError as te:\n return False\n", "def key_press(keys):\n \"\"\"returns a handler that can be used with EventListener.listen()\n and returns when a key in keys is pressed\"\"\"\n return l...
class EventListener(object): """ :param permanent_handlers: iterable of permanent handlers :type permanent_handlers: iterable :param use_ctrl_c_handler: specifies whether a handler that quits the script when ctrl + c is pressed should be used :type use_ctrl_c_handler: Bool """ _mod_keys = {KMOD_LSHIFT, KMOD_RSHIFT, KMOD_SHIFT, KMOD_CAPS, KMOD_LCTRL, KMOD_RCTRL, KMOD_CTRL, KMOD_LALT, KMOD_RALT, KMOD_ALT, KMOD_LMETA, KMOD_RMETA, KMOD_META, KMOD_NUM, KMOD_MODE} @staticmethod def _contained_modifiers(mods, mods_of_interes=_mod_keys): return frozenset(mod for mod in mods_of_interes if mod & mods) @staticmethod def _exit_on_ctrl_c(event): if event.type == pygame.KEYDOWN \ and event.key == pygame.K_c \ and pygame.key.get_mods() & pygame.KMOD_CTRL: pygame.quit() exit(1) else: return EventConsumerInfo.DONT_CARE def __init__(self, permanent_handlers=None, use_ctrl_c_handler=True): self._current_q = [] self.mouse_proxies = defaultdict(dict) self.proxy_group = 0 if use_ctrl_c_handler: self.permanent_handlers = ( EventListener._exit_on_ctrl_c, ) if permanent_handlers: self.permanent_handlers += permanent_handlers else: self.permanent_handlers = permanent_handlers or [] def _get_q(self): self._current_q = itt.chain(self._current_q, pygame.event.get()) return self._current_q def mouse_area(self, handler, group=0, ident=None): """Adds a new MouseProxy for the given group to the EventListener.mouse_proxies dict if it is not in there yet, and returns the (new) MouseProxy. In listen() all entries in the current group of mouse_proxies are used.""" key = ident or id(handler) if key not in self.mouse_proxies[group]: self.mouse_proxies[group][key] = MouseProxy(handler, ident) return self.mouse_proxies[group][key] def group(self, group): """sets current mouse proxy group and returns self. Enables lines like el.group(1).wait_for_keys(...)""" self.proxy_group = group return self def listen(self, *temporary_handlers): """When listen() is called all queued pygame.Events will be passed to all registered listeners. There are two ways to register a listener: 1. as a permanent listener, that is always executed for every event. These are registered by passing the handler-functions during construction 2. as a temporary listener, that will only be executed during the current call to listen(). These are registered by passing the handler functions as arguments to listen() When a handler is called it can provoke three different reactions through its return value. 1. It can return EventConsumerInfo.DONT_CARE in which case the EventListener will pass the event to the next handler in line, or go to the next event, if the last handler was called. 2. It can return EventConsumerInfo.CONSUMED in which case the event will not be passed to following handlers, and the next event in line will be processed. 3. It can return anything else (including None, which will be returned if no return value is specified) in this case the listen()-method will return the result of the handler. Therefore all permanent handlers should usually return EventConsumerInfo.DONT_CARE """ funcs = tuple(itt.chain(self.permanent_handlers, (proxy.listener for proxy in self.mouse_proxies[self.proxy_group].values()), temporary_handlers)) for event in self._get_q(): for func in funcs: ret = func(event) if ret == EventConsumerInfo.CONSUMED: break if ret == EventConsumerInfo.DONT_CARE: continue else: return ret def listen_until_return(self, *temporary_handlers, timeout=0): """Calls listen repeatedly until listen returns something else than None. Then returns listen's result. If timeout is not zero listen_until_return stops after timeout seconds and returns None.""" start = time.time() while timeout == 0 or time.time() - start < timeout: res = self.listen(*temporary_handlers) if res is not None: return res def wait_for_n_keypresses(self, key, n=1): """Waits till one key was pressed n times. :param key: the key to be pressed as defined by pygame. E.g. pygame.K_LEFT for the left arrow key :type key: int :param n: number of repetitions till the function returns :type n: int """ my_const = "key_consumed" counter = 0 def keypress_listener(e): return my_const \ if e.type == pygame.KEYDOWN and e.key == key \ else EventConsumerInfo.DONT_CARE while counter < n: if self.listen(keypress_listener) == my_const: counter += 1 def wait_for_keys_modified(self, *keys, modifiers_to_check=_mod_keys, timeout=0): """The same as wait_for_keys, but returns a frozen_set which contains the pressed key, and the modifier keys. :param modifiers_to_check: iterable of modifiers for which the function will check whether they are pressed :type modifiers: Iterable[int]""" set_mods = pygame.key.get_mods() return frozenset.union( frozenset([self.wait_for_keys(*keys, timeout=timeout)]), EventListener._contained_modifiers(set_mods, modifiers_to_check)) def wait_for_seconds(self, seconds): """basically time.sleep() but in the mean-time the permanent handlers are executed""" self.listen_until_return(timeout=seconds) def wait_for_unicode_char(self, ignored_chars=None, timeout=0): """Returns a str that contains the single character that was pressed. This already respects modifier keys and keyboard layouts. If timeout is not none and no key is pressed within the specified timeout, None is returned. If a key is ingnored_chars it will be ignored. As argument for irgnored_chars any object that has a __contains__ method can be used, e.g. a string, a set, a list, etc""" return self.listen_until_return(Handler.unicode_char(ignored_chars), timeout=timeout)
KnorrFG/pyparadigm
pyparadigm/eventlistener.py
EventListener.wait_for_keys_modified
python
def wait_for_keys_modified(self, *keys, modifiers_to_check=_mod_keys, timeout=0): set_mods = pygame.key.get_mods() return frozenset.union( frozenset([self.wait_for_keys(*keys, timeout=timeout)]), EventListener._contained_modifiers(set_mods, modifiers_to_check))
The same as wait_for_keys, but returns a frozen_set which contains the pressed key, and the modifier keys. :param modifiers_to_check: iterable of modifiers for which the function will check whether they are pressed :type modifiers: Iterable[int]
train
https://github.com/KnorrFG/pyparadigm/blob/69944cdf3ce2f6414ae1aa1d27a0d8c6e5fb3fd3/pyparadigm/eventlistener.py#L275-L288
[ "def _contained_modifiers(mods, mods_of_interes=_mod_keys):\n return frozenset(mod for mod in mods_of_interes if mod & mods)\n", "def wait_for_keys(self, *keys, timeout=0):\n \"\"\"Waits until one of the specified keys was pressed, and returns \n which key was pressed.\n\n :param keys: iterable of int...
class EventListener(object): """ :param permanent_handlers: iterable of permanent handlers :type permanent_handlers: iterable :param use_ctrl_c_handler: specifies whether a handler that quits the script when ctrl + c is pressed should be used :type use_ctrl_c_handler: Bool """ _mod_keys = {KMOD_LSHIFT, KMOD_RSHIFT, KMOD_SHIFT, KMOD_CAPS, KMOD_LCTRL, KMOD_RCTRL, KMOD_CTRL, KMOD_LALT, KMOD_RALT, KMOD_ALT, KMOD_LMETA, KMOD_RMETA, KMOD_META, KMOD_NUM, KMOD_MODE} @staticmethod def _contained_modifiers(mods, mods_of_interes=_mod_keys): return frozenset(mod for mod in mods_of_interes if mod & mods) @staticmethod def _exit_on_ctrl_c(event): if event.type == pygame.KEYDOWN \ and event.key == pygame.K_c \ and pygame.key.get_mods() & pygame.KMOD_CTRL: pygame.quit() exit(1) else: return EventConsumerInfo.DONT_CARE def __init__(self, permanent_handlers=None, use_ctrl_c_handler=True): self._current_q = [] self.mouse_proxies = defaultdict(dict) self.proxy_group = 0 if use_ctrl_c_handler: self.permanent_handlers = ( EventListener._exit_on_ctrl_c, ) if permanent_handlers: self.permanent_handlers += permanent_handlers else: self.permanent_handlers = permanent_handlers or [] def _get_q(self): self._current_q = itt.chain(self._current_q, pygame.event.get()) return self._current_q def mouse_area(self, handler, group=0, ident=None): """Adds a new MouseProxy for the given group to the EventListener.mouse_proxies dict if it is not in there yet, and returns the (new) MouseProxy. In listen() all entries in the current group of mouse_proxies are used.""" key = ident or id(handler) if key not in self.mouse_proxies[group]: self.mouse_proxies[group][key] = MouseProxy(handler, ident) return self.mouse_proxies[group][key] def group(self, group): """sets current mouse proxy group and returns self. Enables lines like el.group(1).wait_for_keys(...)""" self.proxy_group = group return self def listen(self, *temporary_handlers): """When listen() is called all queued pygame.Events will be passed to all registered listeners. There are two ways to register a listener: 1. as a permanent listener, that is always executed for every event. These are registered by passing the handler-functions during construction 2. as a temporary listener, that will only be executed during the current call to listen(). These are registered by passing the handler functions as arguments to listen() When a handler is called it can provoke three different reactions through its return value. 1. It can return EventConsumerInfo.DONT_CARE in which case the EventListener will pass the event to the next handler in line, or go to the next event, if the last handler was called. 2. It can return EventConsumerInfo.CONSUMED in which case the event will not be passed to following handlers, and the next event in line will be processed. 3. It can return anything else (including None, which will be returned if no return value is specified) in this case the listen()-method will return the result of the handler. Therefore all permanent handlers should usually return EventConsumerInfo.DONT_CARE """ funcs = tuple(itt.chain(self.permanent_handlers, (proxy.listener for proxy in self.mouse_proxies[self.proxy_group].values()), temporary_handlers)) for event in self._get_q(): for func in funcs: ret = func(event) if ret == EventConsumerInfo.CONSUMED: break if ret == EventConsumerInfo.DONT_CARE: continue else: return ret def listen_until_return(self, *temporary_handlers, timeout=0): """Calls listen repeatedly until listen returns something else than None. Then returns listen's result. If timeout is not zero listen_until_return stops after timeout seconds and returns None.""" start = time.time() while timeout == 0 or time.time() - start < timeout: res = self.listen(*temporary_handlers) if res is not None: return res def wait_for_n_keypresses(self, key, n=1): """Waits till one key was pressed n times. :param key: the key to be pressed as defined by pygame. E.g. pygame.K_LEFT for the left arrow key :type key: int :param n: number of repetitions till the function returns :type n: int """ my_const = "key_consumed" counter = 0 def keypress_listener(e): return my_const \ if e.type == pygame.KEYDOWN and e.key == key \ else EventConsumerInfo.DONT_CARE while counter < n: if self.listen(keypress_listener) == my_const: counter += 1 def wait_for_keys(self, *keys, timeout=0): """Waits until one of the specified keys was pressed, and returns which key was pressed. :param keys: iterable of integers of pygame-keycodes, or simply multiple keys passed via multiple arguments :type keys: iterable :param timeout: number of seconds to wait till the function returns :type timeout: float :returns: The keycode of the pressed key, or None in case of timeout :rtype: int """ if len(keys) == 1 and _is_iterable(keys[0]): keys = keys[0] return self.listen_until_return(Handler.key_press(keys), timeout=timeout) def wait_for_seconds(self, seconds): """basically time.sleep() but in the mean-time the permanent handlers are executed""" self.listen_until_return(timeout=seconds) def wait_for_unicode_char(self, ignored_chars=None, timeout=0): """Returns a str that contains the single character that was pressed. This already respects modifier keys and keyboard layouts. If timeout is not none and no key is pressed within the specified timeout, None is returned. If a key is ingnored_chars it will be ignored. As argument for irgnored_chars any object that has a __contains__ method can be used, e.g. a string, a set, a list, etc""" return self.listen_until_return(Handler.unicode_char(ignored_chars), timeout=timeout)
KnorrFG/pyparadigm
pyparadigm/eventlistener.py
EventListener.wait_for_unicode_char
python
def wait_for_unicode_char(self, ignored_chars=None, timeout=0): return self.listen_until_return(Handler.unicode_char(ignored_chars), timeout=timeout)
Returns a str that contains the single character that was pressed. This already respects modifier keys and keyboard layouts. If timeout is not none and no key is pressed within the specified timeout, None is returned. If a key is ingnored_chars it will be ignored. As argument for irgnored_chars any object that has a __contains__ method can be used, e.g. a string, a set, a list, etc
train
https://github.com/KnorrFG/pyparadigm/blob/69944cdf3ce2f6414ae1aa1d27a0d8c6e5fb3fd3/pyparadigm/eventlistener.py#L295-L303
[ "def unicode_char(ignored_chars=None):\n \"\"\"returns a handler that listens for unicode characters\"\"\"\n return lambda e: e.unicode if e.type == pygame.KEYDOWN \\\n and ((ignored_chars is None) \n or (e.unicode not in ignored_chars))\\\n else EventConsumerInfo.DONT_CARE\n", "d...
class EventListener(object): """ :param permanent_handlers: iterable of permanent handlers :type permanent_handlers: iterable :param use_ctrl_c_handler: specifies whether a handler that quits the script when ctrl + c is pressed should be used :type use_ctrl_c_handler: Bool """ _mod_keys = {KMOD_LSHIFT, KMOD_RSHIFT, KMOD_SHIFT, KMOD_CAPS, KMOD_LCTRL, KMOD_RCTRL, KMOD_CTRL, KMOD_LALT, KMOD_RALT, KMOD_ALT, KMOD_LMETA, KMOD_RMETA, KMOD_META, KMOD_NUM, KMOD_MODE} @staticmethod def _contained_modifiers(mods, mods_of_interes=_mod_keys): return frozenset(mod for mod in mods_of_interes if mod & mods) @staticmethod def _exit_on_ctrl_c(event): if event.type == pygame.KEYDOWN \ and event.key == pygame.K_c \ and pygame.key.get_mods() & pygame.KMOD_CTRL: pygame.quit() exit(1) else: return EventConsumerInfo.DONT_CARE def __init__(self, permanent_handlers=None, use_ctrl_c_handler=True): self._current_q = [] self.mouse_proxies = defaultdict(dict) self.proxy_group = 0 if use_ctrl_c_handler: self.permanent_handlers = ( EventListener._exit_on_ctrl_c, ) if permanent_handlers: self.permanent_handlers += permanent_handlers else: self.permanent_handlers = permanent_handlers or [] def _get_q(self): self._current_q = itt.chain(self._current_q, pygame.event.get()) return self._current_q def mouse_area(self, handler, group=0, ident=None): """Adds a new MouseProxy for the given group to the EventListener.mouse_proxies dict if it is not in there yet, and returns the (new) MouseProxy. In listen() all entries in the current group of mouse_proxies are used.""" key = ident or id(handler) if key not in self.mouse_proxies[group]: self.mouse_proxies[group][key] = MouseProxy(handler, ident) return self.mouse_proxies[group][key] def group(self, group): """sets current mouse proxy group and returns self. Enables lines like el.group(1).wait_for_keys(...)""" self.proxy_group = group return self def listen(self, *temporary_handlers): """When listen() is called all queued pygame.Events will be passed to all registered listeners. There are two ways to register a listener: 1. as a permanent listener, that is always executed for every event. These are registered by passing the handler-functions during construction 2. as a temporary listener, that will only be executed during the current call to listen(). These are registered by passing the handler functions as arguments to listen() When a handler is called it can provoke three different reactions through its return value. 1. It can return EventConsumerInfo.DONT_CARE in which case the EventListener will pass the event to the next handler in line, or go to the next event, if the last handler was called. 2. It can return EventConsumerInfo.CONSUMED in which case the event will not be passed to following handlers, and the next event in line will be processed. 3. It can return anything else (including None, which will be returned if no return value is specified) in this case the listen()-method will return the result of the handler. Therefore all permanent handlers should usually return EventConsumerInfo.DONT_CARE """ funcs = tuple(itt.chain(self.permanent_handlers, (proxy.listener for proxy in self.mouse_proxies[self.proxy_group].values()), temporary_handlers)) for event in self._get_q(): for func in funcs: ret = func(event) if ret == EventConsumerInfo.CONSUMED: break if ret == EventConsumerInfo.DONT_CARE: continue else: return ret def listen_until_return(self, *temporary_handlers, timeout=0): """Calls listen repeatedly until listen returns something else than None. Then returns listen's result. If timeout is not zero listen_until_return stops after timeout seconds and returns None.""" start = time.time() while timeout == 0 or time.time() - start < timeout: res = self.listen(*temporary_handlers) if res is not None: return res def wait_for_n_keypresses(self, key, n=1): """Waits till one key was pressed n times. :param key: the key to be pressed as defined by pygame. E.g. pygame.K_LEFT for the left arrow key :type key: int :param n: number of repetitions till the function returns :type n: int """ my_const = "key_consumed" counter = 0 def keypress_listener(e): return my_const \ if e.type == pygame.KEYDOWN and e.key == key \ else EventConsumerInfo.DONT_CARE while counter < n: if self.listen(keypress_listener) == my_const: counter += 1 def wait_for_keys(self, *keys, timeout=0): """Waits until one of the specified keys was pressed, and returns which key was pressed. :param keys: iterable of integers of pygame-keycodes, or simply multiple keys passed via multiple arguments :type keys: iterable :param timeout: number of seconds to wait till the function returns :type timeout: float :returns: The keycode of the pressed key, or None in case of timeout :rtype: int """ if len(keys) == 1 and _is_iterable(keys[0]): keys = keys[0] return self.listen_until_return(Handler.key_press(keys), timeout=timeout) def wait_for_keys_modified(self, *keys, modifiers_to_check=_mod_keys, timeout=0): """The same as wait_for_keys, but returns a frozen_set which contains the pressed key, and the modifier keys. :param modifiers_to_check: iterable of modifiers for which the function will check whether they are pressed :type modifiers: Iterable[int]""" set_mods = pygame.key.get_mods() return frozenset.union( frozenset([self.wait_for_keys(*keys, timeout=timeout)]), EventListener._contained_modifiers(set_mods, modifiers_to_check)) def wait_for_seconds(self, seconds): """basically time.sleep() but in the mean-time the permanent handlers are executed""" self.listen_until_return(timeout=seconds)
KnorrFG/pyparadigm
pyparadigm/surface_composition.py
_inner_func_anot
python
def _inner_func_anot(func): @wraps(func) def new_func(*args): return func(*_lmap(_wrap_surface, args)) return new_func
must be applied to all inner functions that return contexts. Wraps all instances of pygame.Surface in the input in Surface
train
https://github.com/KnorrFG/pyparadigm/blob/69944cdf3ce2f6414ae1aa1d27a0d8c6e5fb3fd3/pyparadigm/surface_composition.py#L23-L30
null
"""Easy Image Composition The purpose of this module is to make it easy to compose the frames that are displayed in a paradigm. For an introduction, please refer to the :ref:`tutorial<creating_surfaces>` """ from functools import reduce, wraps, lru_cache, partial from itertools import accumulate from operator import add, methodcaller import contextlib with contextlib.redirect_stdout(None): import pygame _lmap = wraps(map)(lambda *args, **kwargs:list(map(*args, **kwargs))) _wrap_surface = lambda elem:\ Surface()(elem) if type(elem) == pygame.Surface else elem _round_to_int = lambda val: int(round(val)) _call_function = lambda elem:\ elem() if callable(elem) else elem def _inner_func_anot(func): """must be applied to all inner functions that return contexts. Wraps all instances of pygame.Surface in the input in Surface""" @wraps(func) def new_func(*args): return func(*_lmap(_wrap_surface, args)) return new_func def _wrap_children(children): try: return _lmap(_wrap_surface, children) except TypeError: return _wrap_surface(children) def _check_call_op(child): if child is not None: raise RuntimeError("Call operator was called twice") class LLItem: """Defines the relative size of an element in a LinLayout All Elements that are passed to a linear layout are automatically wrapped into an LLItem with relative_size=1. Therefore by default all elements within a layout will be of the same size. To change the proportions a LLItem can be used explicitely with another relative size. It is also possible to use an LLItem as placeholde in a layout, to generate an empty space like this: :Example: LinLayout("h")( LLItem(1), LLItem(1)(Circle(0xFFFF00))) """ def __init__(self, relative_size): self.child = Surface() self.relative_size = relative_size def __call__(self, child): self.child = _wrap_children(child) return self class LinLayout: """A linear layout to order items horizontally or vertically. Every element in the layout is automatically wrapped within a LLItem with relative_size=1, i.e. all elements get assigned an equal amount of space, to change that elements can be wrappend in LLItems manually to get desired proportions :param orientation: orientation of the layout, either 'v' for vertica, or 'h' for horizontal. :type orientation: str """ def __init__(self, orientation): assert orientation in ["v", "h"] self.orientation = orientation self.children = None def __call__(self, *children): _check_call_op(self.children) self.children = _lmap(lambda child: child if type(child) == LLItem else LLItem(1)(child), _wrap_children(children)) return self def _draw(self, surface, target_rect): child_rects = self._compute_child_rects(target_rect) for child, rect in zip(self.children, child_rects): child.child._draw(surface, rect) def _compute_child_rects(self, target_rect): flip_if_not_horizontal = lambda t: \ t if self.orientation == "h" else (t[1], t[0]) target_rect_size = target_rect.size divider, full = flip_if_not_horizontal(target_rect_size) dyn_size_per_unit = divider / sum(child.relative_size for child in self.children) strides = [child.relative_size * dyn_size_per_unit for child in self.children] dyn_offsets = [0] + list(accumulate(strides))[:-1] left_offsets, top_offsets = flip_if_not_horizontal((dyn_offsets, [0] * len(self.children))) widths, heights = flip_if_not_horizontal((strides, [full] * len(self.children))) return [pygame.Rect(target_rect.left + left_offset, target_rect.top + top_offset, w, h) for left_offset, top_offset, w, h in zip(left_offsets, top_offsets, widths, heights)] class Margin: """Defines the relative position of an item within a Surface. For details see Surface. """ __slots__ = ["left", "right", "top", "bottom"] def __init__(self, left=1, right=1, top=1, bottom=1): self.left=left self.right=right self.top=top self.bottom=bottom def _offset_by_margins(space, one, two): return space * one / (one + two) class Surface: """Wraps a pygame surface. The Surface is the connection between the absolute world of pygame.Surfaces and the relative world of the composition functions. A pygame.Surfaces can be bigger than the space that is available to the Surface, or smaller. The Surface does the actual blitting, and determines the concrete position, and if necessary (or desired) scales the input surface. Warning: When images are scaled with smoothing, colors will change decently, which makes it inappropriate to use in combination with colorkeys. :param margin: used to determine the exact location of the pygame.Surfaces within the available space. The margin value represents the proportion of the free space, along an axis, i.e. Margin(1, 1, 1, 1) is centered, Margin(0, 1, 1, 2) is as far left as possible and one/third on the way down. :type margin: Margin object :param scale: If 0 < scale <= 1 the longer side of the surface is scaled to to the given fraction of the available space, the aspect ratio is will be preserved. If scale is 0 the will be no scaling if the image is smaller than the available space. It will still be scaled down if it is too big. :type scale: float :param smooth: if True the result of the scaling will be smoothed :type smooth: float """ def __init__(self, margin=Margin(1, 1, 1, 1), scale=0, smooth=True): assert 0 <= scale <= 1 self.child = None self.margin = margin self.scale = scale self.smooth = smooth def __call__(self, child): _check_call_op(self.child) self.child = child return self @staticmethod def _scale_to_target(source, target_rect, smooth=False): target_size = source.get_rect().fit(target_rect).size return pygame.transform.scale(source, target_size) \ if not smooth else pygame.transform.smoothscale(source, target_size) def _determine_target_size(child, target_rect, scale): if scale > 0: return tuple(dist * scale for dist in target_rect.size) elif all(s_dim <= t_dim for s_dim, t_dim in zip(child.get_size(), target_rect.size)): return 0 else: return target_rect.size def compute_render_rect(self, target_rect): target_size = Surface._determine_target_size(self.child, target_rect, self.scale)\ or self.child.get_rect().size remaining_h_space = target_rect.w - target_size[0] remaining_v_space = target_rect.h - target_size[1] return pygame.Rect( (target_rect.left + _offset_by_margins(remaining_h_space, self.margin.left, self.margin.right), target_rect.top + _offset_by_margins(remaining_v_space, self.margin.top, self.margin.bottom)), target_size) def _draw(self, surface, target_rect): if self.child is None: return target_size = Surface._determine_target_size(self.child, target_rect, self.scale) content = Surface._scale_to_target(self.child, (0, 0, *target_size), self.smooth)\ if target_size else self.child remaining_h_space = target_rect.w - content.get_rect().w remaining_v_space = target_rect.h - content.get_rect().h surface.blit(content, ( target_rect.left + _offset_by_margins(remaining_h_space, self.margin.left, self.margin.right), target_rect.top + _offset_by_margins(remaining_v_space, self.margin.top, self.margin.bottom))) class Padding: """Pads a child element Each argument refers to a percentage of the axis it belongs to. A padding of (0.25, 0.25, 0.25, 0.25) would generate blocked area a quater of the available height in size above and below the child, and a quarter of the available width left and right of the child. If left and right or top and bottom sum up to one that would mean no space for the child is remaining """ def _draw(self, surface, target_rect): assert self.child is not None child_rect = pygame.Rect( target_rect.left + target_rect.w * self.left, target_rect.top + target_rect.h * self.top, target_rect.w * (1 - self.left - self.right), target_rect.h * (1 - self.top - self.bottom) ) self.child._draw(surface, child_rect) def __init__(self, left, right, top, bottom): assert all(0 <= side < 1 for side in [left, right, top, bottom]) assert left + right < 1 assert top + bottom < 1 self.left = left self.right = right self.top = top self.bottom = bottom self.child = None def __call__(self, child): _check_call_op(self.child) self.child = _wrap_children(child) return self @staticmethod def from_scale(scale_w, scale_h=None): """Creates a padding by the remaining space after scaling the content. E.g. Padding.from_scale(0.5) would produce Padding(0.25, 0.25, 0.25, 0.25) and Padding.from_scale(0.5, 1) would produce Padding(0.25, 0.25, 0, 0) because the content would not be scaled (since scale_h=1) and therefore there would be no vertical padding. If scale_h is not specified scale_h=scale_w is used as default :param scale_w: horizontal scaling factors :type scale_w: float :param scale_h: vertical scaling factor :type scale_h: float """ if not scale_h: scale_h = scale_w w_padding = [(1 - scale_w) * 0.5] * 2 h_padding = [(1 - scale_h) * 0.5] * 2 return Padding(*w_padding, *h_padding) class RectangleShaper: """Creates a padding, defined by a target Shape. Width and height are the relative proportions of the target rectangle. E.g RectangleShaper(1, 1) would create a square. and RectangleShaper(2, 1) would create a rectangle which is twice as wide as it is high. The rectangle always has the maximal possible size within the parent area. """ def __init__(self, width=1, height=1): self.child = None self.width = width self.height = height def __call__(self, child): _check_call_op(self.child) self.child = _wrap_children(child) return self def _draw(self, surface, target_rect): parent_w_factor = target_rect.w / target_rect.h my_w_factor = self.width / self.height if parent_w_factor > my_w_factor: my_h = target_rect.h my_w = my_h * my_w_factor my_h_offset = 0 my_w_offset = _round_to_int((target_rect.w - my_w) * 0.5) else: my_w = target_rect.w my_h = my_w / self.width * self.height my_w_offset = 0 my_h_offset = _round_to_int((target_rect.h - my_h) * 0.5) self.child._draw(surface, pygame.Rect( target_rect.left + my_w_offset, target_rect.top + my_h_offset, my_w, my_h )) class Circle: """Draws a Circle in the assigned space. The circle will always be centered, and the radius will be half of the shorter side of the assigned space. :param color: The color of the circle :type color: pygame.Color or int :param width: width of the circle (in pixels). If 0 the circle will be filled :type width: int """ def __init__(self, color, width=0): self.color = color self.width = width def _draw(self, surface, target_rect): pygame.draw.circle(surface, self.color, target_rect.center, int(round(min(target_rect.w, target_rect.h) * 0.5)), self.width) class Fill: """Fills the assigned area. Afterwards, the children are rendered :param color: the color with which the area is filled :type color: pygame.Color or int """ def __init__(self, color): self.color = color self.child = None def __call__(self, child): _check_call_op(self.child) self.child = _wrap_children(child) return self def _draw(self, surface, target_rect): surface.fill(self.color, target_rect) if self.child: self.child._draw(surface, target_rect) class Overlay: """Draws all its children on top of each other in the same rect""" def __init__(self, *children): self.children = _wrap_children(children) def _draw(self, surface, target_rect): for child in self.children: child._draw(surface, target_rect) def Cross(width=3, color=0): """Draws a cross centered in the target area :param width: width of the lines of the cross in pixels :type width: int :param color: color of the lines of the cross :type color: pygame.Color """ return Overlay(Line("h", width, color), Line("v", width, color)) class Border: """Draws a border around the contained area. Can have a single child. :param width: width of the border in pixels :type width: int :param color: color of the border :type color: pygame.Color """ def __init__(self, width=3, color=0): v_line = Line("v", width, color) h_line = Line("h", width, color) self.child_was_added = False self.overlay = Overlay( LinLayout("h")( LLItem(0)(v_line), LLItem(1), LLItem(0)(v_line) ), LinLayout("v")( LLItem(0)(h_line), LLItem(1), LLItem(0)(h_line) ) ) def __call__(self, child): _check_call_op(None if not self.child_was_added else 1) self.overlay.children.append(_wrap_children(child)) return self def _draw(self, surface, target_rect): self.overlay._draw(surface, target_rect) class Line: """Draws a line. :param width: width of the line in pixels :type widht: int :param orientation: "v" or "h". Indicates whether the line should be horizontal or vertical. :type orientation: str """ def __init__(self, orientation, width=3, color=0): assert orientation in ["h", "v"] assert width > 0 self.orientation = orientation self.width = width self.color = color def _draw(self, surface, target_rect): if self.orientation == "h": pygame.draw.line(surface, self.color, ( target_rect.left, _round_to_int(target_rect.top + target_rect.h * 0.5)), ( target_rect.left + target_rect.w - 1, _round_to_int(target_rect.top + target_rect.h * 0.5)), self.width) else: pygame.draw.line(surface, self.color, ( _round_to_int(target_rect.left + target_rect.width * 0.5), target_rect.top), ( _round_to_int(target_rect.left + target_rect.width * 0.5), target_rect.top + target_rect.h - 1), self.width) _fill_col = lambda target_len: lambda col: col + [None] * (target_len - len(col)) _to_h_layout = lambda cols: lambda children: LinLayout("h")( *_lmap(lambda it, child: it(child), map(LLItem, cols), _lmap(_wrap_surface, children))) def GridLayout(row_proportions=None, col_proportions=None): def inner_grid_layout(*children): nonlocal row_proportions, col_proportions assert all(type(child) == list for child in children) if row_proportions is None: row_proportions = [1] * len(children) else: assert len(row_proportions) == len(children) col_width = max(map(len, children)) if col_proportions: assert len(col_proportions) == col_width else: col_proportions = [1] * col_width filled_cols = _lmap(_fill_col(col_width), children) return LinLayout("v")(*_lmap( lambda it, child: it(child), map(LLItem, row_proportions), _lmap(_to_h_layout(col_proportions), children))) return inner_grid_layout def compose(target, root=None): """Top level function to create a surface. :param target: the pygame.Surface to blit on. Or a (width, height) tuple in which case a new surface will be created :type target: - """ if type(root) == Surface: raise ValueError("A Surface may not be used as root, please add " +"it as a single child i.e. compose(...)(Surface(...))") @_inner_func_anot def inner_compose(*children): if root: root_context = root(*children) else: assert len(children) == 1 root_context = children[0] if type(target) == pygame.Surface: surface = target size = target.get_size() else: size = target surface = pygame.Surface(size) root_context._draw(surface, pygame.Rect(0, 0, *size)) return surface return inner_compose @lru_cache(128) def Font(name=None, source="sys", italic=False, bold=False, size=20): """Unifies loading of fonts. :param name: name of system-font or filepath, if None is passed the default system-font is loaded :type name: str :param source: "sys" for system font, or "file" to load a file :type source: str """ assert source in ["sys", "file"] if not name: return pygame.font.SysFont(pygame.font.get_default_font(), size, bold=bold, italic=italic) if source == "sys": return pygame.font.SysFont(name, size, bold=bold, italic=italic) else: f = pygame.font.Font(name, size) f.set_italic(italic) f.set_bold(bold) return f def _text(text, font, color=pygame.Color(0, 0, 0), antialias=False): return font.render(text, antialias, color).convert_alpha() def Text(text, font, color=pygame.Color(0, 0, 0), antialias=False, align="center"): """Renders a text. Supports multiline text, the background will be transparent. :param align: text-alignment must be "center", "left", or "righ" :type align: str :return: the input text :rtype: pygame.Surface """ assert align in ["center", "left", "right"] margin_l, margin_r = 1, 1 if align == "left": margin_l = 0 elif align == "right": margin_r = 0 margin = Margin(margin_l, margin_r) color_key = pygame.Color(0, 0, 1) if pygame.Color(0, 0, 1) != color else 0x000002 text_surfaces = _lmap(lambda text: _text(text, font=font, color=color, antialias=antialias), map(methodcaller("strip"), text.split("\n"))) w = max(surf.get_rect().w for surf in text_surfaces) h = sum(surf.get_rect().h for surf in text_surfaces) surf = compose((w, h), Fill(color_key))(LinLayout("v")( *_lmap(lambda s: Surface(margin)(s), text_surfaces))) surf.set_colorkey(color_key) return surf.convert_alpha()
KnorrFG/pyparadigm
pyparadigm/surface_composition.py
Cross
python
def Cross(width=3, color=0): return Overlay(Line("h", width, color), Line("v", width, color))
Draws a cross centered in the target area :param width: width of the lines of the cross in pixels :type width: int :param color: color of the lines of the cross :type color: pygame.Color
train
https://github.com/KnorrFG/pyparadigm/blob/69944cdf3ce2f6414ae1aa1d27a0d8c6e5fb3fd3/pyparadigm/surface_composition.py#L381-L389
null
"""Easy Image Composition The purpose of this module is to make it easy to compose the frames that are displayed in a paradigm. For an introduction, please refer to the :ref:`tutorial<creating_surfaces>` """ from functools import reduce, wraps, lru_cache, partial from itertools import accumulate from operator import add, methodcaller import contextlib with contextlib.redirect_stdout(None): import pygame _lmap = wraps(map)(lambda *args, **kwargs:list(map(*args, **kwargs))) _wrap_surface = lambda elem:\ Surface()(elem) if type(elem) == pygame.Surface else elem _round_to_int = lambda val: int(round(val)) _call_function = lambda elem:\ elem() if callable(elem) else elem def _inner_func_anot(func): """must be applied to all inner functions that return contexts. Wraps all instances of pygame.Surface in the input in Surface""" @wraps(func) def new_func(*args): return func(*_lmap(_wrap_surface, args)) return new_func def _wrap_children(children): try: return _lmap(_wrap_surface, children) except TypeError: return _wrap_surface(children) def _check_call_op(child): if child is not None: raise RuntimeError("Call operator was called twice") class LLItem: """Defines the relative size of an element in a LinLayout All Elements that are passed to a linear layout are automatically wrapped into an LLItem with relative_size=1. Therefore by default all elements within a layout will be of the same size. To change the proportions a LLItem can be used explicitely with another relative size. It is also possible to use an LLItem as placeholde in a layout, to generate an empty space like this: :Example: LinLayout("h")( LLItem(1), LLItem(1)(Circle(0xFFFF00))) """ def __init__(self, relative_size): self.child = Surface() self.relative_size = relative_size def __call__(self, child): self.child = _wrap_children(child) return self class LinLayout: """A linear layout to order items horizontally or vertically. Every element in the layout is automatically wrapped within a LLItem with relative_size=1, i.e. all elements get assigned an equal amount of space, to change that elements can be wrappend in LLItems manually to get desired proportions :param orientation: orientation of the layout, either 'v' for vertica, or 'h' for horizontal. :type orientation: str """ def __init__(self, orientation): assert orientation in ["v", "h"] self.orientation = orientation self.children = None def __call__(self, *children): _check_call_op(self.children) self.children = _lmap(lambda child: child if type(child) == LLItem else LLItem(1)(child), _wrap_children(children)) return self def _draw(self, surface, target_rect): child_rects = self._compute_child_rects(target_rect) for child, rect in zip(self.children, child_rects): child.child._draw(surface, rect) def _compute_child_rects(self, target_rect): flip_if_not_horizontal = lambda t: \ t if self.orientation == "h" else (t[1], t[0]) target_rect_size = target_rect.size divider, full = flip_if_not_horizontal(target_rect_size) dyn_size_per_unit = divider / sum(child.relative_size for child in self.children) strides = [child.relative_size * dyn_size_per_unit for child in self.children] dyn_offsets = [0] + list(accumulate(strides))[:-1] left_offsets, top_offsets = flip_if_not_horizontal((dyn_offsets, [0] * len(self.children))) widths, heights = flip_if_not_horizontal((strides, [full] * len(self.children))) return [pygame.Rect(target_rect.left + left_offset, target_rect.top + top_offset, w, h) for left_offset, top_offset, w, h in zip(left_offsets, top_offsets, widths, heights)] class Margin: """Defines the relative position of an item within a Surface. For details see Surface. """ __slots__ = ["left", "right", "top", "bottom"] def __init__(self, left=1, right=1, top=1, bottom=1): self.left=left self.right=right self.top=top self.bottom=bottom def _offset_by_margins(space, one, two): return space * one / (one + two) class Surface: """Wraps a pygame surface. The Surface is the connection between the absolute world of pygame.Surfaces and the relative world of the composition functions. A pygame.Surfaces can be bigger than the space that is available to the Surface, or smaller. The Surface does the actual blitting, and determines the concrete position, and if necessary (or desired) scales the input surface. Warning: When images are scaled with smoothing, colors will change decently, which makes it inappropriate to use in combination with colorkeys. :param margin: used to determine the exact location of the pygame.Surfaces within the available space. The margin value represents the proportion of the free space, along an axis, i.e. Margin(1, 1, 1, 1) is centered, Margin(0, 1, 1, 2) is as far left as possible and one/third on the way down. :type margin: Margin object :param scale: If 0 < scale <= 1 the longer side of the surface is scaled to to the given fraction of the available space, the aspect ratio is will be preserved. If scale is 0 the will be no scaling if the image is smaller than the available space. It will still be scaled down if it is too big. :type scale: float :param smooth: if True the result of the scaling will be smoothed :type smooth: float """ def __init__(self, margin=Margin(1, 1, 1, 1), scale=0, smooth=True): assert 0 <= scale <= 1 self.child = None self.margin = margin self.scale = scale self.smooth = smooth def __call__(self, child): _check_call_op(self.child) self.child = child return self @staticmethod def _scale_to_target(source, target_rect, smooth=False): target_size = source.get_rect().fit(target_rect).size return pygame.transform.scale(source, target_size) \ if not smooth else pygame.transform.smoothscale(source, target_size) def _determine_target_size(child, target_rect, scale): if scale > 0: return tuple(dist * scale for dist in target_rect.size) elif all(s_dim <= t_dim for s_dim, t_dim in zip(child.get_size(), target_rect.size)): return 0 else: return target_rect.size def compute_render_rect(self, target_rect): target_size = Surface._determine_target_size(self.child, target_rect, self.scale)\ or self.child.get_rect().size remaining_h_space = target_rect.w - target_size[0] remaining_v_space = target_rect.h - target_size[1] return pygame.Rect( (target_rect.left + _offset_by_margins(remaining_h_space, self.margin.left, self.margin.right), target_rect.top + _offset_by_margins(remaining_v_space, self.margin.top, self.margin.bottom)), target_size) def _draw(self, surface, target_rect): if self.child is None: return target_size = Surface._determine_target_size(self.child, target_rect, self.scale) content = Surface._scale_to_target(self.child, (0, 0, *target_size), self.smooth)\ if target_size else self.child remaining_h_space = target_rect.w - content.get_rect().w remaining_v_space = target_rect.h - content.get_rect().h surface.blit(content, ( target_rect.left + _offset_by_margins(remaining_h_space, self.margin.left, self.margin.right), target_rect.top + _offset_by_margins(remaining_v_space, self.margin.top, self.margin.bottom))) class Padding: """Pads a child element Each argument refers to a percentage of the axis it belongs to. A padding of (0.25, 0.25, 0.25, 0.25) would generate blocked area a quater of the available height in size above and below the child, and a quarter of the available width left and right of the child. If left and right or top and bottom sum up to one that would mean no space for the child is remaining """ def _draw(self, surface, target_rect): assert self.child is not None child_rect = pygame.Rect( target_rect.left + target_rect.w * self.left, target_rect.top + target_rect.h * self.top, target_rect.w * (1 - self.left - self.right), target_rect.h * (1 - self.top - self.bottom) ) self.child._draw(surface, child_rect) def __init__(self, left, right, top, bottom): assert all(0 <= side < 1 for side in [left, right, top, bottom]) assert left + right < 1 assert top + bottom < 1 self.left = left self.right = right self.top = top self.bottom = bottom self.child = None def __call__(self, child): _check_call_op(self.child) self.child = _wrap_children(child) return self @staticmethod def from_scale(scale_w, scale_h=None): """Creates a padding by the remaining space after scaling the content. E.g. Padding.from_scale(0.5) would produce Padding(0.25, 0.25, 0.25, 0.25) and Padding.from_scale(0.5, 1) would produce Padding(0.25, 0.25, 0, 0) because the content would not be scaled (since scale_h=1) and therefore there would be no vertical padding. If scale_h is not specified scale_h=scale_w is used as default :param scale_w: horizontal scaling factors :type scale_w: float :param scale_h: vertical scaling factor :type scale_h: float """ if not scale_h: scale_h = scale_w w_padding = [(1 - scale_w) * 0.5] * 2 h_padding = [(1 - scale_h) * 0.5] * 2 return Padding(*w_padding, *h_padding) class RectangleShaper: """Creates a padding, defined by a target Shape. Width and height are the relative proportions of the target rectangle. E.g RectangleShaper(1, 1) would create a square. and RectangleShaper(2, 1) would create a rectangle which is twice as wide as it is high. The rectangle always has the maximal possible size within the parent area. """ def __init__(self, width=1, height=1): self.child = None self.width = width self.height = height def __call__(self, child): _check_call_op(self.child) self.child = _wrap_children(child) return self def _draw(self, surface, target_rect): parent_w_factor = target_rect.w / target_rect.h my_w_factor = self.width / self.height if parent_w_factor > my_w_factor: my_h = target_rect.h my_w = my_h * my_w_factor my_h_offset = 0 my_w_offset = _round_to_int((target_rect.w - my_w) * 0.5) else: my_w = target_rect.w my_h = my_w / self.width * self.height my_w_offset = 0 my_h_offset = _round_to_int((target_rect.h - my_h) * 0.5) self.child._draw(surface, pygame.Rect( target_rect.left + my_w_offset, target_rect.top + my_h_offset, my_w, my_h )) class Circle: """Draws a Circle in the assigned space. The circle will always be centered, and the radius will be half of the shorter side of the assigned space. :param color: The color of the circle :type color: pygame.Color or int :param width: width of the circle (in pixels). If 0 the circle will be filled :type width: int """ def __init__(self, color, width=0): self.color = color self.width = width def _draw(self, surface, target_rect): pygame.draw.circle(surface, self.color, target_rect.center, int(round(min(target_rect.w, target_rect.h) * 0.5)), self.width) class Fill: """Fills the assigned area. Afterwards, the children are rendered :param color: the color with which the area is filled :type color: pygame.Color or int """ def __init__(self, color): self.color = color self.child = None def __call__(self, child): _check_call_op(self.child) self.child = _wrap_children(child) return self def _draw(self, surface, target_rect): surface.fill(self.color, target_rect) if self.child: self.child._draw(surface, target_rect) class Overlay: """Draws all its children on top of each other in the same rect""" def __init__(self, *children): self.children = _wrap_children(children) def _draw(self, surface, target_rect): for child in self.children: child._draw(surface, target_rect) class Border: """Draws a border around the contained area. Can have a single child. :param width: width of the border in pixels :type width: int :param color: color of the border :type color: pygame.Color """ def __init__(self, width=3, color=0): v_line = Line("v", width, color) h_line = Line("h", width, color) self.child_was_added = False self.overlay = Overlay( LinLayout("h")( LLItem(0)(v_line), LLItem(1), LLItem(0)(v_line) ), LinLayout("v")( LLItem(0)(h_line), LLItem(1), LLItem(0)(h_line) ) ) def __call__(self, child): _check_call_op(None if not self.child_was_added else 1) self.overlay.children.append(_wrap_children(child)) return self def _draw(self, surface, target_rect): self.overlay._draw(surface, target_rect) class Line: """Draws a line. :param width: width of the line in pixels :type widht: int :param orientation: "v" or "h". Indicates whether the line should be horizontal or vertical. :type orientation: str """ def __init__(self, orientation, width=3, color=0): assert orientation in ["h", "v"] assert width > 0 self.orientation = orientation self.width = width self.color = color def _draw(self, surface, target_rect): if self.orientation == "h": pygame.draw.line(surface, self.color, ( target_rect.left, _round_to_int(target_rect.top + target_rect.h * 0.5)), ( target_rect.left + target_rect.w - 1, _round_to_int(target_rect.top + target_rect.h * 0.5)), self.width) else: pygame.draw.line(surface, self.color, ( _round_to_int(target_rect.left + target_rect.width * 0.5), target_rect.top), ( _round_to_int(target_rect.left + target_rect.width * 0.5), target_rect.top + target_rect.h - 1), self.width) _fill_col = lambda target_len: lambda col: col + [None] * (target_len - len(col)) _to_h_layout = lambda cols: lambda children: LinLayout("h")( *_lmap(lambda it, child: it(child), map(LLItem, cols), _lmap(_wrap_surface, children))) def GridLayout(row_proportions=None, col_proportions=None): def inner_grid_layout(*children): nonlocal row_proportions, col_proportions assert all(type(child) == list for child in children) if row_proportions is None: row_proportions = [1] * len(children) else: assert len(row_proportions) == len(children) col_width = max(map(len, children)) if col_proportions: assert len(col_proportions) == col_width else: col_proportions = [1] * col_width filled_cols = _lmap(_fill_col(col_width), children) return LinLayout("v")(*_lmap( lambda it, child: it(child), map(LLItem, row_proportions), _lmap(_to_h_layout(col_proportions), children))) return inner_grid_layout def compose(target, root=None): """Top level function to create a surface. :param target: the pygame.Surface to blit on. Or a (width, height) tuple in which case a new surface will be created :type target: - """ if type(root) == Surface: raise ValueError("A Surface may not be used as root, please add " +"it as a single child i.e. compose(...)(Surface(...))") @_inner_func_anot def inner_compose(*children): if root: root_context = root(*children) else: assert len(children) == 1 root_context = children[0] if type(target) == pygame.Surface: surface = target size = target.get_size() else: size = target surface = pygame.Surface(size) root_context._draw(surface, pygame.Rect(0, 0, *size)) return surface return inner_compose @lru_cache(128) def Font(name=None, source="sys", italic=False, bold=False, size=20): """Unifies loading of fonts. :param name: name of system-font or filepath, if None is passed the default system-font is loaded :type name: str :param source: "sys" for system font, or "file" to load a file :type source: str """ assert source in ["sys", "file"] if not name: return pygame.font.SysFont(pygame.font.get_default_font(), size, bold=bold, italic=italic) if source == "sys": return pygame.font.SysFont(name, size, bold=bold, italic=italic) else: f = pygame.font.Font(name, size) f.set_italic(italic) f.set_bold(bold) return f def _text(text, font, color=pygame.Color(0, 0, 0), antialias=False): return font.render(text, antialias, color).convert_alpha() def Text(text, font, color=pygame.Color(0, 0, 0), antialias=False, align="center"): """Renders a text. Supports multiline text, the background will be transparent. :param align: text-alignment must be "center", "left", or "righ" :type align: str :return: the input text :rtype: pygame.Surface """ assert align in ["center", "left", "right"] margin_l, margin_r = 1, 1 if align == "left": margin_l = 0 elif align == "right": margin_r = 0 margin = Margin(margin_l, margin_r) color_key = pygame.Color(0, 0, 1) if pygame.Color(0, 0, 1) != color else 0x000002 text_surfaces = _lmap(lambda text: _text(text, font=font, color=color, antialias=antialias), map(methodcaller("strip"), text.split("\n"))) w = max(surf.get_rect().w for surf in text_surfaces) h = sum(surf.get_rect().h for surf in text_surfaces) surf = compose((w, h), Fill(color_key))(LinLayout("v")( *_lmap(lambda s: Surface(margin)(s), text_surfaces))) surf.set_colorkey(color_key) return surf.convert_alpha()
KnorrFG/pyparadigm
pyparadigm/surface_composition.py
compose
python
def compose(target, root=None): if type(root) == Surface: raise ValueError("A Surface may not be used as root, please add " +"it as a single child i.e. compose(...)(Surface(...))") @_inner_func_anot def inner_compose(*children): if root: root_context = root(*children) else: assert len(children) == 1 root_context = children[0] if type(target) == pygame.Surface: surface = target size = target.get_size() else: size = target surface = pygame.Surface(size) root_context._draw(surface, pygame.Rect(0, 0, *size)) return surface return inner_compose
Top level function to create a surface. :param target: the pygame.Surface to blit on. Or a (width, height) tuple in which case a new surface will be created :type target: -
train
https://github.com/KnorrFG/pyparadigm/blob/69944cdf3ce2f6414ae1aa1d27a0d8c6e5fb3fd3/pyparadigm/surface_composition.py#L483-L511
[ "def _inner_func_anot(func):\n \"\"\"must be applied to all inner functions that return contexts.\n\n Wraps all instances of pygame.Surface in the input in Surface\"\"\"\n @wraps(func)\n def new_func(*args):\n return func(*_lmap(_wrap_surface, args))\n return new_func\n" ]
"""Easy Image Composition The purpose of this module is to make it easy to compose the frames that are displayed in a paradigm. For an introduction, please refer to the :ref:`tutorial<creating_surfaces>` """ from functools import reduce, wraps, lru_cache, partial from itertools import accumulate from operator import add, methodcaller import contextlib with contextlib.redirect_stdout(None): import pygame _lmap = wraps(map)(lambda *args, **kwargs:list(map(*args, **kwargs))) _wrap_surface = lambda elem:\ Surface()(elem) if type(elem) == pygame.Surface else elem _round_to_int = lambda val: int(round(val)) _call_function = lambda elem:\ elem() if callable(elem) else elem def _inner_func_anot(func): """must be applied to all inner functions that return contexts. Wraps all instances of pygame.Surface in the input in Surface""" @wraps(func) def new_func(*args): return func(*_lmap(_wrap_surface, args)) return new_func def _wrap_children(children): try: return _lmap(_wrap_surface, children) except TypeError: return _wrap_surface(children) def _check_call_op(child): if child is not None: raise RuntimeError("Call operator was called twice") class LLItem: """Defines the relative size of an element in a LinLayout All Elements that are passed to a linear layout are automatically wrapped into an LLItem with relative_size=1. Therefore by default all elements within a layout will be of the same size. To change the proportions a LLItem can be used explicitely with another relative size. It is also possible to use an LLItem as placeholde in a layout, to generate an empty space like this: :Example: LinLayout("h")( LLItem(1), LLItem(1)(Circle(0xFFFF00))) """ def __init__(self, relative_size): self.child = Surface() self.relative_size = relative_size def __call__(self, child): self.child = _wrap_children(child) return self class LinLayout: """A linear layout to order items horizontally or vertically. Every element in the layout is automatically wrapped within a LLItem with relative_size=1, i.e. all elements get assigned an equal amount of space, to change that elements can be wrappend in LLItems manually to get desired proportions :param orientation: orientation of the layout, either 'v' for vertica, or 'h' for horizontal. :type orientation: str """ def __init__(self, orientation): assert orientation in ["v", "h"] self.orientation = orientation self.children = None def __call__(self, *children): _check_call_op(self.children) self.children = _lmap(lambda child: child if type(child) == LLItem else LLItem(1)(child), _wrap_children(children)) return self def _draw(self, surface, target_rect): child_rects = self._compute_child_rects(target_rect) for child, rect in zip(self.children, child_rects): child.child._draw(surface, rect) def _compute_child_rects(self, target_rect): flip_if_not_horizontal = lambda t: \ t if self.orientation == "h" else (t[1], t[0]) target_rect_size = target_rect.size divider, full = flip_if_not_horizontal(target_rect_size) dyn_size_per_unit = divider / sum(child.relative_size for child in self.children) strides = [child.relative_size * dyn_size_per_unit for child in self.children] dyn_offsets = [0] + list(accumulate(strides))[:-1] left_offsets, top_offsets = flip_if_not_horizontal((dyn_offsets, [0] * len(self.children))) widths, heights = flip_if_not_horizontal((strides, [full] * len(self.children))) return [pygame.Rect(target_rect.left + left_offset, target_rect.top + top_offset, w, h) for left_offset, top_offset, w, h in zip(left_offsets, top_offsets, widths, heights)] class Margin: """Defines the relative position of an item within a Surface. For details see Surface. """ __slots__ = ["left", "right", "top", "bottom"] def __init__(self, left=1, right=1, top=1, bottom=1): self.left=left self.right=right self.top=top self.bottom=bottom def _offset_by_margins(space, one, two): return space * one / (one + two) class Surface: """Wraps a pygame surface. The Surface is the connection between the absolute world of pygame.Surfaces and the relative world of the composition functions. A pygame.Surfaces can be bigger than the space that is available to the Surface, or smaller. The Surface does the actual blitting, and determines the concrete position, and if necessary (or desired) scales the input surface. Warning: When images are scaled with smoothing, colors will change decently, which makes it inappropriate to use in combination with colorkeys. :param margin: used to determine the exact location of the pygame.Surfaces within the available space. The margin value represents the proportion of the free space, along an axis, i.e. Margin(1, 1, 1, 1) is centered, Margin(0, 1, 1, 2) is as far left as possible and one/third on the way down. :type margin: Margin object :param scale: If 0 < scale <= 1 the longer side of the surface is scaled to to the given fraction of the available space, the aspect ratio is will be preserved. If scale is 0 the will be no scaling if the image is smaller than the available space. It will still be scaled down if it is too big. :type scale: float :param smooth: if True the result of the scaling will be smoothed :type smooth: float """ def __init__(self, margin=Margin(1, 1, 1, 1), scale=0, smooth=True): assert 0 <= scale <= 1 self.child = None self.margin = margin self.scale = scale self.smooth = smooth def __call__(self, child): _check_call_op(self.child) self.child = child return self @staticmethod def _scale_to_target(source, target_rect, smooth=False): target_size = source.get_rect().fit(target_rect).size return pygame.transform.scale(source, target_size) \ if not smooth else pygame.transform.smoothscale(source, target_size) def _determine_target_size(child, target_rect, scale): if scale > 0: return tuple(dist * scale for dist in target_rect.size) elif all(s_dim <= t_dim for s_dim, t_dim in zip(child.get_size(), target_rect.size)): return 0 else: return target_rect.size def compute_render_rect(self, target_rect): target_size = Surface._determine_target_size(self.child, target_rect, self.scale)\ or self.child.get_rect().size remaining_h_space = target_rect.w - target_size[0] remaining_v_space = target_rect.h - target_size[1] return pygame.Rect( (target_rect.left + _offset_by_margins(remaining_h_space, self.margin.left, self.margin.right), target_rect.top + _offset_by_margins(remaining_v_space, self.margin.top, self.margin.bottom)), target_size) def _draw(self, surface, target_rect): if self.child is None: return target_size = Surface._determine_target_size(self.child, target_rect, self.scale) content = Surface._scale_to_target(self.child, (0, 0, *target_size), self.smooth)\ if target_size else self.child remaining_h_space = target_rect.w - content.get_rect().w remaining_v_space = target_rect.h - content.get_rect().h surface.blit(content, ( target_rect.left + _offset_by_margins(remaining_h_space, self.margin.left, self.margin.right), target_rect.top + _offset_by_margins(remaining_v_space, self.margin.top, self.margin.bottom))) class Padding: """Pads a child element Each argument refers to a percentage of the axis it belongs to. A padding of (0.25, 0.25, 0.25, 0.25) would generate blocked area a quater of the available height in size above and below the child, and a quarter of the available width left and right of the child. If left and right or top and bottom sum up to one that would mean no space for the child is remaining """ def _draw(self, surface, target_rect): assert self.child is not None child_rect = pygame.Rect( target_rect.left + target_rect.w * self.left, target_rect.top + target_rect.h * self.top, target_rect.w * (1 - self.left - self.right), target_rect.h * (1 - self.top - self.bottom) ) self.child._draw(surface, child_rect) def __init__(self, left, right, top, bottom): assert all(0 <= side < 1 for side in [left, right, top, bottom]) assert left + right < 1 assert top + bottom < 1 self.left = left self.right = right self.top = top self.bottom = bottom self.child = None def __call__(self, child): _check_call_op(self.child) self.child = _wrap_children(child) return self @staticmethod def from_scale(scale_w, scale_h=None): """Creates a padding by the remaining space after scaling the content. E.g. Padding.from_scale(0.5) would produce Padding(0.25, 0.25, 0.25, 0.25) and Padding.from_scale(0.5, 1) would produce Padding(0.25, 0.25, 0, 0) because the content would not be scaled (since scale_h=1) and therefore there would be no vertical padding. If scale_h is not specified scale_h=scale_w is used as default :param scale_w: horizontal scaling factors :type scale_w: float :param scale_h: vertical scaling factor :type scale_h: float """ if not scale_h: scale_h = scale_w w_padding = [(1 - scale_w) * 0.5] * 2 h_padding = [(1 - scale_h) * 0.5] * 2 return Padding(*w_padding, *h_padding) class RectangleShaper: """Creates a padding, defined by a target Shape. Width and height are the relative proportions of the target rectangle. E.g RectangleShaper(1, 1) would create a square. and RectangleShaper(2, 1) would create a rectangle which is twice as wide as it is high. The rectangle always has the maximal possible size within the parent area. """ def __init__(self, width=1, height=1): self.child = None self.width = width self.height = height def __call__(self, child): _check_call_op(self.child) self.child = _wrap_children(child) return self def _draw(self, surface, target_rect): parent_w_factor = target_rect.w / target_rect.h my_w_factor = self.width / self.height if parent_w_factor > my_w_factor: my_h = target_rect.h my_w = my_h * my_w_factor my_h_offset = 0 my_w_offset = _round_to_int((target_rect.w - my_w) * 0.5) else: my_w = target_rect.w my_h = my_w / self.width * self.height my_w_offset = 0 my_h_offset = _round_to_int((target_rect.h - my_h) * 0.5) self.child._draw(surface, pygame.Rect( target_rect.left + my_w_offset, target_rect.top + my_h_offset, my_w, my_h )) class Circle: """Draws a Circle in the assigned space. The circle will always be centered, and the radius will be half of the shorter side of the assigned space. :param color: The color of the circle :type color: pygame.Color or int :param width: width of the circle (in pixels). If 0 the circle will be filled :type width: int """ def __init__(self, color, width=0): self.color = color self.width = width def _draw(self, surface, target_rect): pygame.draw.circle(surface, self.color, target_rect.center, int(round(min(target_rect.w, target_rect.h) * 0.5)), self.width) class Fill: """Fills the assigned area. Afterwards, the children are rendered :param color: the color with which the area is filled :type color: pygame.Color or int """ def __init__(self, color): self.color = color self.child = None def __call__(self, child): _check_call_op(self.child) self.child = _wrap_children(child) return self def _draw(self, surface, target_rect): surface.fill(self.color, target_rect) if self.child: self.child._draw(surface, target_rect) class Overlay: """Draws all its children on top of each other in the same rect""" def __init__(self, *children): self.children = _wrap_children(children) def _draw(self, surface, target_rect): for child in self.children: child._draw(surface, target_rect) def Cross(width=3, color=0): """Draws a cross centered in the target area :param width: width of the lines of the cross in pixels :type width: int :param color: color of the lines of the cross :type color: pygame.Color """ return Overlay(Line("h", width, color), Line("v", width, color)) class Border: """Draws a border around the contained area. Can have a single child. :param width: width of the border in pixels :type width: int :param color: color of the border :type color: pygame.Color """ def __init__(self, width=3, color=0): v_line = Line("v", width, color) h_line = Line("h", width, color) self.child_was_added = False self.overlay = Overlay( LinLayout("h")( LLItem(0)(v_line), LLItem(1), LLItem(0)(v_line) ), LinLayout("v")( LLItem(0)(h_line), LLItem(1), LLItem(0)(h_line) ) ) def __call__(self, child): _check_call_op(None if not self.child_was_added else 1) self.overlay.children.append(_wrap_children(child)) return self def _draw(self, surface, target_rect): self.overlay._draw(surface, target_rect) class Line: """Draws a line. :param width: width of the line in pixels :type widht: int :param orientation: "v" or "h". Indicates whether the line should be horizontal or vertical. :type orientation: str """ def __init__(self, orientation, width=3, color=0): assert orientation in ["h", "v"] assert width > 0 self.orientation = orientation self.width = width self.color = color def _draw(self, surface, target_rect): if self.orientation == "h": pygame.draw.line(surface, self.color, ( target_rect.left, _round_to_int(target_rect.top + target_rect.h * 0.5)), ( target_rect.left + target_rect.w - 1, _round_to_int(target_rect.top + target_rect.h * 0.5)), self.width) else: pygame.draw.line(surface, self.color, ( _round_to_int(target_rect.left + target_rect.width * 0.5), target_rect.top), ( _round_to_int(target_rect.left + target_rect.width * 0.5), target_rect.top + target_rect.h - 1), self.width) _fill_col = lambda target_len: lambda col: col + [None] * (target_len - len(col)) _to_h_layout = lambda cols: lambda children: LinLayout("h")( *_lmap(lambda it, child: it(child), map(LLItem, cols), _lmap(_wrap_surface, children))) def GridLayout(row_proportions=None, col_proportions=None): def inner_grid_layout(*children): nonlocal row_proportions, col_proportions assert all(type(child) == list for child in children) if row_proportions is None: row_proportions = [1] * len(children) else: assert len(row_proportions) == len(children) col_width = max(map(len, children)) if col_proportions: assert len(col_proportions) == col_width else: col_proportions = [1] * col_width filled_cols = _lmap(_fill_col(col_width), children) return LinLayout("v")(*_lmap( lambda it, child: it(child), map(LLItem, row_proportions), _lmap(_to_h_layout(col_proportions), children))) return inner_grid_layout def compose(target, root=None): """Top level function to create a surface. :param target: the pygame.Surface to blit on. Or a (width, height) tuple in which case a new surface will be created :type target: - """ if type(root) == Surface: raise ValueError("A Surface may not be used as root, please add " +"it as a single child i.e. compose(...)(Surface(...))") @_inner_func_anot def inner_compose(*children): if root: root_context = root(*children) else: assert len(children) == 1 root_context = children[0] if type(target) == pygame.Surface: surface = target size = target.get_size() else: size = target surface = pygame.Surface(size) root_context._draw(surface, pygame.Rect(0, 0, *size)) return surface return inner_compose @lru_cache(128) def Font(name=None, source="sys", italic=False, bold=False, size=20): """Unifies loading of fonts. :param name: name of system-font or filepath, if None is passed the default system-font is loaded :type name: str :param source: "sys" for system font, or "file" to load a file :type source: str """ assert source in ["sys", "file"] if not name: return pygame.font.SysFont(pygame.font.get_default_font(), size, bold=bold, italic=italic) if source == "sys": return pygame.font.SysFont(name, size, bold=bold, italic=italic) else: f = pygame.font.Font(name, size) f.set_italic(italic) f.set_bold(bold) return f def _text(text, font, color=pygame.Color(0, 0, 0), antialias=False): return font.render(text, antialias, color).convert_alpha() def Text(text, font, color=pygame.Color(0, 0, 0), antialias=False, align="center"): """Renders a text. Supports multiline text, the background will be transparent. :param align: text-alignment must be "center", "left", or "righ" :type align: str :return: the input text :rtype: pygame.Surface """ assert align in ["center", "left", "right"] margin_l, margin_r = 1, 1 if align == "left": margin_l = 0 elif align == "right": margin_r = 0 margin = Margin(margin_l, margin_r) color_key = pygame.Color(0, 0, 1) if pygame.Color(0, 0, 1) != color else 0x000002 text_surfaces = _lmap(lambda text: _text(text, font=font, color=color, antialias=antialias), map(methodcaller("strip"), text.split("\n"))) w = max(surf.get_rect().w for surf in text_surfaces) h = sum(surf.get_rect().h for surf in text_surfaces) surf = compose((w, h), Fill(color_key))(LinLayout("v")( *_lmap(lambda s: Surface(margin)(s), text_surfaces))) surf.set_colorkey(color_key) return surf.convert_alpha()
KnorrFG/pyparadigm
pyparadigm/surface_composition.py
Font
python
def Font(name=None, source="sys", italic=False, bold=False, size=20): assert source in ["sys", "file"] if not name: return pygame.font.SysFont(pygame.font.get_default_font(), size, bold=bold, italic=italic) if source == "sys": return pygame.font.SysFont(name, size, bold=bold, italic=italic) else: f = pygame.font.Font(name, size) f.set_italic(italic) f.set_bold(bold) return f
Unifies loading of fonts. :param name: name of system-font or filepath, if None is passed the default system-font is loaded :type name: str :param source: "sys" for system font, or "file" to load a file :type source: str
train
https://github.com/KnorrFG/pyparadigm/blob/69944cdf3ce2f6414ae1aa1d27a0d8c6e5fb3fd3/pyparadigm/surface_composition.py#L515-L536
null
"""Easy Image Composition The purpose of this module is to make it easy to compose the frames that are displayed in a paradigm. For an introduction, please refer to the :ref:`tutorial<creating_surfaces>` """ from functools import reduce, wraps, lru_cache, partial from itertools import accumulate from operator import add, methodcaller import contextlib with contextlib.redirect_stdout(None): import pygame _lmap = wraps(map)(lambda *args, **kwargs:list(map(*args, **kwargs))) _wrap_surface = lambda elem:\ Surface()(elem) if type(elem) == pygame.Surface else elem _round_to_int = lambda val: int(round(val)) _call_function = lambda elem:\ elem() if callable(elem) else elem def _inner_func_anot(func): """must be applied to all inner functions that return contexts. Wraps all instances of pygame.Surface in the input in Surface""" @wraps(func) def new_func(*args): return func(*_lmap(_wrap_surface, args)) return new_func def _wrap_children(children): try: return _lmap(_wrap_surface, children) except TypeError: return _wrap_surface(children) def _check_call_op(child): if child is not None: raise RuntimeError("Call operator was called twice") class LLItem: """Defines the relative size of an element in a LinLayout All Elements that are passed to a linear layout are automatically wrapped into an LLItem with relative_size=1. Therefore by default all elements within a layout will be of the same size. To change the proportions a LLItem can be used explicitely with another relative size. It is also possible to use an LLItem as placeholde in a layout, to generate an empty space like this: :Example: LinLayout("h")( LLItem(1), LLItem(1)(Circle(0xFFFF00))) """ def __init__(self, relative_size): self.child = Surface() self.relative_size = relative_size def __call__(self, child): self.child = _wrap_children(child) return self class LinLayout: """A linear layout to order items horizontally or vertically. Every element in the layout is automatically wrapped within a LLItem with relative_size=1, i.e. all elements get assigned an equal amount of space, to change that elements can be wrappend in LLItems manually to get desired proportions :param orientation: orientation of the layout, either 'v' for vertica, or 'h' for horizontal. :type orientation: str """ def __init__(self, orientation): assert orientation in ["v", "h"] self.orientation = orientation self.children = None def __call__(self, *children): _check_call_op(self.children) self.children = _lmap(lambda child: child if type(child) == LLItem else LLItem(1)(child), _wrap_children(children)) return self def _draw(self, surface, target_rect): child_rects = self._compute_child_rects(target_rect) for child, rect in zip(self.children, child_rects): child.child._draw(surface, rect) def _compute_child_rects(self, target_rect): flip_if_not_horizontal = lambda t: \ t if self.orientation == "h" else (t[1], t[0]) target_rect_size = target_rect.size divider, full = flip_if_not_horizontal(target_rect_size) dyn_size_per_unit = divider / sum(child.relative_size for child in self.children) strides = [child.relative_size * dyn_size_per_unit for child in self.children] dyn_offsets = [0] + list(accumulate(strides))[:-1] left_offsets, top_offsets = flip_if_not_horizontal((dyn_offsets, [0] * len(self.children))) widths, heights = flip_if_not_horizontal((strides, [full] * len(self.children))) return [pygame.Rect(target_rect.left + left_offset, target_rect.top + top_offset, w, h) for left_offset, top_offset, w, h in zip(left_offsets, top_offsets, widths, heights)] class Margin: """Defines the relative position of an item within a Surface. For details see Surface. """ __slots__ = ["left", "right", "top", "bottom"] def __init__(self, left=1, right=1, top=1, bottom=1): self.left=left self.right=right self.top=top self.bottom=bottom def _offset_by_margins(space, one, two): return space * one / (one + two) class Surface: """Wraps a pygame surface. The Surface is the connection between the absolute world of pygame.Surfaces and the relative world of the composition functions. A pygame.Surfaces can be bigger than the space that is available to the Surface, or smaller. The Surface does the actual blitting, and determines the concrete position, and if necessary (or desired) scales the input surface. Warning: When images are scaled with smoothing, colors will change decently, which makes it inappropriate to use in combination with colorkeys. :param margin: used to determine the exact location of the pygame.Surfaces within the available space. The margin value represents the proportion of the free space, along an axis, i.e. Margin(1, 1, 1, 1) is centered, Margin(0, 1, 1, 2) is as far left as possible and one/third on the way down. :type margin: Margin object :param scale: If 0 < scale <= 1 the longer side of the surface is scaled to to the given fraction of the available space, the aspect ratio is will be preserved. If scale is 0 the will be no scaling if the image is smaller than the available space. It will still be scaled down if it is too big. :type scale: float :param smooth: if True the result of the scaling will be smoothed :type smooth: float """ def __init__(self, margin=Margin(1, 1, 1, 1), scale=0, smooth=True): assert 0 <= scale <= 1 self.child = None self.margin = margin self.scale = scale self.smooth = smooth def __call__(self, child): _check_call_op(self.child) self.child = child return self @staticmethod def _scale_to_target(source, target_rect, smooth=False): target_size = source.get_rect().fit(target_rect).size return pygame.transform.scale(source, target_size) \ if not smooth else pygame.transform.smoothscale(source, target_size) def _determine_target_size(child, target_rect, scale): if scale > 0: return tuple(dist * scale for dist in target_rect.size) elif all(s_dim <= t_dim for s_dim, t_dim in zip(child.get_size(), target_rect.size)): return 0 else: return target_rect.size def compute_render_rect(self, target_rect): target_size = Surface._determine_target_size(self.child, target_rect, self.scale)\ or self.child.get_rect().size remaining_h_space = target_rect.w - target_size[0] remaining_v_space = target_rect.h - target_size[1] return pygame.Rect( (target_rect.left + _offset_by_margins(remaining_h_space, self.margin.left, self.margin.right), target_rect.top + _offset_by_margins(remaining_v_space, self.margin.top, self.margin.bottom)), target_size) def _draw(self, surface, target_rect): if self.child is None: return target_size = Surface._determine_target_size(self.child, target_rect, self.scale) content = Surface._scale_to_target(self.child, (0, 0, *target_size), self.smooth)\ if target_size else self.child remaining_h_space = target_rect.w - content.get_rect().w remaining_v_space = target_rect.h - content.get_rect().h surface.blit(content, ( target_rect.left + _offset_by_margins(remaining_h_space, self.margin.left, self.margin.right), target_rect.top + _offset_by_margins(remaining_v_space, self.margin.top, self.margin.bottom))) class Padding: """Pads a child element Each argument refers to a percentage of the axis it belongs to. A padding of (0.25, 0.25, 0.25, 0.25) would generate blocked area a quater of the available height in size above and below the child, and a quarter of the available width left and right of the child. If left and right or top and bottom sum up to one that would mean no space for the child is remaining """ def _draw(self, surface, target_rect): assert self.child is not None child_rect = pygame.Rect( target_rect.left + target_rect.w * self.left, target_rect.top + target_rect.h * self.top, target_rect.w * (1 - self.left - self.right), target_rect.h * (1 - self.top - self.bottom) ) self.child._draw(surface, child_rect) def __init__(self, left, right, top, bottom): assert all(0 <= side < 1 for side in [left, right, top, bottom]) assert left + right < 1 assert top + bottom < 1 self.left = left self.right = right self.top = top self.bottom = bottom self.child = None def __call__(self, child): _check_call_op(self.child) self.child = _wrap_children(child) return self @staticmethod def from_scale(scale_w, scale_h=None): """Creates a padding by the remaining space after scaling the content. E.g. Padding.from_scale(0.5) would produce Padding(0.25, 0.25, 0.25, 0.25) and Padding.from_scale(0.5, 1) would produce Padding(0.25, 0.25, 0, 0) because the content would not be scaled (since scale_h=1) and therefore there would be no vertical padding. If scale_h is not specified scale_h=scale_w is used as default :param scale_w: horizontal scaling factors :type scale_w: float :param scale_h: vertical scaling factor :type scale_h: float """ if not scale_h: scale_h = scale_w w_padding = [(1 - scale_w) * 0.5] * 2 h_padding = [(1 - scale_h) * 0.5] * 2 return Padding(*w_padding, *h_padding) class RectangleShaper: """Creates a padding, defined by a target Shape. Width and height are the relative proportions of the target rectangle. E.g RectangleShaper(1, 1) would create a square. and RectangleShaper(2, 1) would create a rectangle which is twice as wide as it is high. The rectangle always has the maximal possible size within the parent area. """ def __init__(self, width=1, height=1): self.child = None self.width = width self.height = height def __call__(self, child): _check_call_op(self.child) self.child = _wrap_children(child) return self def _draw(self, surface, target_rect): parent_w_factor = target_rect.w / target_rect.h my_w_factor = self.width / self.height if parent_w_factor > my_w_factor: my_h = target_rect.h my_w = my_h * my_w_factor my_h_offset = 0 my_w_offset = _round_to_int((target_rect.w - my_w) * 0.5) else: my_w = target_rect.w my_h = my_w / self.width * self.height my_w_offset = 0 my_h_offset = _round_to_int((target_rect.h - my_h) * 0.5) self.child._draw(surface, pygame.Rect( target_rect.left + my_w_offset, target_rect.top + my_h_offset, my_w, my_h )) class Circle: """Draws a Circle in the assigned space. The circle will always be centered, and the radius will be half of the shorter side of the assigned space. :param color: The color of the circle :type color: pygame.Color or int :param width: width of the circle (in pixels). If 0 the circle will be filled :type width: int """ def __init__(self, color, width=0): self.color = color self.width = width def _draw(self, surface, target_rect): pygame.draw.circle(surface, self.color, target_rect.center, int(round(min(target_rect.w, target_rect.h) * 0.5)), self.width) class Fill: """Fills the assigned area. Afterwards, the children are rendered :param color: the color with which the area is filled :type color: pygame.Color or int """ def __init__(self, color): self.color = color self.child = None def __call__(self, child): _check_call_op(self.child) self.child = _wrap_children(child) return self def _draw(self, surface, target_rect): surface.fill(self.color, target_rect) if self.child: self.child._draw(surface, target_rect) class Overlay: """Draws all its children on top of each other in the same rect""" def __init__(self, *children): self.children = _wrap_children(children) def _draw(self, surface, target_rect): for child in self.children: child._draw(surface, target_rect) def Cross(width=3, color=0): """Draws a cross centered in the target area :param width: width of the lines of the cross in pixels :type width: int :param color: color of the lines of the cross :type color: pygame.Color """ return Overlay(Line("h", width, color), Line("v", width, color)) class Border: """Draws a border around the contained area. Can have a single child. :param width: width of the border in pixels :type width: int :param color: color of the border :type color: pygame.Color """ def __init__(self, width=3, color=0): v_line = Line("v", width, color) h_line = Line("h", width, color) self.child_was_added = False self.overlay = Overlay( LinLayout("h")( LLItem(0)(v_line), LLItem(1), LLItem(0)(v_line) ), LinLayout("v")( LLItem(0)(h_line), LLItem(1), LLItem(0)(h_line) ) ) def __call__(self, child): _check_call_op(None if not self.child_was_added else 1) self.overlay.children.append(_wrap_children(child)) return self def _draw(self, surface, target_rect): self.overlay._draw(surface, target_rect) class Line: """Draws a line. :param width: width of the line in pixels :type widht: int :param orientation: "v" or "h". Indicates whether the line should be horizontal or vertical. :type orientation: str """ def __init__(self, orientation, width=3, color=0): assert orientation in ["h", "v"] assert width > 0 self.orientation = orientation self.width = width self.color = color def _draw(self, surface, target_rect): if self.orientation == "h": pygame.draw.line(surface, self.color, ( target_rect.left, _round_to_int(target_rect.top + target_rect.h * 0.5)), ( target_rect.left + target_rect.w - 1, _round_to_int(target_rect.top + target_rect.h * 0.5)), self.width) else: pygame.draw.line(surface, self.color, ( _round_to_int(target_rect.left + target_rect.width * 0.5), target_rect.top), ( _round_to_int(target_rect.left + target_rect.width * 0.5), target_rect.top + target_rect.h - 1), self.width) _fill_col = lambda target_len: lambda col: col + [None] * (target_len - len(col)) _to_h_layout = lambda cols: lambda children: LinLayout("h")( *_lmap(lambda it, child: it(child), map(LLItem, cols), _lmap(_wrap_surface, children))) def GridLayout(row_proportions=None, col_proportions=None): def inner_grid_layout(*children): nonlocal row_proportions, col_proportions assert all(type(child) == list for child in children) if row_proportions is None: row_proportions = [1] * len(children) else: assert len(row_proportions) == len(children) col_width = max(map(len, children)) if col_proportions: assert len(col_proportions) == col_width else: col_proportions = [1] * col_width filled_cols = _lmap(_fill_col(col_width), children) return LinLayout("v")(*_lmap( lambda it, child: it(child), map(LLItem, row_proportions), _lmap(_to_h_layout(col_proportions), children))) return inner_grid_layout def compose(target, root=None): """Top level function to create a surface. :param target: the pygame.Surface to blit on. Or a (width, height) tuple in which case a new surface will be created :type target: - """ if type(root) == Surface: raise ValueError("A Surface may not be used as root, please add " +"it as a single child i.e. compose(...)(Surface(...))") @_inner_func_anot def inner_compose(*children): if root: root_context = root(*children) else: assert len(children) == 1 root_context = children[0] if type(target) == pygame.Surface: surface = target size = target.get_size() else: size = target surface = pygame.Surface(size) root_context._draw(surface, pygame.Rect(0, 0, *size)) return surface return inner_compose @lru_cache(128) def _text(text, font, color=pygame.Color(0, 0, 0), antialias=False): return font.render(text, antialias, color).convert_alpha() def Text(text, font, color=pygame.Color(0, 0, 0), antialias=False, align="center"): """Renders a text. Supports multiline text, the background will be transparent. :param align: text-alignment must be "center", "left", or "righ" :type align: str :return: the input text :rtype: pygame.Surface """ assert align in ["center", "left", "right"] margin_l, margin_r = 1, 1 if align == "left": margin_l = 0 elif align == "right": margin_r = 0 margin = Margin(margin_l, margin_r) color_key = pygame.Color(0, 0, 1) if pygame.Color(0, 0, 1) != color else 0x000002 text_surfaces = _lmap(lambda text: _text(text, font=font, color=color, antialias=antialias), map(methodcaller("strip"), text.split("\n"))) w = max(surf.get_rect().w for surf in text_surfaces) h = sum(surf.get_rect().h for surf in text_surfaces) surf = compose((w, h), Fill(color_key))(LinLayout("v")( *_lmap(lambda s: Surface(margin)(s), text_surfaces))) surf.set_colorkey(color_key) return surf.convert_alpha()
KnorrFG/pyparadigm
pyparadigm/surface_composition.py
Text
python
def Text(text, font, color=pygame.Color(0, 0, 0), antialias=False, align="center"): assert align in ["center", "left", "right"] margin_l, margin_r = 1, 1 if align == "left": margin_l = 0 elif align == "right": margin_r = 0 margin = Margin(margin_l, margin_r) color_key = pygame.Color(0, 0, 1) if pygame.Color(0, 0, 1) != color else 0x000002 text_surfaces = _lmap(lambda text: _text(text, font=font, color=color, antialias=antialias), map(methodcaller("strip"), text.split("\n"))) w = max(surf.get_rect().w for surf in text_surfaces) h = sum(surf.get_rect().h for surf in text_surfaces) surf = compose((w, h), Fill(color_key))(LinLayout("v")( *_lmap(lambda s: Surface(margin)(s), text_surfaces))) surf.set_colorkey(color_key) return surf.convert_alpha()
Renders a text. Supports multiline text, the background will be transparent. :param align: text-alignment must be "center", "left", or "righ" :type align: str :return: the input text :rtype: pygame.Surface
train
https://github.com/KnorrFG/pyparadigm/blob/69944cdf3ce2f6414ae1aa1d27a0d8c6e5fb3fd3/pyparadigm/surface_composition.py#L543-L566
[ "def compose(target, root=None):\n \"\"\"Top level function to create a surface.\n\n :param target: the pygame.Surface to blit on. Or a (width, height) tuple\n in which case a new surface will be created\n\n :type target: -\n \"\"\"\n if type(root) == Surface:\n raise ValueError(\"A Sur...
"""Easy Image Composition The purpose of this module is to make it easy to compose the frames that are displayed in a paradigm. For an introduction, please refer to the :ref:`tutorial<creating_surfaces>` """ from functools import reduce, wraps, lru_cache, partial from itertools import accumulate from operator import add, methodcaller import contextlib with contextlib.redirect_stdout(None): import pygame _lmap = wraps(map)(lambda *args, **kwargs:list(map(*args, **kwargs))) _wrap_surface = lambda elem:\ Surface()(elem) if type(elem) == pygame.Surface else elem _round_to_int = lambda val: int(round(val)) _call_function = lambda elem:\ elem() if callable(elem) else elem def _inner_func_anot(func): """must be applied to all inner functions that return contexts. Wraps all instances of pygame.Surface in the input in Surface""" @wraps(func) def new_func(*args): return func(*_lmap(_wrap_surface, args)) return new_func def _wrap_children(children): try: return _lmap(_wrap_surface, children) except TypeError: return _wrap_surface(children) def _check_call_op(child): if child is not None: raise RuntimeError("Call operator was called twice") class LLItem: """Defines the relative size of an element in a LinLayout All Elements that are passed to a linear layout are automatically wrapped into an LLItem with relative_size=1. Therefore by default all elements within a layout will be of the same size. To change the proportions a LLItem can be used explicitely with another relative size. It is also possible to use an LLItem as placeholde in a layout, to generate an empty space like this: :Example: LinLayout("h")( LLItem(1), LLItem(1)(Circle(0xFFFF00))) """ def __init__(self, relative_size): self.child = Surface() self.relative_size = relative_size def __call__(self, child): self.child = _wrap_children(child) return self class LinLayout: """A linear layout to order items horizontally or vertically. Every element in the layout is automatically wrapped within a LLItem with relative_size=1, i.e. all elements get assigned an equal amount of space, to change that elements can be wrappend in LLItems manually to get desired proportions :param orientation: orientation of the layout, either 'v' for vertica, or 'h' for horizontal. :type orientation: str """ def __init__(self, orientation): assert orientation in ["v", "h"] self.orientation = orientation self.children = None def __call__(self, *children): _check_call_op(self.children) self.children = _lmap(lambda child: child if type(child) == LLItem else LLItem(1)(child), _wrap_children(children)) return self def _draw(self, surface, target_rect): child_rects = self._compute_child_rects(target_rect) for child, rect in zip(self.children, child_rects): child.child._draw(surface, rect) def _compute_child_rects(self, target_rect): flip_if_not_horizontal = lambda t: \ t if self.orientation == "h" else (t[1], t[0]) target_rect_size = target_rect.size divider, full = flip_if_not_horizontal(target_rect_size) dyn_size_per_unit = divider / sum(child.relative_size for child in self.children) strides = [child.relative_size * dyn_size_per_unit for child in self.children] dyn_offsets = [0] + list(accumulate(strides))[:-1] left_offsets, top_offsets = flip_if_not_horizontal((dyn_offsets, [0] * len(self.children))) widths, heights = flip_if_not_horizontal((strides, [full] * len(self.children))) return [pygame.Rect(target_rect.left + left_offset, target_rect.top + top_offset, w, h) for left_offset, top_offset, w, h in zip(left_offsets, top_offsets, widths, heights)] class Margin: """Defines the relative position of an item within a Surface. For details see Surface. """ __slots__ = ["left", "right", "top", "bottom"] def __init__(self, left=1, right=1, top=1, bottom=1): self.left=left self.right=right self.top=top self.bottom=bottom def _offset_by_margins(space, one, two): return space * one / (one + two) class Surface: """Wraps a pygame surface. The Surface is the connection between the absolute world of pygame.Surfaces and the relative world of the composition functions. A pygame.Surfaces can be bigger than the space that is available to the Surface, or smaller. The Surface does the actual blitting, and determines the concrete position, and if necessary (or desired) scales the input surface. Warning: When images are scaled with smoothing, colors will change decently, which makes it inappropriate to use in combination with colorkeys. :param margin: used to determine the exact location of the pygame.Surfaces within the available space. The margin value represents the proportion of the free space, along an axis, i.e. Margin(1, 1, 1, 1) is centered, Margin(0, 1, 1, 2) is as far left as possible and one/third on the way down. :type margin: Margin object :param scale: If 0 < scale <= 1 the longer side of the surface is scaled to to the given fraction of the available space, the aspect ratio is will be preserved. If scale is 0 the will be no scaling if the image is smaller than the available space. It will still be scaled down if it is too big. :type scale: float :param smooth: if True the result of the scaling will be smoothed :type smooth: float """ def __init__(self, margin=Margin(1, 1, 1, 1), scale=0, smooth=True): assert 0 <= scale <= 1 self.child = None self.margin = margin self.scale = scale self.smooth = smooth def __call__(self, child): _check_call_op(self.child) self.child = child return self @staticmethod def _scale_to_target(source, target_rect, smooth=False): target_size = source.get_rect().fit(target_rect).size return pygame.transform.scale(source, target_size) \ if not smooth else pygame.transform.smoothscale(source, target_size) def _determine_target_size(child, target_rect, scale): if scale > 0: return tuple(dist * scale for dist in target_rect.size) elif all(s_dim <= t_dim for s_dim, t_dim in zip(child.get_size(), target_rect.size)): return 0 else: return target_rect.size def compute_render_rect(self, target_rect): target_size = Surface._determine_target_size(self.child, target_rect, self.scale)\ or self.child.get_rect().size remaining_h_space = target_rect.w - target_size[0] remaining_v_space = target_rect.h - target_size[1] return pygame.Rect( (target_rect.left + _offset_by_margins(remaining_h_space, self.margin.left, self.margin.right), target_rect.top + _offset_by_margins(remaining_v_space, self.margin.top, self.margin.bottom)), target_size) def _draw(self, surface, target_rect): if self.child is None: return target_size = Surface._determine_target_size(self.child, target_rect, self.scale) content = Surface._scale_to_target(self.child, (0, 0, *target_size), self.smooth)\ if target_size else self.child remaining_h_space = target_rect.w - content.get_rect().w remaining_v_space = target_rect.h - content.get_rect().h surface.blit(content, ( target_rect.left + _offset_by_margins(remaining_h_space, self.margin.left, self.margin.right), target_rect.top + _offset_by_margins(remaining_v_space, self.margin.top, self.margin.bottom))) class Padding: """Pads a child element Each argument refers to a percentage of the axis it belongs to. A padding of (0.25, 0.25, 0.25, 0.25) would generate blocked area a quater of the available height in size above and below the child, and a quarter of the available width left and right of the child. If left and right or top and bottom sum up to one that would mean no space for the child is remaining """ def _draw(self, surface, target_rect): assert self.child is not None child_rect = pygame.Rect( target_rect.left + target_rect.w * self.left, target_rect.top + target_rect.h * self.top, target_rect.w * (1 - self.left - self.right), target_rect.h * (1 - self.top - self.bottom) ) self.child._draw(surface, child_rect) def __init__(self, left, right, top, bottom): assert all(0 <= side < 1 for side in [left, right, top, bottom]) assert left + right < 1 assert top + bottom < 1 self.left = left self.right = right self.top = top self.bottom = bottom self.child = None def __call__(self, child): _check_call_op(self.child) self.child = _wrap_children(child) return self @staticmethod def from_scale(scale_w, scale_h=None): """Creates a padding by the remaining space after scaling the content. E.g. Padding.from_scale(0.5) would produce Padding(0.25, 0.25, 0.25, 0.25) and Padding.from_scale(0.5, 1) would produce Padding(0.25, 0.25, 0, 0) because the content would not be scaled (since scale_h=1) and therefore there would be no vertical padding. If scale_h is not specified scale_h=scale_w is used as default :param scale_w: horizontal scaling factors :type scale_w: float :param scale_h: vertical scaling factor :type scale_h: float """ if not scale_h: scale_h = scale_w w_padding = [(1 - scale_w) * 0.5] * 2 h_padding = [(1 - scale_h) * 0.5] * 2 return Padding(*w_padding, *h_padding) class RectangleShaper: """Creates a padding, defined by a target Shape. Width and height are the relative proportions of the target rectangle. E.g RectangleShaper(1, 1) would create a square. and RectangleShaper(2, 1) would create a rectangle which is twice as wide as it is high. The rectangle always has the maximal possible size within the parent area. """ def __init__(self, width=1, height=1): self.child = None self.width = width self.height = height def __call__(self, child): _check_call_op(self.child) self.child = _wrap_children(child) return self def _draw(self, surface, target_rect): parent_w_factor = target_rect.w / target_rect.h my_w_factor = self.width / self.height if parent_w_factor > my_w_factor: my_h = target_rect.h my_w = my_h * my_w_factor my_h_offset = 0 my_w_offset = _round_to_int((target_rect.w - my_w) * 0.5) else: my_w = target_rect.w my_h = my_w / self.width * self.height my_w_offset = 0 my_h_offset = _round_to_int((target_rect.h - my_h) * 0.5) self.child._draw(surface, pygame.Rect( target_rect.left + my_w_offset, target_rect.top + my_h_offset, my_w, my_h )) class Circle: """Draws a Circle in the assigned space. The circle will always be centered, and the radius will be half of the shorter side of the assigned space. :param color: The color of the circle :type color: pygame.Color or int :param width: width of the circle (in pixels). If 0 the circle will be filled :type width: int """ def __init__(self, color, width=0): self.color = color self.width = width def _draw(self, surface, target_rect): pygame.draw.circle(surface, self.color, target_rect.center, int(round(min(target_rect.w, target_rect.h) * 0.5)), self.width) class Fill: """Fills the assigned area. Afterwards, the children are rendered :param color: the color with which the area is filled :type color: pygame.Color or int """ def __init__(self, color): self.color = color self.child = None def __call__(self, child): _check_call_op(self.child) self.child = _wrap_children(child) return self def _draw(self, surface, target_rect): surface.fill(self.color, target_rect) if self.child: self.child._draw(surface, target_rect) class Overlay: """Draws all its children on top of each other in the same rect""" def __init__(self, *children): self.children = _wrap_children(children) def _draw(self, surface, target_rect): for child in self.children: child._draw(surface, target_rect) def Cross(width=3, color=0): """Draws a cross centered in the target area :param width: width of the lines of the cross in pixels :type width: int :param color: color of the lines of the cross :type color: pygame.Color """ return Overlay(Line("h", width, color), Line("v", width, color)) class Border: """Draws a border around the contained area. Can have a single child. :param width: width of the border in pixels :type width: int :param color: color of the border :type color: pygame.Color """ def __init__(self, width=3, color=0): v_line = Line("v", width, color) h_line = Line("h", width, color) self.child_was_added = False self.overlay = Overlay( LinLayout("h")( LLItem(0)(v_line), LLItem(1), LLItem(0)(v_line) ), LinLayout("v")( LLItem(0)(h_line), LLItem(1), LLItem(0)(h_line) ) ) def __call__(self, child): _check_call_op(None if not self.child_was_added else 1) self.overlay.children.append(_wrap_children(child)) return self def _draw(self, surface, target_rect): self.overlay._draw(surface, target_rect) class Line: """Draws a line. :param width: width of the line in pixels :type widht: int :param orientation: "v" or "h". Indicates whether the line should be horizontal or vertical. :type orientation: str """ def __init__(self, orientation, width=3, color=0): assert orientation in ["h", "v"] assert width > 0 self.orientation = orientation self.width = width self.color = color def _draw(self, surface, target_rect): if self.orientation == "h": pygame.draw.line(surface, self.color, ( target_rect.left, _round_to_int(target_rect.top + target_rect.h * 0.5)), ( target_rect.left + target_rect.w - 1, _round_to_int(target_rect.top + target_rect.h * 0.5)), self.width) else: pygame.draw.line(surface, self.color, ( _round_to_int(target_rect.left + target_rect.width * 0.5), target_rect.top), ( _round_to_int(target_rect.left + target_rect.width * 0.5), target_rect.top + target_rect.h - 1), self.width) _fill_col = lambda target_len: lambda col: col + [None] * (target_len - len(col)) _to_h_layout = lambda cols: lambda children: LinLayout("h")( *_lmap(lambda it, child: it(child), map(LLItem, cols), _lmap(_wrap_surface, children))) def GridLayout(row_proportions=None, col_proportions=None): def inner_grid_layout(*children): nonlocal row_proportions, col_proportions assert all(type(child) == list for child in children) if row_proportions is None: row_proportions = [1] * len(children) else: assert len(row_proportions) == len(children) col_width = max(map(len, children)) if col_proportions: assert len(col_proportions) == col_width else: col_proportions = [1] * col_width filled_cols = _lmap(_fill_col(col_width), children) return LinLayout("v")(*_lmap( lambda it, child: it(child), map(LLItem, row_proportions), _lmap(_to_h_layout(col_proportions), children))) return inner_grid_layout def compose(target, root=None): """Top level function to create a surface. :param target: the pygame.Surface to blit on. Or a (width, height) tuple in which case a new surface will be created :type target: - """ if type(root) == Surface: raise ValueError("A Surface may not be used as root, please add " +"it as a single child i.e. compose(...)(Surface(...))") @_inner_func_anot def inner_compose(*children): if root: root_context = root(*children) else: assert len(children) == 1 root_context = children[0] if type(target) == pygame.Surface: surface = target size = target.get_size() else: size = target surface = pygame.Surface(size) root_context._draw(surface, pygame.Rect(0, 0, *size)) return surface return inner_compose @lru_cache(128) def Font(name=None, source="sys", italic=False, bold=False, size=20): """Unifies loading of fonts. :param name: name of system-font or filepath, if None is passed the default system-font is loaded :type name: str :param source: "sys" for system font, or "file" to load a file :type source: str """ assert source in ["sys", "file"] if not name: return pygame.font.SysFont(pygame.font.get_default_font(), size, bold=bold, italic=italic) if source == "sys": return pygame.font.SysFont(name, size, bold=bold, italic=italic) else: f = pygame.font.Font(name, size) f.set_italic(italic) f.set_bold(bold) return f def _text(text, font, color=pygame.Color(0, 0, 0), antialias=False): return font.render(text, antialias, color).convert_alpha() def Text(text, font, color=pygame.Color(0, 0, 0), antialias=False, align="center"): """Renders a text. Supports multiline text, the background will be transparent. :param align: text-alignment must be "center", "left", or "righ" :type align: str :return: the input text :rtype: pygame.Surface """ assert align in ["center", "left", "right"] margin_l, margin_r = 1, 1 if align == "left": margin_l = 0 elif align == "right": margin_r = 0 margin = Margin(margin_l, margin_r) color_key = pygame.Color(0, 0, 1) if pygame.Color(0, 0, 1) != color else 0x000002 text_surfaces = _lmap(lambda text: _text(text, font=font, color=color, antialias=antialias), map(methodcaller("strip"), text.split("\n"))) w = max(surf.get_rect().w for surf in text_surfaces) h = sum(surf.get_rect().h for surf in text_surfaces) surf = compose((w, h), Fill(color_key))(LinLayout("v")( *_lmap(lambda s: Surface(margin)(s), text_surfaces))) surf.set_colorkey(color_key) return surf.convert_alpha()
KnorrFG/pyparadigm
pyparadigm/surface_composition.py
Padding.from_scale
python
def from_scale(scale_w, scale_h=None): if not scale_h: scale_h = scale_w w_padding = [(1 - scale_w) * 0.5] * 2 h_padding = [(1 - scale_h) * 0.5] * 2 return Padding(*w_padding, *h_padding)
Creates a padding by the remaining space after scaling the content. E.g. Padding.from_scale(0.5) would produce Padding(0.25, 0.25, 0.25, 0.25) and Padding.from_scale(0.5, 1) would produce Padding(0.25, 0.25, 0, 0) because the content would not be scaled (since scale_h=1) and therefore there would be no vertical padding. If scale_h is not specified scale_h=scale_w is used as default :param scale_w: horizontal scaling factors :type scale_w: float :param scale_h: vertical scaling factor :type scale_h: float
train
https://github.com/KnorrFG/pyparadigm/blob/69944cdf3ce2f6414ae1aa1d27a0d8c6e5fb3fd3/pyparadigm/surface_composition.py#L264-L282
null
class Padding: """Pads a child element Each argument refers to a percentage of the axis it belongs to. A padding of (0.25, 0.25, 0.25, 0.25) would generate blocked area a quater of the available height in size above and below the child, and a quarter of the available width left and right of the child. If left and right or top and bottom sum up to one that would mean no space for the child is remaining """ def _draw(self, surface, target_rect): assert self.child is not None child_rect = pygame.Rect( target_rect.left + target_rect.w * self.left, target_rect.top + target_rect.h * self.top, target_rect.w * (1 - self.left - self.right), target_rect.h * (1 - self.top - self.bottom) ) self.child._draw(surface, child_rect) def __init__(self, left, right, top, bottom): assert all(0 <= side < 1 for side in [left, right, top, bottom]) assert left + right < 1 assert top + bottom < 1 self.left = left self.right = right self.top = top self.bottom = bottom self.child = None def __call__(self, child): _check_call_op(self.child) self.child = _wrap_children(child) return self @staticmethod def from_scale(scale_w, scale_h=None): """Creates a padding by the remaining space after scaling the content. E.g. Padding.from_scale(0.5) would produce Padding(0.25, 0.25, 0.25, 0.25) and Padding.from_scale(0.5, 1) would produce Padding(0.25, 0.25, 0, 0) because the content would not be scaled (since scale_h=1) and therefore there would be no vertical padding. If scale_h is not specified scale_h=scale_w is used as default :param scale_w: horizontal scaling factors :type scale_w: float :param scale_h: vertical scaling factor :type scale_h: float """ if not scale_h: scale_h = scale_w w_padding = [(1 - scale_w) * 0.5] * 2 h_padding = [(1 - scale_h) * 0.5] * 2 return Padding(*w_padding, *h_padding)
KnorrFG/pyparadigm
pyparadigm/misc.py
init
python
def init(resolution, pygame_flags=0, display_pos=(0, 0), interactive_mode=False): os.environ['SDL_VIDEO_WINDOW_POS'] = "{}, {}".format(*display_pos) pygame.init() pygame.font.init() disp = pygame.display.set_mode(resolution, pygame_flags) return _PumpThread() if interactive_mode else disp
Creates a window of given resolution. :param resolution: the resolution of the windows as (width, height) in pixels :type resolution: tuple :param pygame_flags: modify the creation of the window. For further information see :ref:`creating_a_window` :type pygame_flags: int :param display_pos: determines the position on the desktop where the window is created. In a multi monitor system this can be used to position the window on a different monitor. E.g. the monitor to the right of the main-monitor would be at position (1920, 0) if the main monitor has the width 1920. :type display_pos: tuple :param interactive_mode: Will install a thread, that emptys the event-queue every 100ms. This is neccessary to be able to use the display() function in an interactive console on windows systems. If interactive_mode is set, init() will return a reference to the background thread. This thread has a stop() method which can be used to cancel it. If you use ctrl+d or exit() within ipython, while the thread is still running, ipython will become unusable, but not close. :type interactive_mode: bool :return: a reference to the display screen, or a reference to the background thread if interactive_mode was set to true. In the second scenario you can obtain a reference to the display surface via pygame.display.get_surface() :rtype: pygame.Surface
train
https://github.com/KnorrFG/pyparadigm/blob/69944cdf3ce2f6414ae1aa1d27a0d8c6e5fb3fd3/pyparadigm/misc.py#L32-L68
null
"""Contains code that did not make it into an own module. """ import contextlib with contextlib.redirect_stdout(None): import pygame from . import surface_composition as sc import os import time from functools import lru_cache from threading import Thread class _PumpThread(Thread): """See the documentation for the interactive_mode arg from :ref:`init`""" def run(self): while self._run: pygame.event.pump() time.sleep(0.1) def stop(self): self._run = False self.join() def __init__(self): super().__init__() self._run = True self.start() def init(resolution, pygame_flags=0, display_pos=(0, 0), interactive_mode=False): """Creates a window of given resolution. :param resolution: the resolution of the windows as (width, height) in pixels :type resolution: tuple :param pygame_flags: modify the creation of the window. For further information see :ref:`creating_a_window` :type pygame_flags: int :param display_pos: determines the position on the desktop where the window is created. In a multi monitor system this can be used to position the window on a different monitor. E.g. the monitor to the right of the main-monitor would be at position (1920, 0) if the main monitor has the width 1920. :type display_pos: tuple :param interactive_mode: Will install a thread, that emptys the event-queue every 100ms. This is neccessary to be able to use the display() function in an interactive console on windows systems. If interactive_mode is set, init() will return a reference to the background thread. This thread has a stop() method which can be used to cancel it. If you use ctrl+d or exit() within ipython, while the thread is still running, ipython will become unusable, but not close. :type interactive_mode: bool :return: a reference to the display screen, or a reference to the background thread if interactive_mode was set to true. In the second scenario you can obtain a reference to the display surface via pygame.display.get_surface() :rtype: pygame.Surface """ os.environ['SDL_VIDEO_WINDOW_POS'] = "{}, {}".format(*display_pos) pygame.init() pygame.font.init() disp = pygame.display.set_mode(resolution, pygame_flags) return _PumpThread() if interactive_mode else disp def display(surface): """Displays a pygame.Surface in the window. in pygame the window is represented through a surface, on which you can draw as on any other pygame.Surface. A refernce to to the screen can be optained via the :py:func:`pygame.display.get_surface` function. To display the contents of the screen surface in the window :py:func:`pygame.display.flip` needs to be called. :py:func:`display` draws the surface onto the screen surface at the postion (0, 0), and then calls :py:func:`flip`. :param surface: the pygame.Surface to display :type surface: pygame.Surface """ screen = pygame.display.get_surface() screen.blit(surface, (0, 0)) pygame.display.flip() def slide_show(slides, continue_handler): """Displays one "slide" after another. After displaying a slide, continue_handler is called without arguments. When continue_handler returns, the next slide is displayed. Usage example :: slide_show(text_screens, partial(event_listener.wait_for_n_keypresses, pygame.K_RETURN)) (partial is imported from the functools module.) :param slides: pygame.Surfaces to be displayed. :type slides: iterable :param continue_handler: function, that returns when the next slide should be displayed. :type continue_handler: callable with arity 0. """ for slide in slides: display(slide) continue_handler() def empty_surface(fill_color, size=None): """Returns an empty surface filled with fill_color. :param fill_color: color to fill the surface with :type fill_color: pygame.Color :param size: the size of the new surface, if None its created to be the same size as the screen :type size: int-2-tuple """ sr = pygame.display.get_surface().get_rect() surf = pygame.Surface(size or (sr.w, sr.h)) surf.fill(fill_color) return surf _char_mappings = { "\r": "\n", "\t": " " } def process_char(buffer: str, char: str, mappings=_char_mappings): """This is a convinience method for use with EventListener.wait_for_unicode_char(). In most cases it simply appends char to buffer. Some replacements are done because presing return will produce '\\r' but for most cases '\\n' would be desireable. Also backspace cant just be added to a string either, therefore, if char is "\\u0008" the last character from buffer will be cut off. The replacement from '\\r' to '\\n' is done using the mappings argument, the default value for it also contains a mapping from '\t' to 4 spaces. :param buffer: the string to be updated :type buffer: str :param char: the unicode character to be processed :type char: str :param mappings: a dict containing mappings :type mappings: dict :returns: a new string""" if char in mappings: return buffer + mappings[char] elif char == "\u0008": return buffer[:-1] if len(buffer) > 0 else buffer else: return buffer + char
KnorrFG/pyparadigm
pyparadigm/misc.py
display
python
def display(surface): screen = pygame.display.get_surface() screen.blit(surface, (0, 0)) pygame.display.flip()
Displays a pygame.Surface in the window. in pygame the window is represented through a surface, on which you can draw as on any other pygame.Surface. A refernce to to the screen can be optained via the :py:func:`pygame.display.get_surface` function. To display the contents of the screen surface in the window :py:func:`pygame.display.flip` needs to be called. :py:func:`display` draws the surface onto the screen surface at the postion (0, 0), and then calls :py:func:`flip`. :param surface: the pygame.Surface to display :type surface: pygame.Surface
train
https://github.com/KnorrFG/pyparadigm/blob/69944cdf3ce2f6414ae1aa1d27a0d8c6e5fb3fd3/pyparadigm/misc.py#L70-L87
null
"""Contains code that did not make it into an own module. """ import contextlib with contextlib.redirect_stdout(None): import pygame from . import surface_composition as sc import os import time from functools import lru_cache from threading import Thread class _PumpThread(Thread): """See the documentation for the interactive_mode arg from :ref:`init`""" def run(self): while self._run: pygame.event.pump() time.sleep(0.1) def stop(self): self._run = False self.join() def __init__(self): super().__init__() self._run = True self.start() def init(resolution, pygame_flags=0, display_pos=(0, 0), interactive_mode=False): """Creates a window of given resolution. :param resolution: the resolution of the windows as (width, height) in pixels :type resolution: tuple :param pygame_flags: modify the creation of the window. For further information see :ref:`creating_a_window` :type pygame_flags: int :param display_pos: determines the position on the desktop where the window is created. In a multi monitor system this can be used to position the window on a different monitor. E.g. the monitor to the right of the main-monitor would be at position (1920, 0) if the main monitor has the width 1920. :type display_pos: tuple :param interactive_mode: Will install a thread, that emptys the event-queue every 100ms. This is neccessary to be able to use the display() function in an interactive console on windows systems. If interactive_mode is set, init() will return a reference to the background thread. This thread has a stop() method which can be used to cancel it. If you use ctrl+d or exit() within ipython, while the thread is still running, ipython will become unusable, but not close. :type interactive_mode: bool :return: a reference to the display screen, or a reference to the background thread if interactive_mode was set to true. In the second scenario you can obtain a reference to the display surface via pygame.display.get_surface() :rtype: pygame.Surface """ os.environ['SDL_VIDEO_WINDOW_POS'] = "{}, {}".format(*display_pos) pygame.init() pygame.font.init() disp = pygame.display.set_mode(resolution, pygame_flags) return _PumpThread() if interactive_mode else disp def display(surface): """Displays a pygame.Surface in the window. in pygame the window is represented through a surface, on which you can draw as on any other pygame.Surface. A refernce to to the screen can be optained via the :py:func:`pygame.display.get_surface` function. To display the contents of the screen surface in the window :py:func:`pygame.display.flip` needs to be called. :py:func:`display` draws the surface onto the screen surface at the postion (0, 0), and then calls :py:func:`flip`. :param surface: the pygame.Surface to display :type surface: pygame.Surface """ screen = pygame.display.get_surface() screen.blit(surface, (0, 0)) pygame.display.flip() def slide_show(slides, continue_handler): """Displays one "slide" after another. After displaying a slide, continue_handler is called without arguments. When continue_handler returns, the next slide is displayed. Usage example :: slide_show(text_screens, partial(event_listener.wait_for_n_keypresses, pygame.K_RETURN)) (partial is imported from the functools module.) :param slides: pygame.Surfaces to be displayed. :type slides: iterable :param continue_handler: function, that returns when the next slide should be displayed. :type continue_handler: callable with arity 0. """ for slide in slides: display(slide) continue_handler() def empty_surface(fill_color, size=None): """Returns an empty surface filled with fill_color. :param fill_color: color to fill the surface with :type fill_color: pygame.Color :param size: the size of the new surface, if None its created to be the same size as the screen :type size: int-2-tuple """ sr = pygame.display.get_surface().get_rect() surf = pygame.Surface(size or (sr.w, sr.h)) surf.fill(fill_color) return surf _char_mappings = { "\r": "\n", "\t": " " } def process_char(buffer: str, char: str, mappings=_char_mappings): """This is a convinience method for use with EventListener.wait_for_unicode_char(). In most cases it simply appends char to buffer. Some replacements are done because presing return will produce '\\r' but for most cases '\\n' would be desireable. Also backspace cant just be added to a string either, therefore, if char is "\\u0008" the last character from buffer will be cut off. The replacement from '\\r' to '\\n' is done using the mappings argument, the default value for it also contains a mapping from '\t' to 4 spaces. :param buffer: the string to be updated :type buffer: str :param char: the unicode character to be processed :type char: str :param mappings: a dict containing mappings :type mappings: dict :returns: a new string""" if char in mappings: return buffer + mappings[char] elif char == "\u0008": return buffer[:-1] if len(buffer) > 0 else buffer else: return buffer + char
KnorrFG/pyparadigm
pyparadigm/misc.py
empty_surface
python
def empty_surface(fill_color, size=None): sr = pygame.display.get_surface().get_rect() surf = pygame.Surface(size or (sr.w, sr.h)) surf.fill(fill_color) return surf
Returns an empty surface filled with fill_color. :param fill_color: color to fill the surface with :type fill_color: pygame.Color :param size: the size of the new surface, if None its created to be the same size as the screen :type size: int-2-tuple
train
https://github.com/KnorrFG/pyparadigm/blob/69944cdf3ce2f6414ae1aa1d27a0d8c6e5fb3fd3/pyparadigm/misc.py#L114-L127
null
"""Contains code that did not make it into an own module. """ import contextlib with contextlib.redirect_stdout(None): import pygame from . import surface_composition as sc import os import time from functools import lru_cache from threading import Thread class _PumpThread(Thread): """See the documentation for the interactive_mode arg from :ref:`init`""" def run(self): while self._run: pygame.event.pump() time.sleep(0.1) def stop(self): self._run = False self.join() def __init__(self): super().__init__() self._run = True self.start() def init(resolution, pygame_flags=0, display_pos=(0, 0), interactive_mode=False): """Creates a window of given resolution. :param resolution: the resolution of the windows as (width, height) in pixels :type resolution: tuple :param pygame_flags: modify the creation of the window. For further information see :ref:`creating_a_window` :type pygame_flags: int :param display_pos: determines the position on the desktop where the window is created. In a multi monitor system this can be used to position the window on a different monitor. E.g. the monitor to the right of the main-monitor would be at position (1920, 0) if the main monitor has the width 1920. :type display_pos: tuple :param interactive_mode: Will install a thread, that emptys the event-queue every 100ms. This is neccessary to be able to use the display() function in an interactive console on windows systems. If interactive_mode is set, init() will return a reference to the background thread. This thread has a stop() method which can be used to cancel it. If you use ctrl+d or exit() within ipython, while the thread is still running, ipython will become unusable, but not close. :type interactive_mode: bool :return: a reference to the display screen, or a reference to the background thread if interactive_mode was set to true. In the second scenario you can obtain a reference to the display surface via pygame.display.get_surface() :rtype: pygame.Surface """ os.environ['SDL_VIDEO_WINDOW_POS'] = "{}, {}".format(*display_pos) pygame.init() pygame.font.init() disp = pygame.display.set_mode(resolution, pygame_flags) return _PumpThread() if interactive_mode else disp def display(surface): """Displays a pygame.Surface in the window. in pygame the window is represented through a surface, on which you can draw as on any other pygame.Surface. A refernce to to the screen can be optained via the :py:func:`pygame.display.get_surface` function. To display the contents of the screen surface in the window :py:func:`pygame.display.flip` needs to be called. :py:func:`display` draws the surface onto the screen surface at the postion (0, 0), and then calls :py:func:`flip`. :param surface: the pygame.Surface to display :type surface: pygame.Surface """ screen = pygame.display.get_surface() screen.blit(surface, (0, 0)) pygame.display.flip() def slide_show(slides, continue_handler): """Displays one "slide" after another. After displaying a slide, continue_handler is called without arguments. When continue_handler returns, the next slide is displayed. Usage example :: slide_show(text_screens, partial(event_listener.wait_for_n_keypresses, pygame.K_RETURN)) (partial is imported from the functools module.) :param slides: pygame.Surfaces to be displayed. :type slides: iterable :param continue_handler: function, that returns when the next slide should be displayed. :type continue_handler: callable with arity 0. """ for slide in slides: display(slide) continue_handler() _char_mappings = { "\r": "\n", "\t": " " } def process_char(buffer: str, char: str, mappings=_char_mappings): """This is a convinience method for use with EventListener.wait_for_unicode_char(). In most cases it simply appends char to buffer. Some replacements are done because presing return will produce '\\r' but for most cases '\\n' would be desireable. Also backspace cant just be added to a string either, therefore, if char is "\\u0008" the last character from buffer will be cut off. The replacement from '\\r' to '\\n' is done using the mappings argument, the default value for it also contains a mapping from '\t' to 4 spaces. :param buffer: the string to be updated :type buffer: str :param char: the unicode character to be processed :type char: str :param mappings: a dict containing mappings :type mappings: dict :returns: a new string""" if char in mappings: return buffer + mappings[char] elif char == "\u0008": return buffer[:-1] if len(buffer) > 0 else buffer else: return buffer + char
KnorrFG/pyparadigm
pyparadigm/misc.py
process_char
python
def process_char(buffer: str, char: str, mappings=_char_mappings): if char in mappings: return buffer + mappings[char] elif char == "\u0008": return buffer[:-1] if len(buffer) > 0 else buffer else: return buffer + char
This is a convinience method for use with EventListener.wait_for_unicode_char(). In most cases it simply appends char to buffer. Some replacements are done because presing return will produce '\\r' but for most cases '\\n' would be desireable. Also backspace cant just be added to a string either, therefore, if char is "\\u0008" the last character from buffer will be cut off. The replacement from '\\r' to '\\n' is done using the mappings argument, the default value for it also contains a mapping from '\t' to 4 spaces. :param buffer: the string to be updated :type buffer: str :param char: the unicode character to be processed :type char: str :param mappings: a dict containing mappings :type mappings: dict :returns: a new string
train
https://github.com/KnorrFG/pyparadigm/blob/69944cdf3ce2f6414ae1aa1d27a0d8c6e5fb3fd3/pyparadigm/misc.py#L135-L160
null
"""Contains code that did not make it into an own module. """ import contextlib with contextlib.redirect_stdout(None): import pygame from . import surface_composition as sc import os import time from functools import lru_cache from threading import Thread class _PumpThread(Thread): """See the documentation for the interactive_mode arg from :ref:`init`""" def run(self): while self._run: pygame.event.pump() time.sleep(0.1) def stop(self): self._run = False self.join() def __init__(self): super().__init__() self._run = True self.start() def init(resolution, pygame_flags=0, display_pos=(0, 0), interactive_mode=False): """Creates a window of given resolution. :param resolution: the resolution of the windows as (width, height) in pixels :type resolution: tuple :param pygame_flags: modify the creation of the window. For further information see :ref:`creating_a_window` :type pygame_flags: int :param display_pos: determines the position on the desktop where the window is created. In a multi monitor system this can be used to position the window on a different monitor. E.g. the monitor to the right of the main-monitor would be at position (1920, 0) if the main monitor has the width 1920. :type display_pos: tuple :param interactive_mode: Will install a thread, that emptys the event-queue every 100ms. This is neccessary to be able to use the display() function in an interactive console on windows systems. If interactive_mode is set, init() will return a reference to the background thread. This thread has a stop() method which can be used to cancel it. If you use ctrl+d or exit() within ipython, while the thread is still running, ipython will become unusable, but not close. :type interactive_mode: bool :return: a reference to the display screen, or a reference to the background thread if interactive_mode was set to true. In the second scenario you can obtain a reference to the display surface via pygame.display.get_surface() :rtype: pygame.Surface """ os.environ['SDL_VIDEO_WINDOW_POS'] = "{}, {}".format(*display_pos) pygame.init() pygame.font.init() disp = pygame.display.set_mode(resolution, pygame_flags) return _PumpThread() if interactive_mode else disp def display(surface): """Displays a pygame.Surface in the window. in pygame the window is represented through a surface, on which you can draw as on any other pygame.Surface. A refernce to to the screen can be optained via the :py:func:`pygame.display.get_surface` function. To display the contents of the screen surface in the window :py:func:`pygame.display.flip` needs to be called. :py:func:`display` draws the surface onto the screen surface at the postion (0, 0), and then calls :py:func:`flip`. :param surface: the pygame.Surface to display :type surface: pygame.Surface """ screen = pygame.display.get_surface() screen.blit(surface, (0, 0)) pygame.display.flip() def slide_show(slides, continue_handler): """Displays one "slide" after another. After displaying a slide, continue_handler is called without arguments. When continue_handler returns, the next slide is displayed. Usage example :: slide_show(text_screens, partial(event_listener.wait_for_n_keypresses, pygame.K_RETURN)) (partial is imported from the functools module.) :param slides: pygame.Surfaces to be displayed. :type slides: iterable :param continue_handler: function, that returns when the next slide should be displayed. :type continue_handler: callable with arity 0. """ for slide in slides: display(slide) continue_handler() def empty_surface(fill_color, size=None): """Returns an empty surface filled with fill_color. :param fill_color: color to fill the surface with :type fill_color: pygame.Color :param size: the size of the new surface, if None its created to be the same size as the screen :type size: int-2-tuple """ sr = pygame.display.get_surface().get_rect() surf = pygame.Surface(size or (sr.w, sr.h)) surf.fill(fill_color) return surf _char_mappings = { "\r": "\n", "\t": " " }
KnorrFG/pyparadigm
doc/examples/stroop.py
rand_elem
python
def rand_elem(seq, n=None): return map(random.choice, repeat(seq, n) if n is not None else repeat(seq))
returns a random element from seq n times. If n is None, it continues indefinitly
train
https://github.com/KnorrFG/pyparadigm/blob/69944cdf3ce2f6414ae1aa1d27a0d8c6e5fb3fd3/doc/examples/stroop.py#L201-L203
null
""" This script contains an example implementation of the stroop task. The easiest way to understand this code is to start reading in the main function, and then read every function when it's called first """ import random import time import csv from collections import namedtuple from enum import Enum from functools import lru_cache from itertools import islice, repeat import pygame from pyparadigm import (EventListener, Fill, Font, LinLayout, LLItem, Padding, RectangleShaper, Surface, Text, compose, display, empty_surface, init, slide_show) # ================================================================================ # Just Configuration # ================================================================================ n_train_1_trials = 30 n_train_2_trials = 10 trials_per_block = 10 intro_text = [""" Welcome to the Stroop-demo. In this task you will be presented with words naming colors which are written in a colored font. You will either have to indicate the name of the color, or the color of the font, using the arrow keys. Press Return to continue. """, """ To indicate the color you will have to use the number keys, 1 for red 2 for green 3 for blue press Return to continue """, """ First you will learn the mappings by heart. To do so you will be displayed with the mappings, after %d trials the mappings won't be shown any more. Then after %d correct trials, the main task will start. """ % (n_train_1_trials, n_train_2_trials)] pre_hidden_training_text = """ Now we will hide the mapping, and the task will continue until you answered correctly %d times. Press Return to continue""" % n_train_2_trials post_hidden_training_text = """ The training was succesful. Press Return to continue""" pre_text_block_text = """ Now, we begin with the test. Please indicate the color that is named by the letters Press Return to continue """ post_test_block_text = """ Now, please indicate the color in which the word is written Press Return to continue """ end_text = """ The task is complete, thank you for your participation Press Return to escape """ # ================================================================================ # some utility functions # ================================================================================ @lru_cache() def text(s: str, color=0): # This is our configuration of how to display text, with the arial font, and # a pointsize of 30. # Due to the way text is plotted it needs the information of an alphachannel # therefore it is not possible to simply pass the hex-code of the color, but it # is necessary to create a pygame.Color object. For which, again, it is necessary # to multiply the hex code with 0x100 to respect the alphachannel return Text(s, Font("Arial", size=30), color=pygame.Color(color * 0x100)) def _bg(): # short for background return empty_surface(0xFFFFFF) def display_text(s:str): display(compose(_bg())(text(s))) def display_text_and_wait(s: str, el: EventListener, key: int = pygame.K_RETURN): display_text(s) el.wait_for_keys(key) # ================================================================================ # Main Program # ================================================================================ class Color(Enum): red = 0xFF0000 green = 0x00FF00 blue = 0x0000FF colors = list(Color) key_color_mapping = { eval("pygame.K_%d" % (i + 1)): color for i, color in enumerate(Color) } def display_intro(el: EventListener): # the first argument for slide_show must be an iterable of pygame.Surface # to create it we render the text onto an empty surface with the map() # function. slide_show displays one slide, and then calls the function that # is passed to it as second argument. When this function returns, the next # slide is displayed and the function is called again. The function that is # passed simply waits for the return key slides = map(lambda s: compose(_bg())(text(s)), intro_text) slide_show(slides, lambda: el.wait_for_keys(pygame.K_RETURN)) @lru_cache() def make_train_stim(type: str, color: Color): # encapsulates the creation of a training stim. Either a square of the given # or the name of the color as text, they are wrapped by a RectangleShaper, # by default, will create a square assert type in ["color", "text"] return RectangleShaper()( text(color.name) if type == "text" else Fill(color.value)) def make_color_mapping(): # The mapping is a horizontal layout consisting of groups of # a text element describing the key, and a square containing the color # we use make_train_stim() to create the square, and add a LLItem(1) in # the back and the front to get visible gaps between the groups. # The * in from of the list is used to expand the list to the arguments # for the LinLayouts inner function. return LinLayout("h")(*[LinLayout("h")(LLItem(1), text(str(key + 1)), make_train_stim("color", color), LLItem(1)) for key, color in enumerate(Color)]) @lru_cache() def render_train_screen(show_mapping, stim_type, target_color): # the contents are aranged in a vertical layout, topmost is the # title "target color", followed by the stim for training (either a # square containing the color, or the word naming the color) # in the Bottom there is the information which key is mapped to which # color. But its only displayed optionally return compose(_bg(), LinLayout("v"))( # Create the Text text("target color:"), # Create the stimulus, and scale it down a little. Padding.from_scale(0.3)(make_train_stim(stim_type, target_color)), # Up till here the content is static, but displaying the mapping is optionally # and depends on the parameter, therefore we either add the mapping, or # an LLItem(1) as placeholder make_color_mapping() if show_mapping else LLItem(1) ) def do_train_trial(event_listener: EventListener, show_mapping: bool, stim_type: str, target_color: Color): # displays a training_screen display(render_train_screen(show_mapping, stim_type, target_color)) # waits for a response response_key = event_listener.wait_for_keys(key_color_mapping) # returns whether the response was correct return key_color_mapping[response_key] == target_color def until_n_correct(n, func): n_correct = 0 while n_correct < n: if func(): n_correct += 1 else: n_correct = 0 def do_training(el: EventListener): arguments = zip(rand_elem(["text", "color"]), rand_elem(colors)) for stim_type, color in islice(arguments, n_train_1_trials): do_train_trial(el, True, stim_type, color) display_text_and_wait(pre_hidden_training_text, el) until_n_correct(n_train_2_trials, lambda: do_train_trial(el, False, *next(arguments))) display_text_and_wait(post_hidden_training_text, el) @lru_cache() def render_trial_screen(word, font_color, target): return compose(_bg(), LinLayout("v"))( # Create the Text text("Which color is named by the letters?" if target == "text" else "What's the color of the word?"), # Create the stimulus, and scale it down a little. Padding.from_scale(0.3)(text(word, font_color)), LLItem(1) ) BlockResult = namedtuple("BlockResult", "RT word font_color response was_correct") def run_block(event_listener: EventListener, by: str, n_trials: int)-> BlockResult: assert by in ["text", "color"] RTs = []; words = []; fonts = []; responses = []; was_correct = [] for word, font in zip(rand_elem(colors, n_trials), rand_elem(colors)): words.append(word) fonts.append(font) display(render_trial_screen(word.name, font.value, by)) # We use this to record reaction times start = time.time() response_key = event_listener.wait_for_keys(key_color_mapping) # Now the reaction time is just now - then RTs.append(time.time() - start) response = key_color_mapping[response_key] responses.append(response) was_correct.append(response == (word if by == "text" else font)) return BlockResult(RTs, words, fonts, responses, was_correct) def save_results(text_res: BlockResult, font_res: BlockResult): with open("results.tsv", "w") as f: writer = csv.writer(f, delimiter="\t") writer.writerow(("by",) + BlockResult._fields) for line in zip(*text_res): writer.writerow(("text",) + line) for line in zip(*font_res): writer.writerow(("font",) + line) def main(): # create the pygame window. It has a resolution of 1024 x 800 pixels init((1024, 800)) # create an event listener that will be used through the whole program event_listener = EventListener() display_intro(event_listener) do_training(event_listener) display_text_and_wait(pre_text_block_text, event_listener) text_block_results = run_block(event_listener, by="text", n_trials=trials_per_block) display_text_and_wait(post_test_block_text, event_listener) color_block_results = run_block(event_listener, by="color", n_trials=trials_per_block) display_text_and_wait(end_text, event_listener) save_results(text_block_results, color_block_results) if __name__ == "__main__": main()