示例#1
0
def get_devices():
    aws_iot = AwSIoT()
    thing_names = aws_iot.get_thing_list()
    thing_names.sort()

    def pid_exists(pid):
        try:
            os.kill(pid, 0)
        except OSError:
            return False
        else:
            return True

    def get_thing_simulation_state(thing_name):
        aws_iot_thing = aws_iot.get_iot_thing(thing_name)
        try:
            pid = aws_iot_thing.shadow['state']['reported']['pid']
            return pid > -1 and pid_exists(pid)
        except:
            return False

    thing_properties = json.dumps([{
        'thingName':
        name,
        'isRunning':
        get_thing_simulation_state(name)
    } for name in thing_names])
    return Response(thing_properties, mimetype='application/json')
示例#2
0
def get_intelligence():
    aws_iot = AwSIoT()
    thing_names = aws_iot.get_thing_list()

    db_client = boto3.client('dynamodb')
    pred_entities = db_client.query(
        TableName='predictions',
        ExpressionAttributeValues={
            ':key': {
                'S': '_INDEX_'
            },
        },
        ExpressionAttributeNames={
            '#P': 'Prediction',
            '#D': 'Timestamp',
            '#M': 'MachineID'
        },
        KeyConditionExpression='PartitionKey = :key',
        ProjectionExpression='#P, #D, #M')['Items']

    pred_entities.sort(key=lambda x: x['Timestamp']['S'], reverse=True)
    predictions_by_thing = {
        p['MachineID']['S']: (p['Prediction']['S'], p['Timestamp']['S'])
        for p in pred_entities
    }
    unknown_predictions = {
        thing_name: ('未知', None)
        for thing_name in thing_names if thing_name not in predictions_by_thing
    }
    combined = {**predictions_by_thing, **unknown_predictions}

    summary = {
        '被預測到的異常': 0,
        # '健康': 0,
        # '需要維修': 0,
        '未知': 0
    }

    summary_computed = collections.Counter([
        '被預測到的異常' if v[0].startswith('異常') else v[0]
        for v in combined.values()
    ])
    summary.update(summary_computed)

    payload = {
        'predictions': [{
            'deviceId': k,
            'prediction': v[0],
            'lastUpdated': v[1],
        } for (k, v) in combined.items()],
        'summary':
        summary
    }
    logging.log(logging.WARNING, payload)

    payload_json = json.dumps(payload)
    resp = Response(payload_json)
    resp.headers['Content-type'] = 'application/json'
    return resp
示例#3
0
def device_driver(thing_name):
    driver_unique_id = str(uuid.uuid4())
    aws_iot = AwSIoT()
    aws_iot_thing = aws_iot.get_iot_thing(thing_name)
    while True:
        try:
            claim_and_run_device(aws_iot_thing,  driver_unique_id)
            logging.log(logging.WARNING, 'Driver {0} finished execution.'.format(driver_unique_id))
        except Exception as e:
            logging.log(logging.ERROR, 'Driver {0} threw an exception: {1}.'.format(driver_unique_id, str(e)))
            aws_iot_thing.reset_simulator_state()
            break
        except:
            logging.log(logging.ERROR, 'Driver {0} threw an exception.')
            aws_iot_thing.reset_simulator_state()
            break
示例#4
0
def create_thing():
    thing_name = str.strip(request.form['thingName'])

    if not thing_name:
        return error_response('INVALID_ID', 'Thing name cannot be empty.',
                              HTTPStatus.BAD_REQUEST)

    try:
        simulation_properties = json.loads(
            request.form['simulationProperties'])
    except Exception as e:
        return error_response('INVALID_PARAMETERS', str(e),
                              HTTPStatus.BAD_REQUEST)

    aws_iot = AwSIoT()

    try:
        aws_iot.create_thing(thing_name, simulation_properties)
    except Exception as e:
        return error_response('INVALID_ID', str(e), HTTPStatus.BAD_REQUEST)

    return Response()
示例#5
0
def stop_thing_simulator(thing_name):
    aws_iot = AwSIoT()
    aws_iot.stop_thing_simulator(thing_name)

    resp = Response()
    return resp
示例#6
0
def delete_device(thing_name):
    aws_iot = AwSIoT()
    aws_iot.delete_thing(thing_name)

    resp = Response()
    return resp