def task_with_following_details(context, name): task = { row[0]: get_json_value(row[1], time_zone=context.time_zone) for row in context.table.rows } task["uuid"] = str(uuid.uuid4()) if "annotations" in task: final_annotations = [] for annotation in task["annotations"]: if isinstance(annotation, basestring): final_annotations.append({ "description": annotation, "entry": datetime.datetime.utcnow() }) else: final_annotations.append(annotation) task["annotations"] = final_annotations store = get_store() task = store.client.import_task(task) if not hasattr(context, "named_tasks"): context.named_tasks = {} context.named_tasks[name] = task
def receiver(service='mihome'): from plugins import gateway assert service in MULTICAST, 'No such service' store = get_store() address, port = MULTICAST.get(service) sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) sock.bind(("0.0.0.0", port)) mreq = struct.pack("=4sl", socket.inet_aton(address), socket.INADDR_ANY) sock.setsockopt(socket.IPPROTO_IP, socket.IP_MULTICAST_TTL, 32) sock.setsockopt(socket.IPPROTO_IP, socket.IP_MULTICAST_LOOP, 1) sock.setsockopt(socket.SOL_SOCKET, socket.SO_RCVBUF, SOCKET_BUFSIZE) sock.setsockopt(socket.IPPROTO_IP, socket.IP_ADD_MEMBERSHIP, mreq) current = {} while True: data, _ = sock.recvfrom(SOCKET_BUFSIZE) # buffer size is 1024 bytes print(datetime.now().isoformat(), data) if service == 'mihome': message = json.loads(data.decode()) data = json.loads(message['data']) if message.get('model') == 'sensor_ht' and not sensor_ht.process( conn, cursor, current, message, data): continue elif message.get('model') == 'magnet': magnet.process(store, message, data) elif message.get('model') == 'gateway': gateway.process(store, message, data) current = {} elif service == 'yeelight': yeelight.process(data.decode())
def task_count_matches(context, count, status): count = int(count) store = get_store() tasks = store.client.filter_tasks({'status': status}) assert len(tasks) == count
def existing_task_with_details(context): task = {'description': 'Untitled'} for key, value in context.table.rows: task[key] = get_json_value(value, time_zone=context.time_zone) task['uuid'] = str(uuid.uuid4()) if 'annotations' in task: final_annotations = [] for annotation in task['annotations']: if isinstance(annotation, basestring): final_annotations.append({ 'description': annotation, 'entry': datetime.datetime.utcnow() }) else: final_annotations.append(annotation) task['annotations'] = final_annotations store = get_store() task = store.client.import_task(task) context.created_task_id = task['uuid'] context.execute_steps(u''' then the user clicks the refresh button ''')
def task_null_field(context, status, field): store = get_store() tasks = store.client.filter_tasks({'status': status}) assert len(tasks) == 1, "Asserted single task to be found, found %s" % ( len(tasks)) task = tasks[0] assert not task.get(field)
def existing_task_with_details(context): task = {"description": "Untitled"} for key, value in context.table.rows: task[key] = get_json_value(value, time_zone=context.time_zone) task["uuid"] = str(uuid.uuid4()) if "annotations" in task: final_annotations = [] for annotation in task["annotations"]: if isinstance(annotation, basestring): final_annotations.append({ "description": annotation, "entry": datetime.datetime.utcnow() }) else: final_annotations.append(annotation) task["annotations"] = final_annotations store = get_store() task = store.client.import_task(task) context.created_task_id = task["uuid"] context.execute_steps(""" then the user clicks the refresh button """)
def openid_server(request): """ This view is the actual OpenID server - running at the URL pointed to by the <link rel="openid.server"> tag. """ server = Server(get_store(request), op_endpoint=request.build_absolute_uri( reverse('openid-provider-root'))) # Cancellation if 'cancel' in request.REQUEST: if 'OPENID_REQUEST' in request.session: return oresponse_to_response(server, request.session['OPENID_REQUEST'].answer(False)) else: return HttpResponseRedirect('/') # Clear AuthorizationInfo session var, if it is set if request.session.get('AuthorizationInfo', None): del request.session['AuthorizationInfo'] querydict = dict(request.REQUEST.items()) try: orequest = server.decodeRequest(querydict) except ProtocolError, why: logger.error('Invalid OpenID message %s' % querydict) return oresponse_to_response(server, why)
def task_with_following_details(context, name): task = { row[0]: get_json_value( row[1], time_zone=context.time_zone ) for row in context.table.rows } task['uuid'] = str(uuid.uuid4()) if 'annotations' in task: final_annotations = [] for annotation in task['annotations']: if isinstance(annotation, basestring): final_annotations.append({ 'description': annotation, 'entry': datetime.datetime.utcnow() }) else: final_annotations.append(annotation) task['annotations'] = final_annotations store = get_store() task = store.client.import_task(task) if not hasattr(context, 'named_tasks'): context.named_tasks = {} context.named_tasks[name] = task
def send_command(command, timeout=10): _, port = MULTICAST.get('mihome') if isinstance(command.get('data'), dict): command['data'] = json.dumps(command['data']) address = get_store().get('gateway_addr') if address is None: print( "Doesn't receive any heartbeat from gateway. Delaying request for 10 seconds." ) time.sleep(10) sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) sock.settimeout(timeout) sock.connect((address, port)) sock.send(json.dumps(command).encode('ascii')) data = None try: data, addr = sock.recvfrom(SOCKET_BUFSIZE) except ConnectionRefusedError: print("send_command :: recvfrom() connection refused: {}:{}".format( address.decode(), port)) except socket.timeout: print("send_command :: recvfrom() timed out: {}:{}".format( address.decode(), port)) finally: sock.close() return data
def existing_task_with_details(context): task = { 'description': 'Untitled' } for key, value in context.table.rows: task[key] = get_json_value(value, time_zone=context.time_zone) task['uuid'] = str(uuid.uuid4()) if 'annotations' in task: final_annotations = [] for annotation in task['annotations']: if isinstance(annotation, basestring): final_annotations.append({ 'description': annotation, 'entry': datetime.datetime.utcnow() }) else: final_annotations.append(annotation) task['annotations'] = final_annotations store = get_store() task = store.client.import_task(task) context.created_task_id = task['uuid'] context.execute_steps(u''' then the user clicks the refresh button ''')
def task_non_null_field(context, status, field): store = get_store() tasks = store.client.filter_tasks({'status': status}) assert len(tasks) == 1, "Asserted single task to be found, found %s" % ( len(tasks) ) task = tasks[0] assert task.get(field)
def task_with_field_exists(context, field, value): store = get_store() matches = store.client.filter_tasks({ field: value }) assert len(matches) > 0, "No task found with %s == %s" % ( field, value )
def get_base_command(): store = get_store() return { 'cmd': 'write', 'model': 'gateway', 'sid': store.get('gateway_sid').decode(), 'short_id': 0, 'data': { 'key': get_key().decode() } }
def task_with_following_details(context, name): task = {row[0]: get_json_value(row[1]) for row in context.table.rows} task['uuid'] = str(uuid.uuid4()) store = get_store() task = store.client.import_task(task) if not hasattr(context, 'named_tasks'): context.named_tasks = {} context.named_tasks[name] = task
def task_with_details(context, status): store = get_store() tasks = store.client.filter_tasks({"status": status}) assert len(tasks) == 1, "Asserted single task to be found, found %s" % ( len(tasks)) task = tasks[0] for key, value in context.table.rows: assert task.get(key) == get_json_value( value, time_zone=context.time_zone ), "Task field {}'s value is {}, not {}".format( key, task.get(key), value)
def task_whatever_is_marked_as_whatnot(context, name, fieldname, value): store = get_store() old_task_data = context.named_tasks[name] task = store.client.filter_tasks({'uuid': old_task_data['uuid']})[0] assert task[fieldname] == value, ( "Task %s '%s' does not match expectation '%s'" % ( fieldname, task[fieldname], value, ))
def task_whatever_is_marked_as_whatnot(context, name, fieldname, value): store = get_store() old_task_data = context.named_tasks[name] task = store.client.filter_tasks({"uuid": old_task_data["uuid"]})[0] assert (task[fieldname] == value ), "Task {} '{}' does not match expectation '{}'".format( fieldname, task[fieldname], value, )
def task_existing_with_value(context, field, value): store = get_store() basic_task = { 'description': 'Gather at Terminus for Hari Seldon\'s Address', 'project': 'terminus_empire', 'tags': ['next_steps', 'mule'], } if field == 'tags': value = value.split(',') basic_task[field] = value task = store.client.task_add(**basic_task) context.created_task_id = task['uuid']
def task_existing_with_value(context, field, value): store = get_store() basic_task = { "description": "Gather at Terminus for Hari Seldon's Address", "project": "terminus_empire", "tags": ["next_steps", "mule"], } if field == "tags": value = value.split(",") basic_task[field] = value task = store.client.task_add(**basic_task) context.created_task_id = task["uuid"]
def store_configuration(context): store = get_store() for key, value in context.table.rows: setattr( store, key, get_json_value( value, time_zone=context.time_zone ) ) store.save()
def deploy_package(package_name, endpoint_url, username, password): """ Deploy a package into destination (e.g. ALS/Cloud Foundry) Params: package_name - the name of the package to deploy endpoint_url - the destination (e.g. ALS/Cloud Foundry) endpoint URL ie: 'https://api.15.126.129.33.xip.io' username - the user name (admin email) for destination login password - the password for destination login """ store = get_store() if (not store.check_package_exists(package_name)): return {'status': 404} cwd = '' try: cwd = tempfile.mkdtemp() pkg_filename = '{0}.tar.gz'.format(package_name) package_path = '{0}/{1}'.format(cwd, pkg_filename) package = Package(package_name, package_path, endpoint_url) # instantiate a cli composer composer = HelionCliComposer(endpoint_url, username, password) deploy_status = DeploymentStatus(package, store) deployment = Deployment(package, composer, deploy_status, True) deployment_id = deployment.deployment_id deployment.set_status('INIT') # Start a new process to execute the deployment process = Process(name='deployment_{0}'.format(deployment_id), target=deployment.deploy) process.start() LOGGER.info('Deployment {0} started for {1}.'.format( deployment_id, package_name)) return { 'status': 201, 'deployment_id': deployment_id, 'package': package_name } except Exception as e: stack_info = traceback.format_exc() error_message = "Exception on deploy {0}. Details:\n{1}".format( package_name, stack_info) LOGGER.exception(error_message) delete_directory_tree(cwd) return {'status': 500, 'errors': error_message}
def task_whatever_is_marked_as_whatnot(context, name, fieldname, value): store = get_store() old_task_data = context.named_tasks[name] task = store.client.filter_tasks({'uuid': old_task_data['uuid']})[0] assert task[fieldname] == value, ( "Task %s '%s' does not match expectation '%s'" % ( fieldname, task[fieldname], value, ) )
def existing_task_with_details(context): task = {'description': 'Untitled'} for key, value in context.table.rows: task[key] = get_json_value(value) task['uuid'] = str(uuid.uuid4()) store = get_store() task = store.client.import_task(task) context.created_task_id = task['uuid'] context.execute_steps(u''' then the user clicks the refresh button ''')
def task_with_details(context, status): store = get_store() tasks = store.client.filter_tasks({'status': status}) assert len(tasks) == 1, "Asserted single task to be found, found %s" % ( len(tasks)) task = tasks[0] for key, value in context.table.rows: assert task.get(key) == get_json_value(value), ( "Task field %s's value is %s, not %s" % ( key, task.get(key), value, ))
def task_annotated_as_duplicate(context, left, right): store = get_store() beta = store.client.filter_tasks( {"uuid": context.named_tasks[left]["uuid"]})[0] alpha = store.client.filter_tasks( {"uuid": context.named_tasks[right]["uuid"]})[0] assert alpha["intheammergedfrom"] == str( beta["uuid"]), "No backreference set." assert beta["intheamduplicateof"] == str( alpha["uuid"]), "Not marked as duplicate." context.named_tasks[left] = beta context.named_tasks[right] = alpha
def task_with_details(context, status): store = get_store() tasks = store.client.filter_tasks({'status': status}) assert len(tasks) == 1, "Asserted single task to be found, found %s" % ( len(tasks) ) task = tasks[0] for key, value in context.table.rows: assert task.get(key) == get_json_value(value), ( "Task field %s's value is %s, not %s" % ( key, task.get(key), value, ) )
def existing_task_with_details(context): task = { 'description': 'Untitled' } for key, value in context.table.rows: task[key] = get_json_value(value) task['uuid'] = str(uuid.uuid4()) store = get_store() task = store.client.import_task(task) context.created_task_id = task['uuid'] context.execute_steps(u''' then the user clicks the refresh button ''')
def task_annotated_as_duplicate(context, left, right): store = get_store() beta = store.client.filter_tasks( {'uuid': context.named_tasks[left]['uuid']})[0] alpha = store.client.filter_tasks( {'uuid': context.named_tasks[right]['uuid']})[0] assert alpha['intheammergedfrom'] == str( beta['uuid']), ("No backreference set.") assert beta['intheamduplicateof'] == str( alpha['uuid']), ("Not marked as duplicate.") context.named_tasks[left] = beta context.named_tasks[right] = alpha
def task_annotated_as_duplicate(context, left, right): store = get_store() beta = store.client.filter_tasks( {'uuid': context.named_tasks[left]['uuid']} )[0] alpha = store.client.filter_tasks( {'uuid': context.named_tasks[right]['uuid']} )[0] assert alpha['intheammergedfrom'] == str(beta['uuid']), ( "No backreference set." ) assert beta['intheamduplicateof'] == str(alpha['uuid']), ( "Not marked as duplicate." ) context.named_tasks[left] = beta context.named_tasks[right] = alpha
def get_status(id): """ Get the deployment status by id """ try: LOGGER.info("======= deployment::get_status =======") store = get_store() deploy_status = DeploymentStatus(store=store) result = deploy_status.get_status(id) LOGGER.debug('Deployment result: {0}'.format(result)) if result == {} or not result['deploy_status']: return {'status': 404} else: return {'status': 200, 'data': result} except Exception as e: stack_info = traceback.format_exc() error = "Exception on getting deployment status" error_message = "{0} for {1}. Details:\n{2}".format( error, id, stack_info) LOGGER.exception(error_message) return {'status': 500, 'errors': error_message}
def task_with_following_details(context, name): task = {row[0]: get_json_value(row[1]) for row in context.table.rows} task['uuid'] = str(uuid.uuid4()) if 'annotations' in task: final_annotations = [] for annotation in task['annotations']: if isinstance(annotation, basestring): final_annotations.append({ 'description': annotation, 'entry': datetime.datetime.utcnow() }) else: final_annotations.append(annotation) task['annotations'] = final_annotations store = get_store() task = store.client.import_task(task) if not hasattr(context, 'named_tasks'): context.named_tasks = {} context.named_tasks[name] = task
def store_configuration(context): store = get_store() for key, value in context.table.rows: setattr(store, key, get_json_value(value)) store.save()
def task_search_for_duplicates_of(context, name): store = get_store() task = context.named_tasks[name] context.duplicate_found = find_duplicate_tasks(store, task)
def when_merge_singular_task(context, name): store = get_store() task_record = context.named_tasks[name] merge_duplicate_tasks(store, task_record)
def when_merge_duplicate_tasks(context): store = get_store() merge_all_duplicate_tasks(store)
def when_search_for_duplicate_tasks(context): store = get_store() context.duplicates_found = find_all_duplicate_tasks(store)
# # Unsupported (feel free to implement something of this): set_ct_abx, set_rgb, # set_hsv, set_music. import json import re import socket import time from web.w import UpdatesHandler from utils import get_store STORE_KEY = 'yeelight' DEVICE = 'yeelight' YEE_DISCOVER = ['M-SEARCH * HTTP/1.1', 'MAN: "ssdp:discover"', 'ST: wifi_bulb'] store = get_store() def toggle(device_id=None): """ Toggle the smart LED. """ return send_command({'method': 'toggle', 'params': []}, device_id) def set_power(power, effect='smooth', duration=500, device_id=None): """ Switch on or off the smart LED. `power` - Boolean `effect` - "smooth" or "sudden" `duration` - duration of smooth effect, ignored if effect is "sudden"
def get_key(): """Get current gateway key""" cipher = AES.new(config.MIHOME_GATEWAY_PASSWORD, AES.MODE_CBC, IV) encrypted = cipher.encrypt(get_store().get('gateway_token')) return binascii.hexlify(encrypted)