Пример #1
0
def get_all_device_state() -> list:
    devices = get_gpio_config()
    all_device_state = []
    for device in devices:
        if device['device']:
            all_device_state.append({
                'device_id':
                device['device_id'],
                'state':
                gpio_read(device['BCM']),
                'name':
                device['device']['name'],
                'description':
                device['device']['description'],
                'type':
                device['device']['type'],
                'run_type':
                device['device']['run_type'],
                'options':
                device['device']['options'],
                'created_at':
                device['device']['created_at'],
                'updated_at':
                device['device']['updated_at'],
            })
    return all_device_state
Пример #2
0
def device_delete(message: str) -> None:
    
    delete_device = json.loads(message)
    gpio_config = get_gpio_config()
    delete_device_id = delete_device['device_id']

    for device in gpio_config:
        if device['device_id'] == delete_device_id:

            if device['device'] == {}:
                raise DeviceNotFound('Device does not found.')
            
            deleted_device = device['device']
            
            # delete device_data
            device['device'] = {}
            break
    
    set_gpio_config(gpio_config)
    set_new_timer()
    publish_device_state()

    slack_post_text = SLACK_DELETE_DEVICE_NOTIFICATION_FORMAT.format(
        now = formated_str_now_date(),
        device_id = delete_device_id,
        name = deleted_device['name'],
        description = deleted_device['description'],
        type_ = deleted_device['type'],
        run_type = deleted_device['run_type'],
    )
    post_slack_by_type(
        text = slack_post_text,
        type_ = SLACK_NOTIFICATION_TYPE['NOTIFICATION']
    )
Пример #3
0
def device_exchange(message: dict) -> None:
    exchange_devices = json.loads(message)['devices']
    gpio_config = get_gpio_config()

    result = exchanged(exchange_devices, gpio_config)

    set_gpio_config(result)
    set_new_timer()
    publish_device_state()

    post_slack_by_type(text='Devices are exchanged.',
                       type_=SLACK_NOTIFICATION_TYPE['NOTIFICATION'])
Пример #4
0
def device_update(message: str) -> None:
    update_device = json.loads(message)

    if update_device['type'] not in DEVICE_TYPE.values():
        raise DeviceTypeUndefined('This device type is undefined.')

    if update_device['run_type'] not in DEVICE_RUN_TYPE.values():
        raise DeviceRunTypeUndefined('This run type is undefined.')

    gpio_config = get_gpio_config()
    update_device_id = update_device['device_id']

    for device in gpio_config:
        if device['device_id'] == update_device_id:

            if device['device'] == {}:
                raise DeviceNotFound('Device does not found.')

            before_device = dict(device['device'])

            device['device']['name'] = update_device['name']
            device['device']['description'] = update_device['description']
            device['device']['type'] = update_device['type']
            device['device']['run_type'] = update_device['run_type']
            device['device']['options'] = update_device['options']
            device['device']['updated_at'] = int(
                datetime.datetime.now().strftime('%s'))
            break

    set_gpio_config(gpio_config)
    set_new_timer()
    publish_device_state()

    slack_post_text = SLACK_UPDATE_DEVICE_NOTIFICATION_FORMAT.format(
        now=formated_str_now_date(),
        device_id=update_device_id,
        before_name=before_device['name'],
        before_description=before_device['description'],
        before_type=before_device['type'],
        before_run_type=before_device['run_type'],
        after_name=update_device['name'],
        after_description=update_device['description'],
        after_type=update_device['type'],
        after_run_type=update_device['run_type'],
    )
    post_slack_by_type(
        text=slack_post_text,
        type_=SLACK_NOTIFICATION_TYPE['NOTIFICATION'],
    )
Пример #5
0
def device_create(message: str) -> None:
    new_device = json.loads(message)

    if new_device['type'] not in DEVICE_TYPE.values():
        raise DeviceTypeUndefined('This device type is undefined.')

    if new_device['run_type'] not in DEVICE_RUN_TYPE.values():
        raise DeviceRunTypeUndefined('This run type is undefined.')

    gpio_config = get_gpio_config()
    new_device_id = new_device['device_id']

    for device in gpio_config:
        if device['device_id'] == new_device_id:

            if device['device']:
                raise DeviceAlreadyExist('This device id is already used.')

            device['device'] = {
                'name': new_device['name'],
                'description': new_device['description'],
                'type': new_device['type'],
                'run_type': new_device['run_type'],
                'options': new_device['options'],
                'created_at': int(datetime.datetime.now().strftime('%s')),
                'updated_at': int(datetime.datetime.now().strftime('%s')),
            }
            break

    set_gpio_config(gpio_config)
    set_new_timer()
    publish_device_state()

    slack_post_text = SLACK_CREATE_DEVICE_NOTIFICATION_FORMAT.format(
        now=formated_str_now_date(),
        device_id=new_device_id,
        name=new_device['name'],
        description=new_device['description'],
        type_=new_device['type'],
        run_type=new_device['run_type'],
    )
    post_slack_by_type(text=slack_post_text,
                       type_=SLACK_NOTIFICATION_TYPE['NOTIFICATION'])
Пример #6
0
def device_control(message: str) -> None:
    target_devices = json.loads(message)['devices']
    devices = get_gpio_config()

    for target_device in target_devices:
        target_device_id = target_device['device_id']
        next_state = target_device['state']

        for device in devices:
            if device['device_id'] == target_device_id:

                # feed pump should not be controlled by this function
                if device['device']['type'] == DEVICE_TYPE['FEED_PUMP']:
                    continue

                BCM = device['BCM']
                gpio_write(BCM, int(next_state))
                break

    publish_device_state()
Пример #7
0
def set_init_device_state() -> None:
    devices = get_gpio_config()

    for device in devices:

        # no device
        if device['device'] == {}:
            continue

        # device run type is not daily
        if device['device']['run_type'] != DEVICE_RUN_TYPE['DAILY']:
            continue

        timer = device['device']['options']['timer']
        ideal_device_state = get_now_device_should_be_on_by_timer(
            on_hour=timer['on_hour'],
            on_minute=timer['on_minute'],
            off_hour=timer['off_hour'],
            off_minute=timer['off_minute'],
        )
        gpio_write(pin=device['BCM'], value=int(ideal_device_state))
Пример #8
0
def device_auto_feeder(message: str) -> None:
    auto_feeder_action = json.loads(message)

    devices = get_gpio_config()
    target_device_id = auto_feeder_action['device_id']

    for device in devices:
        if device['device_id'] == target_device_id:

            if device['device'] == {}:
                raise DeviceNotFound('Device does not found.')

            if device['device']['type'] != DEVICE_TYPE['AUTO_FEEDER']:
                raise DeviceOtherError('This is not auto feeder.')

            ams_root_path = get_root_path()
            entry_point = '/'.join(
                [ams_root_path, 'entry_points', 'auto_feeder.py'])
            cmd = 'python3 {entry_point} {device_id}'.format(
                entry_point=entry_point,
                device_id=target_device_id,
            )
            subprocess.Popen(cmd.split())
Пример #9
0
def device_feed_pump(message: str) -> None:
    feed_pump_action = json.loads(message)

    devices = get_gpio_config()
    target_device_id = feed_pump_action['device_id']

    for device in devices:
        if device['device_id'] == target_device_id:

            if device['device'] == {}:
                raise DeviceNotFound('Device does not found.')

            if device['device']['type'] != DEVICE_TYPE['FEED_PUMP']:
                raise DeviceOtherError('This is not feed pump.')

            ams_root_path = get_root_path()
            entry_point = '/'.join(
                [ams_root_path, 'entry_points', 'feed_pump.py'])
            cmd = 'python3 {entry_point} {device_id} {water_supply_time}'.format(
                entry_point=entry_point,
                device_id=target_device_id,
                water_supply_time=feed_pump_action['water_supply_time'],
            )
            subprocess.Popen(cmd.split())
Пример #10
0
def get_device_backup_file() -> str:
    return get_gpio_config()
Пример #11
0
def get_devices():
    ams_logger(request, DEBUG)
    devices = get_gpio_config()
    return json.dumps(devices)
Пример #12
0
def cron_text_generator() -> str:
    """
    This text is generated by this function.
    
    # ------ AMS start -------
    # device_id: 1
    # device_name: my_main_light
    # on
    30 10 * * * gpio -g mode 26 out && gpio -g write 26 1
    # off
    30 18 * * * gpio -g mode 26 out && gpio -g write 26 0

    # device_id: 2
    # device_name: my_sub_light
    # on
    30 10 * * * gpio -g mode 19 out && gpio -g write 19 1
    # off
    30 18 * * * gpio -g mode 19 out && gpio -g write 19 0

    ...

    # device_id: 5
    # device_name: feed_pump
    # on
    30 10 * * * python3 feed_pump.py [args]
    0 15 * * * python3 feed_pump.py [args]
    30 22 * * * python3 feed_pump.py [args]
    # ------ AMS end -------

    """
    gpio_config = get_gpio_config()

    # initial value
    cron_text = CRON_START_TEXT + '\n'

    for device in gpio_config:

        # if device does not exist
        if device['device'] == {}:
            continue

        # if the device runs continuously like a wave pump
        if device['device']['run_type'] == DEVICE_RUN_TYPE['CONTINUOUS']:
            # add comment
            cron_text += CRON_COMMENT_FORMAT.format(
                device_id=device['device_id'],
                device_name=device['device']['name'].replace('\n', ' '),
            )
            # add cron entries
            cron_text += CRON_FORMAT_CONTINUOUS.format(BCM=device['BCM'])
            cron_text += '\n\n'
            continue

        timer = device['device']['options']['timer']

        # if run type is "daily"
        if device['device']['run_type'] == DEVICE_RUN_TYPE['DAILY']:
            """
            "timer":{
                "on_hour":17,
                "on_minute":30,
                "off_hour":10,
                "off_minute":0
            }
            """
            # add comment
            cron_text += CRON_COMMENT_FORMAT.format(
                device_id=device['device_id'],
                device_name=device['device']['name'].replace('\n', ' '),
            )
            # add cron entry
            cron_text += CRON_FORMAT_DAILY.format(
                BCM=device['BCM'],
                on_minute=timer['on_minute'],
                on_hour=timer['on_hour'],
                off_minute=timer['off_minute'],
                off_hour=timer['off_hour'],
            )

        # if run type is "discreate"
        elif device['device']['run_type'] == DEVICE_RUN_TYPE['DISCREATE']:
            """
            "timer": [
                {"hour": 10, "minute": 30},
                {"hour": 15, "minute": 0},
                {"hour": 22, "minute": 30}
            ]
            """
            # There is not any timer entry.
            if len(timer) == 0:
                continue

            # add comment
            cron_text += CRON_COMMENT_FORMAT.format(
                device_id=device['device_id'],
                device_name=device['device']['name'].replace('\n', ' '),
            )
            # add cron entries
            for one_timer in timer:
                cron_text += CRON_FORMAT_DISCREATE.format(
                    minute=one_timer['minute'],
                    hour=one_timer['hour'],
                    cmd=cron_cmd_generator_by_type(
                        device['device']['type'],
                        device_id=device['device_id'],
                    ),
                )
            cron_text += '\n\n'

    cron_text += CRON_END_TEXT

    return cron_text
Пример #13
0
def get_all_device_by_device_id(device_id):
    devices = get_gpio_config()
    for device in devices:
        if device['device_id'] == device_id:
            return device
    return {}