コード例 #1
0
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
コード例 #2
0
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())
コード例 #3
0
ファイル: task_steps.py プロジェクト: coddingtonbear/inthe.am
def task_count_matches(context, count, status):
    count = int(count)

    store = get_store()
    tasks = store.client.filter_tasks({'status': status})

    assert len(tasks) == count
コード例 #4
0
ファイル: task_steps.py プロジェクト: williamtoll/inthe.am
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
    ''')
コード例 #5
0
ファイル: task_steps.py プロジェクト: eyecreate/inthe.am
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)
コード例 #6
0
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
    """)
コード例 #7
0
ファイル: views.py プロジェクト: pu239ppy/authentic2
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)
コード例 #8
0
ファイル: task_steps.py プロジェクト: coddingtonbear/inthe.am
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
コード例 #9
0
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)
コード例 #10
0
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
コード例 #11
0
ファイル: task_steps.py プロジェクト: coddingtonbear/inthe.am
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
    ''')
コード例 #12
0
ファイル: task_steps.py プロジェクト: eyecreate/inthe.am
def task_count_matches(context, count, status):
    count = int(count)

    store = get_store()
    tasks = store.client.filter_tasks({'status': status})

    assert len(tasks) == count
コード例 #13
0
ファイル: task_steps.py プロジェクト: coddingtonbear/inthe.am
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)
コード例 #14
0
ファイル: task_steps.py プロジェクト: scheijan/inthe.am
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
    )
コード例 #15
0
ファイル: task_steps.py プロジェクト: coddingtonbear/inthe.am
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
    )
コード例 #16
0
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()
        }
    }
コード例 #17
0
ファイル: task_steps.py プロジェクト: eyecreate/inthe.am
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
コード例 #18
0
ファイル: task_steps.py プロジェクト: eyecreate/inthe.am
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
コード例 #19
0
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)
コード例 #20
0
ファイル: task_steps.py プロジェクト: eyecreate/inthe.am
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,
        ))
コード例 #21
0
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,
            )
コード例 #22
0
ファイル: task_steps.py プロジェクト: coddingtonbear/inthe.am
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']
コード例 #23
0
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"]
コード例 #24
0
ファイル: task_steps.py プロジェクト: coddingtonbear/inthe.am
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()
コード例 #25
0
ファイル: task_steps.py プロジェクト: eyecreate/inthe.am
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']
コード例 #26
0
ファイル: deployment.py プロジェクト: dockerian/pyapi
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}
コード例 #27
0
ファイル: task_steps.py プロジェクト: coddingtonbear/inthe.am
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,
        )
    )
コード例 #28
0
ファイル: task_steps.py プロジェクト: eyecreate/inthe.am
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
    ''')
コード例 #29
0
ファイル: task_steps.py プロジェクト: eyecreate/inthe.am
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,
            ))
コード例 #30
0
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
コード例 #31
0
ファイル: task_steps.py プロジェクト: mrphishxxx/inthe.am
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,
            )
        )
コード例 #32
0
ファイル: task_steps.py プロジェクト: eyecreate/inthe.am
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
    ''')
コード例 #33
0
ファイル: task_steps.py プロジェクト: eyecreate/inthe.am
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
コード例 #34
0
ファイル: task_steps.py プロジェクト: coddingtonbear/inthe.am
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
コード例 #35
0
ファイル: deployment.py プロジェクト: dockerian/pyapi
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}
コード例 #36
0
ファイル: task_steps.py プロジェクト: scheijan/inthe.am
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
コード例 #37
0
ファイル: task_steps.py プロジェクト: eyecreate/inthe.am
def store_configuration(context):
    store = get_store()
    for key, value in context.table.rows:
        setattr(store, key, get_json_value(value))
    store.save()
コード例 #38
0
ファイル: task_steps.py プロジェクト: eyecreate/inthe.am
def task_search_for_duplicates_of(context, name):
    store = get_store()
    task = context.named_tasks[name]

    context.duplicate_found = find_duplicate_tasks(store, task)
コード例 #39
0
ファイル: task_steps.py プロジェクト: eyecreate/inthe.am
def when_merge_singular_task(context, name):
    store = get_store()
    task_record = context.named_tasks[name]

    merge_duplicate_tasks(store, task_record)
コード例 #40
0
ファイル: task_steps.py プロジェクト: eyecreate/inthe.am
def when_merge_duplicate_tasks(context):
    store = get_store()

    merge_all_duplicate_tasks(store)
コード例 #41
0
ファイル: task_steps.py プロジェクト: eyecreate/inthe.am
def when_search_for_duplicate_tasks(context):
    store = get_store()

    context.duplicates_found = find_all_duplicate_tasks(store)
コード例 #42
0
ファイル: task_steps.py プロジェクト: coddingtonbear/inthe.am
def when_merge_duplicate_tasks(context):
    store = get_store()

    merge_all_duplicate_tasks(store)
コード例 #43
0
ファイル: task_steps.py プロジェクト: coddingtonbear/inthe.am
def when_search_for_duplicate_tasks(context):
    store = get_store()

    context.duplicates_found = find_all_duplicate_tasks(store)
コード例 #44
0
ファイル: yeelight.py プロジェクト: tobievii/goodbye-mihome
#
# 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"
コード例 #45
0
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)
コード例 #46
0
ファイル: task_steps.py プロジェクト: coddingtonbear/inthe.am
def when_merge_singular_task(context, name):
    store = get_store()
    task_record = context.named_tasks[name]

    merge_duplicate_tasks(store, task_record)
コード例 #47
0
ファイル: task_steps.py プロジェクト: coddingtonbear/inthe.am
def task_search_for_duplicates_of(context, name):
    store = get_store()
    task = context.named_tasks[name]

    context.duplicate_found = find_duplicate_tasks(store, task)