Exemplo n.º 1
0
 def get_latest_gampang_template_string(self, supported_board_uuid):
     db = GudangMongoDB()
     latest_template_document = db.get_latest_gampang_template_document(
         supported_board_uuid=supported_board_uuid)
     # Get the code object from s3
     code_object = self.get_object(
         target_bucket=RUMAHIOT_UPLOAD_BUCKET,
         target_file=latest_template_document['s3_path'])
     return code_object['Body'].read().decode('utf-8')
Exemplo n.º 2
0
    def get_n_random_material_color(self, n):
        db = GudangMongoDB()
        color_list = []
        db_color = db.get_material_color_document()
        # Pop the object id
        db_color.pop('_id')
        db_color_list = list(db_color.values())

        for i in range(0, n):
            rand_int = random.randint(0, len(db_color_list)-1)
            color_list.append(db_color_list[rand_int])

        return color_list
Exemplo n.º 3
0
def remove_user_device(request, user, device_uuid):

    # Gudang class
    rg = ResponseGenerator()
    db = GudangMongoDB()

    device = db.get_device_data_by_uuid(user_uuid=user['user_uuid'],
                                        device_uuid=device_uuid)
    if (device):
        # Remove the device
        db.remove_user_device(device_uuid=device_uuid)
        response_data = rg.success_response_generator(
            200, 'Device successfully removed')
        return HttpResponse(json.dumps(response_data),
                            content_type='application/json',
                            status=200)
    else:
        response_data = rg.error_response_generator(400, 'Invalid device uuid')
        return HttpResponse(json.dumps(response_data),
                            content_type='application/json',
                            status=400)
Exemplo n.º 4
0
def remove_supported_sensor(request, user, master_sensor_reference_uuid):

    # Gudang class
    rg = ResponseGenerator()
    db = GudangMongoDB()

    master_sensor_reference = db.get_master_sensor_reference_by_uuid(
        master_sensor_reference_uuid=master_sensor_reference_uuid)
    if (master_sensor_reference):
        # Check master sensor uuid
        for master_sensor_uuid in master_sensor_reference[
                'master_sensor_uuids']:
            user_sensor = db.get_user_sensor_by_master_sensor(
                master_sensor_uuid=master_sensor_uuid)
            if not user_sensor:
                # Remove the supported sensor
                db.remove_supported_sensor(
                    master_sensor_reference_uuid=master_sensor_reference_uuid)
                response_data = rg.success_response_generator(
                    200, 'Sensor successfully removed')
                return HttpResponse(json.dumps(response_data),
                                    content_type='application/json',
                                    status=200)
            else:
                response_data = rg.error_response_generator(
                    400, 'Sensor being used by one or more user device')
                return HttpResponse(json.dumps(response_data),
                                    content_type='application/json',
                                    status=400)
    else:
        response_data = rg.error_response_generator(
            400, 'Invalid supported sensor UUID')
        return HttpResponse(json.dumps(response_data),
                            content_type='application/json',
                            status=400)
Exemplo n.º 5
0
def remove_supported_board(request, user, board_uuid):

    # Gudang class
    rg = ResponseGenerator()
    db = GudangMongoDB()

    # Check if the board being used by a device
    device = db.get_device_by_board_uuid(board_uuid=board_uuid)

    if device.count(True) == 0:
        # Check the board
        board = db.get_supported_board_by_uuid(board_uuid=board_uuid)
        if (board):
            db.remove_supported_board(board_uuid=board_uuid)
            response_data = rg.success_response_generator(
                200, 'Board successfully removed')
            return HttpResponse(json.dumps(response_data),
                                content_type='application/json',
                                status=200)
        else:
            response_data = rg.error_response_generator(
                400, 'Invalid board uuid')
            return HttpResponse(json.dumps(response_data),
                                content_type='application/json',
                                status=400)
    else:
        response_data = rg.error_response_generator(
            400, 'Board being used by one or more user device')
        return HttpResponse(json.dumps(response_data),
                            content_type='application/json',
                            status=400)
Exemplo n.º 6
0
def store_new_device(request, user):

    # Gudang Classes
    rg = ResponseGenerator()
    db = GudangMongoDB()
    gutils = GudangUtils()

    # Verify the root structure
    try:
        j = json.loads(request.body.decode('utf-8'))
        new_device = NewDeviceResource(**j)
    except TypeError:
        response_data = rg.error_response_generator(
            400, 'One of the request inputs is not valid')
        return HttpResponse(json.dumps(response_data),
                            content_type='application/json',
                            status=400)
    except ValueError:
        response_data = rg.error_response_generator(400, 'Malformed JSON')
        return HttpResponse(json.dumps(response_data),
                            content_type='application/json',
                            status=400)
    else:
        if (gutils.string_length_checker(new_device.location_text, 128)
                and gutils.string_length_checker(new_device.device_name, 32)
                and gutils.check_data_sending_interval_value(
                    new_device.device_data_sending_interval)):
            # Check device wifi connection
            user_wifi_connection = db.get_user_wifi_connection_by_uuid(
                user_uuid=user['user_uuid'],
                user_wifi_connection_uuid=new_device.user_wifi_connection_uuid)
            if user_wifi_connection != None:
                # Verify location structure
                try:
                    position = DevicePositionResource(**new_device.position)
                except TypeError:
                    response_data = rg.error_response_generator(
                        400, 'One of the request inputs is not valid')
                    return HttpResponse(json.dumps(response_data),
                                        content_type='application/json',
                                        status=400)
                except ValueError:
                    response_data = rg.error_response_generator(
                        400, 'Malformed JSON')
                    return HttpResponse(json.dumps(response_data),
                                        content_type='application/json',
                                        status=400)

                else:
                    # Make sure lat and lng is float
                    if gutils.float_int_check(
                            position.lat) and gutils.float_int_check(
                                position.lng):
                        # Check supported board uuid
                        supported_board = db.get_supported_board_by_uuid(
                            board_uuid=new_device.supported_board_uuid)
                        if supported_board != None:
                            # Check user_sensor structure and validity
                            # Make the copy for board pin structure checking
                            supported_board_copy = copy.deepcopy(
                                supported_board)
                            # total sensor pin ( Do not count NC pin)
                            sensor_pin_total = 0
                            for added_sensor in new_device.added_sensors:
                                try:
                                    sensor = AddedSensorResource(
                                        **added_sensor)
                                except TypeError:
                                    response_data = rg.error_response_generator(
                                        400,
                                        'One of the request inputs is not valid'
                                    )
                                    return HttpResponse(
                                        json.dumps(response_data),
                                        content_type='application/json',
                                        status=400)
                                except ValueError:
                                    response_data = rg.error_response_generator(
                                        400, 'Malformed JSON')
                                    return HttpResponse(
                                        json.dumps(response_data),
                                        content_type='application/json',
                                        status=400)
                                else:
                                    if (gutils.string_length_checker(
                                            sensor.added_sensor_name, 32)):
                                        # Check master reference sensor
                                        master_sensor_reference = db.get_master_sensor_reference_by_uuid(
                                            master_sensor_reference_uuid=sensor
                                            .master_sensor_reference_uuid)
                                        if master_sensor_reference != None:
                                            # Check pin mapping structure ( data validity will be checked in different function)
                                            for pin_mapping in sensor.sensor_pin_mappings:
                                                try:
                                                    pin = SensorPinMappingResource(
                                                        **pin_mapping)
                                                except TypeError:
                                                    response_data = rg.error_response_generator(
                                                        400,
                                                        'One of the request inputs is not valid'
                                                    )
                                                    return HttpResponse(
                                                        json.dumps(
                                                            response_data),
                                                        content_type=
                                                        'application/json',
                                                        status=400)
                                                except ValueError:
                                                    response_data = rg.error_response_generator(
                                                        400, 'Malformed JSON')
                                                    return HttpResponse(
                                                        json.dumps(
                                                            response_data),
                                                        content_type=
                                                        'application/json',
                                                        status=400)
                                                else:
                                                    # Count total sensor pin ( NC pin should not be count)
                                                    if pin.device_pin == "NC" and pin.device_pin_name == "NC" and pin.function == "NC":
                                                        pass
                                                    else:
                                                        sensor_pin_total += 1

                                            # Match the submitted pin configuration with master sensor configuration
                                            if not gutils.validate_sensor_pin_mapping(
                                                    added_sensor_pin_mappings=
                                                    added_sensor[
                                                        'sensor_pin_mappings'],
                                                    master_sensor_reference_pin_mappings
                                                    =master_sensor_reference[
                                                        'sensor_pin_mappings']
                                            ):
                                                response_data = rg.error_response_generator(
                                                    400,
                                                    'Invalid sensor pin structure'
                                                )
                                                return HttpResponse(
                                                    json.dumps(response_data),
                                                    content_type=
                                                    'application/json',
                                                    status=400)
                                        else:
                                            response_data = rg.error_response_generator(
                                                400,
                                                'Invalid master sensor reference uuid'
                                            )
                                            return HttpResponse(
                                                json.dumps(response_data),
                                                content_type='application/json',
                                                status=400)
                                    else:
                                        response_data = rg.error_response_generator(
                                            400,
                                            'Invalid added sensor string length'
                                        )
                                        return HttpResponse(
                                            json.dumps(response_data),
                                            content_type='application/json',
                                            status=400)

                                # Validate the pin configuration
                                if not gutils.validate_board_pin_mapping(
                                        added_sensor_pin_mappings=added_sensor[
                                            'sensor_pin_mappings'],
                                        supported_board_pin_mappings=
                                        supported_board_copy['board_pins']):
                                    response_data = rg.error_response_generator(
                                        400, 'Invalid sensor pin structure')
                                    return HttpResponse(
                                        json.dumps(response_data),
                                        content_type='application/json',
                                        status=400)

                            # Check if the resulting structure mutation is correct
                            if (len(supported_board['board_pins']) == len(
                                    supported_board_copy['board_pins']) +
                                    sensor_pin_total):

                                # THE DATA THAT ENTER THIS STATE SHOULD BE FULLY VERIFIED AND NORMALIZED
                                ########################################################################

                                user_sensor_uuids = []

                                # For each added sensor
                                for added_sensor in new_device.added_sensors:
                                    # Make user_sensor mapping
                                    new_user_sensor_mapping = {
                                        'user_sensor_mapping_uuid':
                                        uuid4().hex,
                                        'time_added':
                                        float(datetime.now().timestamp()),
                                        'sensor_pin_mappings':
                                        added_sensor['sensor_pin_mappings']
                                    }

                                    # Write into db
                                    db.put_user_sensor_mapping(
                                        user_sensor_mapping=
                                        new_user_sensor_mapping)

                                    # Get master sensor reference
                                    # Threshold defaulting to disabled when new device is added
                                    master_sensor_reference = db.get_master_sensor_reference_by_uuid(
                                        master_sensor_reference_uuid=
                                        added_sensor[
                                            'master_sensor_reference_uuid'])
                                    for master_sensor_uuid in master_sensor_reference[
                                            'master_sensor_uuids']:
                                        master_sensor = db.get_master_sensor_by_uuid(
                                            master_sensor_uuid=
                                            master_sensor_uuid)
                                        new_user_sensor = {
                                            'user_uuid':
                                            user['user_uuid'],
                                            'user_sensor_uuid':
                                            uuid4().hex,
                                            'user_sensor_name':
                                            added_sensor['added_sensor_name'],
                                            'master_sensor_uuid':
                                            master_sensor_uuid,
                                            'sensor_threshold':
                                            float(0),
                                            'currently_over_threshold':
                                            False,
                                            'threshold_direction':
                                            '1',
                                            'threshold_enabled':
                                            False,
                                            'user_sensor_mapping_uuid':
                                            new_user_sensor_mapping[
                                                'user_sensor_mapping_uuid']
                                        }
                                        # Write into db
                                        db.put_user_sensor(
                                            user_sensor=new_user_sensor)
                                        user_sensor_uuids.append(
                                            new_user_sensor['user_sensor_uuid']
                                        )

                                # User device structure
                                user_device = {
                                    'supported_board_uuid':
                                    new_device.supported_board_uuid,
                                    'user_sensor_uuids': user_sensor_uuids,
                                    'device_uuid': uuid4().hex,
                                    'position': {
                                        'lat': float(position.lat),
                                        'lng': float(position.lng)
                                    },
                                    'location_text': new_device.location_text,
                                    'read_key': uuid4().hex,
                                    'time_added':
                                    float(datetime.now().timestamp()),
                                    'user_uuid': user['user_uuid'],
                                    'write_key': uuid4().hex,
                                    'device_name': new_device.device_name,
                                    'user_wifi_connection_uuid':
                                    new_device.user_wifi_connection_uuid,
                                    'device_data_sending_interval':
                                    new_device.device_data_sending_interval,
                                    'removed': False
                                }

                                # Write into db
                                db.put_user_device(user_device=user_device)

                                # Device successfully added
                                response_data = rg.success_response_generator(
                                    200, "Device successfully added")
                                return HttpResponse(
                                    json.dumps(response_data),
                                    content_type="application/json",
                                    status=200)

                            else:
                                response_data = rg.error_response_generator(
                                    400, 'Invalid board pin structure')
                                return HttpResponse(
                                    json.dumps(response_data),
                                    content_type='application/json',
                                    status=400)
                        else:
                            response_data = rg.error_response_generator(
                                400, 'Invalid supported board uuid')
                            return HttpResponse(
                                json.dumps(response_data),
                                content_type='application/json',
                                status=400)
                    else:
                        response_data = rg.error_response_generator(
                            400, 'Invalid position coordinate data type')
                        return HttpResponse(json.dumps(response_data),
                                            content_type='application/json',
                                            status=400)
            else:
                response_data = rg.error_response_generator(
                    400, 'invalid user wifi connection uuid')
                return HttpResponse(json.dumps(response_data),
                                    content_type='application/json',
                                    status=400)
        else:
            response_data = rg.error_response_generator(
                400, 'Invalid added device string length')
            return HttpResponse(json.dumps(response_data),
                                content_type='application/json',
                                status=400)
Exemplo n.º 7
0
def store_device_data(request):
    # Gudang classes
    rg = ResponseGenerator()
    # Construct sensor_list from request and compare it with the one in the user_device document
    sensor_list = []

    try:
        # Verify the data format
        j = json.loads(request.body.decode('utf-8'))
        d = DeviceDataResource(**j)
        db = GudangMongoDB()
        gutils = GudangUtils()

    except TypeError:
        response_data = rg.error_response_generator(
            400, "One of the request inputs is not valid")
        return HttpResponse(json.dumps(response_data),
                            content_type="application/json",
                            status=400)
    except ValueError:
        response_data = rg.error_response_generator(400, "Malformed JSON")
        return HttpResponse(json.dumps(response_data),
                            content_type="application/json",
                            status=400)
    else:
        # make sure the device data type is correct
        # str for write_key and list for sensor_datas
        if type(d.write_key) is str and type(d.sensor_datas) is list:
            # check the write key
            device_data = db.get_user_device_data(key=d.write_key,
                                                  key_type="w")
            if device_data != None:
                # Check the data structure and make sure the sensor exist in user device
                for data in d.sensor_datas:
                    try:
                        # Verify the sensor data
                        s = SensorDataResource(**data)
                    except TypeError:
                        response_data = rg.error_response_generator(
                            400, "One of the request inputs is not valid")
                        return HttpResponse(json.dumps(response_data),
                                            content_type="application/json",
                                            status=400)
                    except ValueError:
                        response_data = rg.error_response_generator(
                            400, "Malformed JSON")
                        return HttpResponse(json.dumps(response_data),
                                            content_type="application/json",
                                            status=400)
                    else:
                        # make sure the sensor data type is correct
                        # str for device_sensor_uuid and float for device_sensor_value
                        # Do not forget NaN will be detected as float
                        if type(s.user_sensor_uuid
                                ) is str and gutils.float_int_check(
                                    s.user_sensor_value):
                            # Append the uuid from request to comapre with the one in user_device document
                            sensor_list.append(s.user_sensor_uuid)
                            pass
                        else:
                            response_data = rg.error_response_generator(
                                400, "Incorrect field type")
                            return HttpResponse(
                                json.dumps(response_data),
                                content_type="application/json",
                                status=400)

                # Sensor list from corresponding device
                db_sensor_list = [
                    sensor for sensor in device_data['user_sensor_uuids']
                ]

                # Use sort to make sure both data in the same order

                db_sensor_list.sort()
                sensor_list.sort()

                # Match the data from user_device collection with the one from the request
                if db_sensor_list == sensor_list:
                    try:
                        # put the time into the data
                        j['time_added'] = datetime.now().timestamp()
                        # Put the write key away
                        j.pop('write_key', None)
                        # Add the device_uuid
                        j['device_uuid'] = device_data['device_uuid']
                    # for unknown error
                    except:
                        response_data = rg.error_response_generator(
                            500, "Internal server error")
                        return HttpResponse(json.dumps(response_data),
                                            content_type="application/json",
                                            status=500)
                    else:
                        # Put the data first
                        response = db.put_data(
                            database=RUMAHIOT_GUDANG_DATABASE,
                            collection=RUMAHIOT_GUDANG_DEVICE_DATA_COLLECTION,
                            data=j)
                        # Todo : Find a better way to do this (might be slow at scale)
                        # Check the value of each sensor
                        for sensor_data in j['sensor_datas']:
                            # Todo : Check the output and put it in the log
                            # Put device data in the too so it can be used when the threshold criteria met
                            threshold_check_success = gutils.check_sensor_threshold(
                                user_sensor_uuid=sensor_data[
                                    'user_sensor_uuid'],
                                sensor_value=sensor_data['user_sensor_value'],
                                device_data=device_data)

                            if not threshold_check_success:
                                response_data = rg.error_response_generator(
                                    500, "Internal server error")
                                return HttpResponse(
                                    json.dumps(response_data),
                                    content_type="application/json",
                                    status=500)
                        if response != None:
                            response_data = rg.success_response_generator(
                                200, "Device data successfully submitted")
                            return HttpResponse(
                                json.dumps(response_data),
                                content_type="application/json",
                                status=200)
                        else:
                            # If the mongodb server somehow didn't return the object id
                            response_data = rg.error_response_generator(
                                500, "Internal server error")
                            return HttpResponse(
                                json.dumps(response_data),
                                content_type="application/json",
                                status=500)
                else:
                    response_data = rg.error_response_generator(
                        400, "Invalid sensor configuration")
                    return HttpResponse(json.dumps(response_data),
                                        content_type="application/json",
                                        status=400)
            else:
                response_data = rg.error_response_generator(
                    400, "Invalid Write Key")
                return HttpResponse(json.dumps(response_data),
                                    content_type="application/json",
                                    status=400)
        else:
            response_data = rg.error_response_generator(
                400, "Incorrect field type")
            return HttpResponse(json.dumps(response_data),
                                content_type="application/json",
                                status=400)
Exemplo n.º 8
0
def store_new_supported_sensor(request, user):

    # Gudang classes
    rg = ResponseGenerator()
    db = GudangMongoDB()

    try:
        # Verify JSON structure
        j = json.loads(request.body.decode('utf-8'))

    except TypeError:
        response_data = rg.error_response_generator(
            400, "One of the request inputs is not valid")
        return HttpResponse(json.dumps(response_data),
                            content_type="application/json",
                            status=400)
    except ValueError:
        response_data = rg.error_response_generator(400, "Malformed JSON")
        return HttpResponse(json.dumps(response_data),
                            content_type="application/json",
                            status=400)
    else:
        # Verify the data format for added board
        try:
            added_sensor = NewSupportedSensorResource(**j)
        except TypeError:
            response_data = rg.error_response_generator(
                400, "One of the sensor data structure is not valid")
            return HttpResponse(json.dumps(response_data),
                                content_type="application/json",
                                status=400)
        except ValueError:
            response_data = rg.error_response_generator(400, "Malformed JSON")
            return HttpResponse(json.dumps(response_data),
                                content_type="application/json",
                                status=400)
        else:
            # Check for library variable initialization
            try:
                lib = LibraryVariableInitializationResource(
                    **added_sensor.library_variable_initialization)
            except TypeError:
                response_data = rg.error_response_generator(
                    400, "One of the library data structure is not valid")
                return HttpResponse(json.dumps(response_data),
                                    content_type="application/json",
                                    status=400)
            except ValueError:
                response_data = rg.error_response_generator(
                    400, "Malformed JSON")
                return HttpResponse(json.dumps(response_data),
                                    content_type="application/json",
                                    status=400)
            else:
                # Check for sensor pin mapping
                for sensor_pin_mapping in added_sensor.sensor_pin_mappings:
                    try:
                        sensor_mapping = NewSupportedSensorMappingResource(
                            **sensor_pin_mapping)
                    except TypeError:
                        response_data = rg.error_response_generator(
                            400,
                            "One of the sensor pin mapping structure is not valid"
                        )
                        return HttpResponse(json.dumps(response_data),
                                            content_type="application/json",
                                            status=400)
                    except ValueError:
                        response_data = rg.error_response_generator(
                            400, "Malformed JSON")
                        return HttpResponse(json.dumps(response_data),
                                            content_type="application/json",
                                            status=400)

                # Check for master sensors
                for master_sensor in added_sensor.master_sensors:
                    try:
                        sensor = MasterSensorResource(**master_sensor)
                    except TypeError:
                        response_data = rg.error_response_generator(
                            400,
                            "One of the sensor master data structure is not valid"
                        )
                        return HttpResponse(json.dumps(response_data),
                                            content_type="application/json",
                                            status=400)
                    except ValueError:
                        response_data = rg.error_response_generator(
                            400, "Malformed JSON")
                        return HttpResponse(json.dumps(response_data),
                                            content_type="application/json",
                                            status=400)

                # Store new supported sensor
                db.put_new_supported_sensor(
                    library_dependencies=added_sensor.library_dependencies,
                    library_initialization_command=added_sensor.
                    library_initialization_command,
                    library_variable_initialization=added_sensor.
                    library_variable_initialization,
                    master_sensors=added_sensor.master_sensors,
                    sensor_image_source=added_sensor.sensor_image_source,
                    sensor_image_url=added_sensor.sensor_image_url,
                    sensor_model=added_sensor.sensor_model,
                    sensor_pin_mappings=added_sensor.sensor_pin_mappings)

                response_data = rg.success_response_generator(
                    200, "New supported sensor successfully added")
                return HttpResponse(json.dumps(response_data),
                                    content_type="application/json",
                                    status=200)
Exemplo n.º 9
0
def store_generated_device_xlsx_data(request, user):

    # Gudang Classes
    rg = ResponseGenerator()
    db = GudangMongoDB()
    gutils = GudangUtils()

    form = ExportXlsxDeviceDataForm(request.POST)
    if form.is_valid():
        if (gutils.float_check(form.cleaned_data['from_time'])
                and gutils.float_check(form.cleaned_data['to_time'])):
            if (float(form.cleaned_data['from_time']) < float(
                    form.cleaned_data['to_time'])):
                # Check for the device
                device = db.get_device_data_by_uuid(
                    user_uuid=user['user_uuid'],
                    device_uuid=form.cleaned_data['device_uuid'])
                if (device):
                    # Check for timezone
                    if form.cleaned_data['time_zone'] in all_timezones:

                        user_exported_xlsx_uuid = uuid4().hex
                        date_format = "%d-%m-%Y %H:%M:%S"

                        # Write reserved object into db
                        db.put_user_exported_xlsx(
                            user_uuid=user['user_uuid'],
                            user_exported_xlsx_uuid=user_exported_xlsx_uuid,
                            device_uuid=device['device_uuid'],
                            from_time=float(form.cleaned_data['from_time']),
                            to_time=float(form.cleaned_data['to_time']))

                        # Call the async function for generating the sheets
                        # Todo : make the query call more efficient, by cutting the validation steps
                        buffered_xlsxwriter(
                            device_uuid=form.cleaned_data['device_uuid'],
                            user_uuid=user['user_uuid'],
                            from_time=float(form.cleaned_data['from_time']),
                            to_time=float(form.cleaned_data['to_time']),
                            user_exported_xlsx_uuid=user_exported_xlsx_uuid,
                            time_zone=form.cleaned_data['time_zone'])

                        # Return the response object
                        # Device successfully added
                        response_data = rg.success_response_generator(
                            200,
                            "Excel document export successfully queued, you can access the data in Exported Data section when it is ready"
                        )
                        return HttpResponse(json.dumps(response_data),
                                            content_type="application/json",
                                            status=200)

                    else:
                        response_data = rg.error_response_generator(
                            400, 'Invalid timezone')
                        return HttpResponse(json.dumps(response_data),
                                            content_type='application/json',
                                            status=400)
                else:
                    response_data = rg.error_response_generator(
                        400, 'Invalid device uuid')
                    return HttpResponse(json.dumps(response_data),
                                        content_type='application/json',
                                        status=400)
            else:
                response_data = rg.error_response_generator(
                    400, 'From time must be smaller than to time')
                return HttpResponse(json.dumps(response_data),
                                    content_type='application/json',
                                    status=400)
        else:
            response_data = rg.error_response_generator(
                400, 'Invalid time data format')
            return HttpResponse(json.dumps(response_data),
                                content_type='application/json',
                                status=400)
    else:
        response_data = rg.error_response_generator(
            400, 'Invalid form parameter submitted')
        return HttpResponse(json.dumps(response_data),
                            content_type='application/json',
                            status=400)
Exemplo n.º 10
0
def store_new_supported_board(request, user):

    # Gudang Classes
    rg = ResponseGenerator()
    db = GudangMongoDB()

    try:
        # Verify JSON structure
        j = json.loads(request.body.decode('utf-8'))

    except TypeError:
        response_data = rg.error_response_generator(
            400, "One of the request inputs is not valid")
        return HttpResponse(json.dumps(response_data),
                            content_type="application/json",
                            status=400)
    except ValueError:
        response_data = rg.error_response_generator(400, "Malformed JSON")
        return HttpResponse(json.dumps(response_data),
                            content_type="application/json",
                            status=400)
    else:

        # Verify the data format for added board
        try:
            added_board = NewSupportedBoardResource(**j)
        except TypeError:
            response_data = rg.error_response_generator(
                400, "One of the board data structure is not valid")
            return HttpResponse(json.dumps(response_data),
                                content_type="application/json",
                                status=400)
        except ValueError:
            response_data = rg.error_response_generator(400, "Malformed JSON")
            return HttpResponse(json.dumps(response_data),
                                content_type="application/json",
                                status=400)
        else:
            # Verify the sensor pin configuration
            # Todo : Make sure all of the data is in correct format
            for board_pin in added_board.board_pins:
                try:
                    pin = NewSupportedBoardPinResource(**board_pin)
                except TypeError:
                    response_data = rg.error_response_generator(
                        400,
                        "One of the board pin data structure is not valid")
                    return HttpResponse(json.dumps(response_data),
                                        content_type="application/json",
                                        status=400)
                except ValueError:
                    response_data = rg.error_response_generator(
                        400, "Malformed JSON")
                    return HttpResponse(json.dumps(response_data),
                                        content_type="application/json",
                                        status=400)

            # All data successfully verified in this step
            # Put new board in db
            db.put_new_supported_board(
                board_name=added_board.board_name,
                chip=added_board.chip,
                manufacturer=added_board.manufacturer,
                board_specification=added_board.board_specification,
                board_image=added_board.board_image,
                board_image_source=added_board.board_image_source,
                board_pins=added_board.board_pins,
                s3_path=added_board.s3_path,
                version=added_board.version)

            response_data = rg.success_response_generator(
                200, "New board successfully added")
            return HttpResponse(json.dumps(response_data),
                                content_type="application/json",
                                status=200)
Exemplo n.º 11
0
def update_device_detail(request, user):
    # Gudang class
    rg = ResponseGenerator()
    db = GudangMongoDB()
    gutils = GudangUtils()

    try:
        json_body = json.loads(request.body.decode('utf-8'))
        new_device_detail = UpdateDeviceDetailResource(**json_body)
    except TypeError:
        response_data = rg.error_response_generator(
            400, "One of the request inputs is not valid")
        return HttpResponse(json.dumps(response_data),
                            content_type="application/json",
                            status=400)
    except ValueError:
        response_data = rg.error_response_generator(400, "Malformed JSON")
        return HttpResponse(json.dumps(response_data),
                            content_type="application/json",
                            status=400)
    else:
        try:
            # Verify location value exist
            position = (DevicePositionResource(**new_device_detail.position))
        except TypeError:
            response_data = rg.error_response_generator(
                400, "One of the request inputs is not valid")
            return HttpResponse(json.dumps(response_data),
                                content_type="application/json",
                                status=400)
        except ValueError:
            response_data = rg.error_response_generator(400, "Malformed JSON")
            return HttpResponse(json.dumps(response_data),
                                content_type="application/json",
                                status=400)
        else:
            # Check for the datatype
            if gutils.string_length_checker(
                    new_device_detail.device_uuid,
                    32) and gutils.string_length_checker(
                        new_device_detail.device_name, 32) and type(
                            new_device_detail.user_wifi_connection_uuid
                        ) is str and type(
                            new_device_detail.device_name) is str and type(
                                new_device_detail.device_uuid
                            ) is str and gutils.float_int_check(
                                position.lat) and gutils.float_int_check(
                                    position.lng) and type(
                                        new_device_detail.location_text
                                    ) is str and gutils.float_int_check(
                                        new_device_detail.
                                        device_data_sending_interval):
                # check user_wifi_connection_uuid
                if (new_device_detail.device_data_sending_interval <= 1440 and
                        new_device_detail.device_data_sending_interval >= 5):
                    wifi_connection = db.get_user_wifi_connection_by_uuid(
                        user_uuid=user['user_uuid'],
                        user_wifi_connection_uuid=new_device_detail.
                        user_wifi_connection_uuid)
                    if (wifi_connection):
                        db.update_device_detail(
                            device_uuid=new_device_detail.device_uuid,
                            device_name=new_device_detail.device_name,
                            position=new_device_detail.position,
                            user_wifi_connection_uuid=new_device_detail.
                            user_wifi_connection_uuid,
                            location_text=new_device_detail.location_text,
                            device_data_sending_interval=new_device_detail.
                            device_data_sending_interval)
                        # Device successfully added
                        response_data = rg.success_response_generator(
                            200, 'Device detail successfully updated')
                        return HttpResponse(json.dumps(response_data),
                                            content_type='application/json',
                                            status=200)
                    else:
                        response_data = rg.error_response_generator(
                            400, 'Invalid wifi connection uuid')
                        return HttpResponse(json.dumps(response_data),
                                            content_type='application/json',
                                            status=400)
                else:
                    response_data = rg.error_response_generator(
                        400, 'Invalid device data sending interval')
                    return HttpResponse(json.dumps(response_data),
                                        content_type='application/json',
                                        status=400)
            else:
                response_data = rg.error_response_generator(
                    400, 'Invalid request data type')
                return HttpResponse(json.dumps(response_data),
                                    content_type='application/json',
                                    status=400)
Exemplo n.º 12
0
class GudangTemplateMaster:

    def __init__(self, device, wifi_connection, tls_fingerprint):
        self.s3 = GudangS3()
        self.db = GudangMongoDB()
        self.gutils = GudangUtils()
        self.device = device
        self.wifi_connection = wifi_connection
        self.tls_fingerprint = tls_fingerprint
        self.library_dependencies = []
        self.sensor_configurations = []
        # For differentiating between each sensor
        user_sensor_mapping_uuid_temp = []
        master_sensor_reference_uuid_temp = []

        for user_sensor_uuid in self.device['user_sensor_uuids']:
            # Todo : Find a better way to optimize the query
            user_sensor = self.db.get_user_sensor_by_uuid(user_sensor_uuid=user_sensor_uuid)
            user_sensor_mapping = self.db.get_sensor_mapping_by_uuid(user_sensor_mapping_uuid=user_sensor['user_sensor_mapping_uuid'])
            master_sensor = self.db.get_master_sensor_by_uuid(master_sensor_uuid=user_sensor['master_sensor_uuid'])
            master_sensor_reference = self.db.get_master_sensor_reference_by_uuid(master_sensor_reference_uuid=master_sensor['master_sensor_reference_uuid'])
            # Added library
            # Iterate through library dependencies inside master sensor referece
            for library_dependency in master_sensor_reference['library_dependencies']:
                if library_dependency not in self.library_dependencies:
                    # only add it it if it's haven't been added earlier
                    self.library_dependencies.append(library_dependency)

            # Mark sensor mapping and master sensor reference
            if user_sensor_mapping['user_sensor_mapping_uuid'] not in user_sensor_mapping_uuid_temp:
                user_sensor_mapping_uuid_temp.append(user_sensor_mapping['user_sensor_mapping_uuid'])
                master_sensor_reference_uuid_temp.append(master_sensor_reference['master_sensor_reference_uuid'])

        # Library variable initialization
        for mapping_index in range(0,len(user_sensor_mapping_uuid_temp)):
            master_sensor_reference = self.db.get_master_sensor_reference_by_uuid(master_sensor_reference_uuid=master_sensor_reference_uuid_temp[mapping_index])
            user_sensor_mapping = self.db.get_sensor_mapping_by_uuid(user_sensor_mapping_uuid=user_sensor_mapping_uuid_temp[mapping_index])
            # Retrieve the user sensor back
            user_sensors = self.db.get_user_sensor_by_mapping_uuid(user_sensor_mapping_uuid=user_sensor_mapping_uuid_temp[mapping_index])
            # Random varname for each sensor
            sensor_varname = self.gutils.generate_random_id(8)
            # List for sensor code formatting
            code_filler_list = []
            # List for sensor configuration for each physical sensor
            sensor_json_configuration_format_list = []
            # List for digital pin that used as ground pin
            grounded_digital_pin_list = []

            # For digital pin that used as ground pin
            for sensor_pin_mapping in user_sensor_mapping['sensor_pin_mappings']:
                if (sensor_pin_mapping['function'] == 'GROUND') and (sensor_pin_mapping['device_pin'] != 'GND'):
                    grounded_digital_pin_list.append('pinMode({}, OUTPUT);\ndigitalWrite({}, LOW);'.format(sensor_pin_mapping['device_arduino_pin'], sensor_pin_mapping['device_arduino_pin']))

            for code_filler in master_sensor_reference['library_variable_initialization']['code_filler']:
                # Generate the variable name
                if code_filler == 'VARNAME':
                    code_filler_list.append(sensor_varname)
                else:
                    for sensor_pin_mapping in user_sensor_mapping['sensor_pin_mappings']:
                        if sensor_pin_mapping['function'] == code_filler:
                            code_filler_list.append(sensor_pin_mapping['device_arduino_pin'])

            # Iterate through each sensor value for each physical sensor
            for sensor in user_sensors:
                sensor_value_varname = self.gutils.generate_random_id(8)
                master_sensor = self.db.get_master_sensor_by_uuid(master_sensor_uuid=sensor['master_sensor_uuid'])
                # Generate the json configuration for each sensor value
                sensor_json_configuration_format_list.append('\t\tJsonObject& {} = sensor_datas.createNestedObject();\n\t\t{}["user_sensor_uuid"] = "{}";\n\t\t{}["user_sensor_value"] = {}.{}'.format(sensor_value_varname, sensor_value_varname, sensor['user_sensor_uuid'], sensor_value_varname, sensor_varname, master_sensor['master_sensor_library_function']))

            # Configuration for each physical sensor
            sensor_configuration = {
                'sensor_var_name': sensor_varname,
                'library_variable_initialization_code' : master_sensor_reference['library_variable_initialization']['code'].format(*code_filler_list),
                'library_initialization_commands':  master_sensor_reference['library_initialization_command'].format(sensor_varname),
                'sensor_configuration_datas': sensor_json_configuration_format_list,
                'grounded_digital_pins': grounded_digital_pin_list
            }
            self.sensor_configurations.append(sensor_configuration)


    # Generate arduino code using template and user provided data
    def generate_gampang_template(self):
        # Grab the latest template
        latest_gampang_template = Template(self.s3.get_latest_gampang_template_string(self.device['supported_board_uuid']))
        # Prepare the parameters
        write_key = self.device['write_key']
        ssid = self.wifi_connection['ssid']
        # Wifi password
        if (self.wifi_connection['security_enabled']):
            wifi_password = self.wifi_connection['password']
        else:
            wifi_password = ''
        time_generated = datetime.now().timestamp()
        # TLS Fingerprint
        tls_fingerprint = self.tls_fingerprint['tls_fingerprint']
        # Library variable initialization
        library_variable_initialization_codes = []
        # Library initialization
        library_initialization_commands = []
        # Variable initializations for json payload data
        sensor_configuration_datas = []
        # List for digital pin that used as ground pin
        grounded_digital_pin_list = []
        # Data sending interval
        sending_interval = self.device['device_data_sending_interval'] * 1000 * 60

        for sensor_configuration in self.sensor_configurations:
            library_variable_initialization_codes.append(sensor_configuration['library_variable_initialization_code'])
            library_initialization_commands.append(sensor_configuration['library_initialization_commands'])
            for sensor_configuration_data in sensor_configuration['sensor_configuration_datas']:
                sensor_configuration_datas.append(sensor_configuration_data)
            for grounded_digital_pin in sensor_configuration['grounded_digital_pins']:
                grounded_digital_pin_list.append(grounded_digital_pin)

        return latest_gampang_template.render(ssid=ssid,
                                              wifi_password=wifi_password,
                                              time_generated=time_generated,
                                              write_key=write_key,
                                              tls_fingerprint=tls_fingerprint,
                                              added_library =self.gutils.list_to_delimited_string(self.library_dependencies),
                                              library_variable_initialization=self.gutils.list_to_delimited_string(library_variable_initialization_codes),
                                              library_initialization_commands=self.gutils.list_to_delimited_string(library_initialization_commands),
                                              user_sensor_configuration=self.gutils.list_to_delimited_string(sensor_configuration_datas),
                                              grounded_digital_pins=self.gutils.list_to_delimited_string(grounded_digital_pin_list),
                                              sending_interval=sending_interval
                                             )
Exemplo n.º 13
0
def update_supported_board(request, user):

    # Gudang Classes
    rg = ResponseGenerator()
    db = GudangMongoDB()

    try:
        # Verify JSON structure
        j = json.loads(request.body.decode('utf-8'))

    except TypeError:
        response_data = rg.error_response_generator(
            400, "One of the request inputs is not valid")
        return HttpResponse(json.dumps(response_data),
                            content_type="application/json",
                            status=400)
    except ValueError:
        response_data = rg.error_response_generator(400, "Malformed JSON")
        return HttpResponse(json.dumps(response_data),
                            content_type="application/json",
                            status=400)
    else:

        # Verify the data format for added board
        try:
            updated_board = UpdateSupportedBoardResource(**j)
        except TypeError:
            response_data = rg.error_response_generator(
                400, "One of the board data structure is not valid")
            return HttpResponse(json.dumps(response_data),
                                content_type="application/json",
                                status=400)
        except ValueError:
            response_data = rg.error_response_generator(400, "Malformed JSON")
            return HttpResponse(json.dumps(response_data),
                                content_type="application/json",
                                status=400)
        else:
            # Make sure the board exist
            board = db.get_supported_board_by_uuid(
                board_uuid=updated_board.board_uuid)
            if (board):
                # Verify the sensor pin configuration
                for board_pin in updated_board.board_pins:
                    try:
                        pin = NewSupportedBoardPinResource(**board_pin)
                    except TypeError:
                        response_data = rg.error_response_generator(
                            400,
                            "One of the board pin data structure is not valid")
                        return HttpResponse(json.dumps(response_data),
                                            content_type="application/json",
                                            status=400)
                    except ValueError:
                        response_data = rg.error_response_generator(
                            400, "Malformed JSON")
                        return HttpResponse(json.dumps(response_data),
                                            content_type="application/json",
                                            status=400)

                # All data successfully verified in this step
                # Put new board in db
                db.update_supported_board(
                    board_uuid=updated_board.board_uuid,
                    board_name=updated_board.board_name,
                    chip=updated_board.chip,
                    manufacturer=updated_board.manufacturer,
                    board_specification=updated_board.board_specification,
                    board_image=updated_board.board_image,
                    board_image_source=updated_board.board_image_source,
                    board_pins=updated_board.board_pins,
                    s3_path=updated_board.s3_path,
                    version=updated_board.version)

                response_data = rg.success_response_generator(
                    200, "Supported board configuration successfully updated")
                return HttpResponse(json.dumps(response_data),
                                    content_type="application/json",
                                    status=200)
            else:
                response_data = rg.error_response_generator(
                    400, "Invalid board UUID")
                return HttpResponse(json.dumps(response_data),
                                    content_type="application/json",
                                    status=400)
Exemplo n.º 14
0
def update_user_sensor_detail(request, user):

    # Gudang class
    rg = ResponseGenerator()
    db = GudangMongoDB()
    gutils = GudangUtils()

    form = UpdateUserSensorDetailForm(request.POST)
    if form.is_valid():
        # Normalize the threshold_direction, threshold_enabled, and new_threshold
        threshold_enabled = True
        # 1 (Positive) As the default direction if the threshold is disabled
        threshold_direction = "1"
        # 0 For default value if the threshold is disabled
        if form.cleaned_data['threshold_enabled'] == "0":
            form.cleaned_data['new_threshold'] = 0
            threshold_enabled = False

        if gutils.float_check(form.cleaned_data['new_threshold']):
            if form.cleaned_data['threshold_enabled'] == "1":
                # Put the real threshold direction if the threshold is enabled
                threshold_direction = form.cleaned_data['threshold_direction']

            user_sensor = db.get_user_sensor_by_uuid(
                user_sensor_uuid=form.cleaned_data['user_sensor_uuid'])
            if user_sensor != None:
                if user_sensor['user_uuid'] == user['user_uuid']:
                    try:
                        db.update_user_sensor_detail(
                            object_id=user_sensor['_id'],
                            new_threshold_value=float(
                                form.cleaned_data['new_threshold']),
                            new_user_sensor_name=form.
                            cleaned_data['new_user_sensor_name'],
                            threshold_direction=threshold_direction,
                            threshold_enabled=threshold_enabled)
                    except:
                        response_data = rg.error_response_generator(
                            500, "Internal server error")
                        return HttpResponse(json.dumps(response_data),
                                            content_type="application/json",
                                            status=500)
                    else:
                        response_data = rg.success_response_generator(
                            200, "Sensor detail successfully updated")
                        return HttpResponse(json.dumps(response_data),
                                            content_type="application/json",
                                            status=200)
                else:
                    # Obfuscate the error for accessing unowned sensor
                    response_data = rg.error_response_generator(
                        400, 'Invalid user sensor uuid')
                    return HttpResponse(json.dumps(response_data),
                                        content_type='application/json',
                                        status=400)
            else:
                response_data = rg.error_response_generator(
                    400, 'Invalid user sensor uuid')
                return HttpResponse(json.dumps(response_data),
                                    content_type='application/json',
                                    status=400)
        else:
            response_data = rg.error_response_generator(
                400, 'Invalid threshold value')
            return HttpResponse(json.dumps(response_data),
                                content_type='application/json',
                                status=400)
    else:
        response_data = rg.error_response_generator(
            400, 'invalid or missing parameter submitted')
        return HttpResponse(json.dumps(response_data),
                            content_type='application/json',
                            status=400)
Exemplo n.º 15
0
    def __init__(self, device, wifi_connection, tls_fingerprint):
        self.s3 = GudangS3()
        self.db = GudangMongoDB()
        self.gutils = GudangUtils()
        self.device = device
        self.wifi_connection = wifi_connection
        self.tls_fingerprint = tls_fingerprint
        self.library_dependencies = []
        self.sensor_configurations = []
        # For differentiating between each sensor
        user_sensor_mapping_uuid_temp = []
        master_sensor_reference_uuid_temp = []

        for user_sensor_uuid in self.device['user_sensor_uuids']:
            # Todo : Find a better way to optimize the query
            user_sensor = self.db.get_user_sensor_by_uuid(user_sensor_uuid=user_sensor_uuid)
            user_sensor_mapping = self.db.get_sensor_mapping_by_uuid(user_sensor_mapping_uuid=user_sensor['user_sensor_mapping_uuid'])
            master_sensor = self.db.get_master_sensor_by_uuid(master_sensor_uuid=user_sensor['master_sensor_uuid'])
            master_sensor_reference = self.db.get_master_sensor_reference_by_uuid(master_sensor_reference_uuid=master_sensor['master_sensor_reference_uuid'])
            # Added library
            # Iterate through library dependencies inside master sensor referece
            for library_dependency in master_sensor_reference['library_dependencies']:
                if library_dependency not in self.library_dependencies:
                    # only add it it if it's haven't been added earlier
                    self.library_dependencies.append(library_dependency)

            # Mark sensor mapping and master sensor reference
            if user_sensor_mapping['user_sensor_mapping_uuid'] not in user_sensor_mapping_uuid_temp:
                user_sensor_mapping_uuid_temp.append(user_sensor_mapping['user_sensor_mapping_uuid'])
                master_sensor_reference_uuid_temp.append(master_sensor_reference['master_sensor_reference_uuid'])

        # Library variable initialization
        for mapping_index in range(0,len(user_sensor_mapping_uuid_temp)):
            master_sensor_reference = self.db.get_master_sensor_reference_by_uuid(master_sensor_reference_uuid=master_sensor_reference_uuid_temp[mapping_index])
            user_sensor_mapping = self.db.get_sensor_mapping_by_uuid(user_sensor_mapping_uuid=user_sensor_mapping_uuid_temp[mapping_index])
            # Retrieve the user sensor back
            user_sensors = self.db.get_user_sensor_by_mapping_uuid(user_sensor_mapping_uuid=user_sensor_mapping_uuid_temp[mapping_index])
            # Random varname for each sensor
            sensor_varname = self.gutils.generate_random_id(8)
            # List for sensor code formatting
            code_filler_list = []
            # List for sensor configuration for each physical sensor
            sensor_json_configuration_format_list = []
            # List for digital pin that used as ground pin
            grounded_digital_pin_list = []

            # For digital pin that used as ground pin
            for sensor_pin_mapping in user_sensor_mapping['sensor_pin_mappings']:
                if (sensor_pin_mapping['function'] == 'GROUND') and (sensor_pin_mapping['device_pin'] != 'GND'):
                    grounded_digital_pin_list.append('pinMode({}, OUTPUT);\ndigitalWrite({}, LOW);'.format(sensor_pin_mapping['device_arduino_pin'], sensor_pin_mapping['device_arduino_pin']))

            for code_filler in master_sensor_reference['library_variable_initialization']['code_filler']:
                # Generate the variable name
                if code_filler == 'VARNAME':
                    code_filler_list.append(sensor_varname)
                else:
                    for sensor_pin_mapping in user_sensor_mapping['sensor_pin_mappings']:
                        if sensor_pin_mapping['function'] == code_filler:
                            code_filler_list.append(sensor_pin_mapping['device_arduino_pin'])

            # Iterate through each sensor value for each physical sensor
            for sensor in user_sensors:
                sensor_value_varname = self.gutils.generate_random_id(8)
                master_sensor = self.db.get_master_sensor_by_uuid(master_sensor_uuid=sensor['master_sensor_uuid'])
                # Generate the json configuration for each sensor value
                sensor_json_configuration_format_list.append('\t\tJsonObject& {} = sensor_datas.createNestedObject();\n\t\t{}["user_sensor_uuid"] = "{}";\n\t\t{}["user_sensor_value"] = {}.{}'.format(sensor_value_varname, sensor_value_varname, sensor['user_sensor_uuid'], sensor_value_varname, sensor_varname, master_sensor['master_sensor_library_function']))

            # Configuration for each physical sensor
            sensor_configuration = {
                'sensor_var_name': sensor_varname,
                'library_variable_initialization_code' : master_sensor_reference['library_variable_initialization']['code'].format(*code_filler_list),
                'library_initialization_commands':  master_sensor_reference['library_initialization_command'].format(sensor_varname),
                'sensor_configuration_datas': sensor_json_configuration_format_list,
                'grounded_digital_pins': grounded_digital_pin_list
            }
            self.sensor_configurations.append(sensor_configuration)
Exemplo n.º 16
0
    def check_sensor_threshold(self, user_sensor_uuid, sensor_value, device_data):
        db = GudangMongoDB()
        try:
            user_sensor = db.get_user_sensor_by_uuid(user_sensor_uuid=user_sensor_uuid)
            master_sensor = db.get_master_sensor_by_uuid(master_sensor_uuid=user_sensor['master_sensor_uuid'])
        except:
            # For unknown error
            return False
        else:
            # Only Execute when the threshold is set
            smodule = GudangSidikModule()
            if user_sensor['threshold_enabled'] :
                if user_sensor['threshold_direction'] == "1" :
                    # Todo : Make a logger for the value
                    # Compare the value to the threshold
                    if sensor_value > user_sensor['sensor_threshold']:
                        # Check the current status
                        if user_sensor['currently_over_threshold']:
                            # Log the status
                            return True
                        else:
                            # Log the status, send the notification, and modify currently_above_threshold
                            # When the value is over threshold
                            try:
                                db.update_currently_over_threshold(object_id=user_sensor['_id'], new_status=True)
                            except:
                                # For unknown error
                                return False
                            else:
                                # Get user detail (to get the email address)
                                user = smodule.get_email_address(user_uuid=user_sensor['user_uuid'])
                                # Get the master sensor (For unit & symbol)
                                master_sensor = db.get_master_sensor_by_uuid(master_sensor_uuid=user_sensor['master_sensor_uuid'])
                                if user.status_code == 200:
                                    # Prepare the request data
                                    user_email = user.json()['data']['email']
                                    device_name = device_data['device_name']
                                    user_sensor_name = user_sensor['user_sensor_name']
                                    threshold_value = user_sensor['sensor_threshold']
                                    latest_value = sensor_value
                                    time_reached = datetime.now().timestamp()
                                    threshold_direction = user_sensor['threshold_direction']
                                    unit_symbol = master_sensor['master_sensor_default_unit_symbol']
                                    notification_type = "0"
                                    # Required parameter for logger
                                    user_uuid = user.json()['data']['user_uuid']
                                    user_sensor_uuid = user_sensor['user_sensor_uuid']
                                    device_uuid = device_data['device_uuid']

                                    # Send using different lambda execution env.
                                    send_device_notification_email_worker(user_uuid=user_uuid, user_sensor_uuid=user_sensor_uuid, device_uuid=device_uuid, email=user_email, device_name=device_name,
                                                                                 user_sensor_name=user_sensor_name, threshold_value=threshold_value, latest_value=latest_value,
                                                                                 time_reached=time_reached, threshold_direction=threshold_direction, unit_symbol=unit_symbol,
                                                                                 notification_type=notification_type)
                                    # Send using different lambda execution env.
                                    send_device_android_notification_worker(user_uuid=user_uuid, device_uuid=device_uuid, user_sensor_name=user_sensor_name, device_name=device_name,
                                                                                   user_sensor_uuid=user_sensor_uuid, status='1', time_reached=time_reached)


                                    return True

                                else:
                                    return False
                    else:
                        # Check the current status
                        # When the value is return back to normal
                        if user_sensor['currently_over_threshold']:
                            # Log the status, send the notification, and modify currently_above_threshold
                            try:
                                db.update_currently_over_threshold(object_id=user_sensor['_id'], new_status=False)
                            except:
                                # For unknown error
                                return False
                            else:
                                # Get user detail (to get the email address)
                                user = smodule.get_email_address(user_uuid=user_sensor['user_uuid'])
                                # Get the master sensor (For unit & symbol)
                                master_sensor = db.get_master_sensor_by_uuid(
                                    master_sensor_uuid=user_sensor['master_sensor_uuid'])
                                if user.status_code == 200:
                                    # Prepare the request data
                                    user_email = user.json()['data']['email']
                                    device_name = device_data['device_name']
                                    user_sensor_name = user_sensor['user_sensor_name']
                                    threshold_value = user_sensor['sensor_threshold']
                                    latest_value = sensor_value
                                    time_reached = datetime.now().timestamp()
                                    threshold_direction = user_sensor['threshold_direction']
                                    unit_symbol = master_sensor['master_sensor_default_unit_symbol']
                                    notification_type = "1"

                                    # Required parameter for logger
                                    user_uuid = user.json()['data']['user_uuid']
                                    user_sensor_uuid = user_sensor['user_sensor_uuid']
                                    device_uuid = device_data['device_uuid']

                                    # Send using different lambda execution env.
                                    send_device_notification_email_worker(user_uuid=user_uuid,
                                                                          user_sensor_uuid=user_sensor_uuid,
                                                                          device_uuid=device_uuid, email=user_email,
                                                                          device_name=device_name,
                                                                          user_sensor_name=user_sensor_name,
                                                                          threshold_value=threshold_value,
                                                                          latest_value=latest_value,
                                                                          time_reached=time_reached,
                                                                          threshold_direction=threshold_direction,
                                                                          unit_symbol=unit_symbol,
                                                                          notification_type=notification_type)

                                    # Send using different lambda execution env.
                                    send_device_android_notification_worker(user_uuid=user_uuid,
                                                                                   device_uuid=device_uuid,
                                                                                   user_sensor_name=user_sensor_name,
                                                                                   device_name=device_name,
                                                                                   user_sensor_uuid=user_sensor_uuid,
                                                                                   status='0',
                                                                                   time_reached=time_reached)

                                    return True


                                else:
                                    return False
                        else:
                            # Status Wont be logged
                            return True
                elif user_sensor['threshold_direction'] == "-1":
                    # Todo : Make a logger for the value
                    # Compare the value to the threshold
                    if sensor_value < user_sensor['sensor_threshold']:
                        # Check the current status
                        if user_sensor['currently_over_threshold']:
                            # Log the status
                            return True
                        else:
                            # When the value is over the threshold
                            # Log the status, send the notification, and modify currently_above_threshold
                            try:
                                db.update_currently_over_threshold(object_id=user_sensor['_id'], new_status=True)
                            except:
                                # For unknown error
                                return False
                            else:
                                # Get user detail (to get the email address)
                                user = smodule.get_email_address(user_uuid=user_sensor['user_uuid'])
                                # Get the master sensor (For unit & symbol)
                                master_sensor = db.get_master_sensor_by_uuid(
                                    master_sensor_uuid=user_sensor['master_sensor_uuid'])
                                if user.status_code == 200:
                                    # Prepare the request data
                                    user_email = user.json()['data']['email']
                                    device_name = device_data['device_name']
                                    user_sensor_name = user_sensor['user_sensor_name']
                                    threshold_value = user_sensor['sensor_threshold']
                                    latest_value = sensor_value
                                    time_reached = datetime.now().timestamp()
                                    threshold_direction = user_sensor['threshold_direction']
                                    unit_symbol = master_sensor['master_sensor_default_unit_symbol']
                                    notification_type = "0"

                                    # Required parameter for logger
                                    user_uuid = user.json()['data']['user_uuid']
                                    user_sensor_uuid = user_sensor['user_sensor_uuid']
                                    device_uuid = device_data['device_uuid']

                                    # Send using different lambda execution env.
                                    send_device_notification_email_worker(user_uuid=user_uuid,
                                                                          user_sensor_uuid=user_sensor_uuid,
                                                                          device_uuid=device_uuid, email=user_email,
                                                                          device_name=device_name,
                                                                          user_sensor_name=user_sensor_name,
                                                                          threshold_value=threshold_value,
                                                                          latest_value=latest_value,
                                                                          time_reached=time_reached,
                                                                          threshold_direction=threshold_direction,
                                                                          unit_symbol=unit_symbol,
                                                                          notification_type=notification_type)

                                    # Send using different lambda execution env.
                                    send_device_android_notification_worker(user_uuid=user_uuid,
                                                                                   device_uuid=device_uuid,
                                                                                   user_sensor_name=user_sensor_name,
                                                                                   device_name=device_name,
                                                                                   user_sensor_uuid=user_sensor_uuid,
                                                                                   status='1',
                                                                                   time_reached=time_reached)

                                    return True

                                else:
                                    return False
                    else:
                        # Check the current status
                        if user_sensor['currently_over_threshold']:
                            # Log the status, send the notification, and modify currently_above_threshold
                            try:
                                db.update_currently_over_threshold(object_id=user_sensor['_id'], new_status=False)
                            except:
                                # For unknown error
                                return False
                            else:
                                # Get user detail (to get the email address)
                                user = smodule.get_email_address(user_uuid=user_sensor['user_uuid'])
                                # Get the master sensor (For unit & symbol)
                                master_sensor = db.get_master_sensor_by_uuid(
                                    master_sensor_uuid=user_sensor['master_sensor_uuid'])
                                if user.status_code == 200:
                                    # Prepare the request data
                                    user_email = user.json()['data']['email']
                                    device_name = device_data['device_name']
                                    user_sensor_name = user_sensor['user_sensor_name']
                                    threshold_value = user_sensor['sensor_threshold']
                                    latest_value = sensor_value
                                    time_reached = datetime.now().timestamp()
                                    threshold_direction = user_sensor['threshold_direction']
                                    unit_symbol = master_sensor['master_sensor_default_unit_symbol']
                                    notification_type = "1"

                                    # Required parameter for logger
                                    user_uuid = user.json()['data']['user_uuid']
                                    user_sensor_uuid = user_sensor['user_sensor_uuid']
                                    device_uuid = device_data['device_uuid']

                                    # Send using different lambda execution env.
                                    send_device_notification_email_worker(user_uuid=user_uuid,
                                                                          user_sensor_uuid=user_sensor_uuid,
                                                                          device_uuid=device_uuid, email=user_email,
                                                                          device_name=device_name,
                                                                          user_sensor_name=user_sensor_name,
                                                                          threshold_value=threshold_value,
                                                                          latest_value=latest_value,
                                                                          time_reached=time_reached,
                                                                          threshold_direction=threshold_direction,
                                                                          unit_symbol=unit_symbol,
                                                                          notification_type=notification_type)

                                    # Send using different lambda execution env.
                                    send_device_android_notification_worker(user_uuid=user_uuid,
                                                                                   device_uuid=device_uuid,
                                                                                   user_sensor_name=user_sensor_name,
                                                                                   device_name=device_name,
                                                                                   user_sensor_uuid=user_sensor_uuid,
                                                                                   status='0',
                                                                                   time_reached=time_reached)

                                    return True


                                else:
                                    return False
                        else:
                            # Status Wont be logged
                            return True
                else:
                    return False
            else:
                # If threshold is disabled
                return True
Exemplo n.º 17
0
def update_supported_sensor(request, user):
    # Gudang Classes
    rg = ResponseGenerator()
    db = GudangMongoDB()

    try:
        # Verify JSON structure
        j = json.loads(request.body.decode('utf-8'))

    except TypeError:
        response_data = rg.error_response_generator(
            400, "One of the request inputs is not valid")
        return HttpResponse(json.dumps(response_data),
                            content_type="application/json",
                            status=400)
    except ValueError:
        response_data = rg.error_response_generator(400, "Malformed JSON")
        return HttpResponse(json.dumps(response_data),
                            content_type="application/json",
                            status=400)
    else:
        # Verify the data format for updated sensor
        try:
            updated_sensor = UpdateSupportedSensorResource(**j)
        except TypeError:
            response_data = rg.error_response_generator(
                400, "One of the sensor data structure is not valid")
            return HttpResponse(json.dumps(response_data),
                                content_type="application/json",
                                status=400)
        except ValueError:
            response_data = rg.error_response_generator(400, "Malformed JSON")
            return HttpResponse(json.dumps(response_data),
                                content_type="application/json",
                                status=400)
        else:
            # Check for library variable initialization
            try:
                lib = LibraryVariableInitializationResource(
                    **updated_sensor.library_variable_initialization)
            except TypeError:
                response_data = rg.error_response_generator(
                    400, "One of the sensor library structure is not valid")
                return HttpResponse(json.dumps(response_data),
                                    content_type="application/json",
                                    status=400)
            except ValueError:
                response_data = rg.error_response_generator(
                    400, "Malformed JSON")
                return HttpResponse(json.dumps(response_data),
                                    content_type="application/json",
                                    status=400)
            else:
                # Check for sensor pin mapping
                for sensor_pin_mapping in updated_sensor.sensor_pin_mappings:
                    try:
                        sensor_mapping = NewSupportedSensorMappingResource(
                            **sensor_pin_mapping)
                    except TypeError:
                        response_data = rg.error_response_generator(
                            400,
                            "One of the sensor pin structure is not valid")
                        return HttpResponse(json.dumps(response_data),
                                            content_type="application/json",
                                            status=400)
                    except ValueError:
                        response_data = rg.error_response_generator(
                            400, "Malformed JSON")
                        return HttpResponse(json.dumps(response_data),
                                            content_type="application/json",
                                            status=400)

                # Check for master sensors
                for master_sensor in updated_sensor.master_sensors:
                    try:
                        sensor = UpdateMasterSensorResource(**master_sensor)
                    except TypeError:
                        response_data = rg.error_response_generator(
                            400,
                            "One of the master sensor data structure is not valid"
                        )
                        return HttpResponse(json.dumps(response_data),
                                            content_type="application/json",
                                            status=400)
                    except ValueError:
                        response_data = rg.error_response_generator(
                            400, "Malformed JSON")
                        return HttpResponse(json.dumps(response_data),
                                            content_type="application/json",
                                            status=400)

                # Check for master sensor configuration
                master_sensor_reference = db.get_master_sensor_reference_by_uuid(
                    master_sensor_reference_uuid=updated_sensor.
                    master_sensor_reference_uuid)
                if (master_sensor_reference):
                    # Keep the uuids
                    master_sensor_uuids = []
                    for master_sensor in updated_sensor.master_sensors:
                        master_sensor_uuids.append(
                            master_sensor['master_sensor_uuid'])

                    # Sort all the uuid list
                    master_sensor_uuids.sort()
                    master_sensor_reference['master_sensor_uuids'].sort()

                    # Compare the uuids
                    if master_sensor_uuids == master_sensor_reference[
                            'master_sensor_uuids']:
                        # Update data on the database
                        db.update_supported_sensor(
                            master_sensor_reference_uuid=updated_sensor.
                            master_sensor_reference_uuid,
                            library_dependencies=updated_sensor.
                            library_dependencies,
                            library_variable_initialization=updated_sensor.
                            library_variable_initialization,
                            library_initialization_command=updated_sensor.
                            library_initialization_command,
                            master_sensors=updated_sensor.master_sensors,
                            sensor_image_source=updated_sensor.
                            sensor_image_source,
                            sensor_image_url=updated_sensor.sensor_image_url,
                            sensor_model=updated_sensor.sensor_model,
                            sensor_pin_mappings=updated_sensor.
                            sensor_pin_mappings)

                        response_data = rg.success_response_generator(
                            200,
                            "Supported sensor configuration successfully updated"
                        )
                        return HttpResponse(json.dumps(response_data),
                                            content_type="application/json",
                                            status=200)

                    else:
                        response_data = rg.error_response_generator(
                            400, "Invalid sensor configuration")
                        return HttpResponse(json.dumps(response_data),
                                            content_type="application/json",
                                            status=400)
                else:
                    response_data = rg.error_response_generator(
                        400, "Invalid master sensor reference UUID")
                    return HttpResponse(json.dumps(response_data),
                                        content_type="application/json",
                                        status=400)
Exemplo n.º 18
0
def buffered_xlsxwriter(user_uuid, device_uuid, from_time, to_time, time_zone,
                        user_exported_xlsx_uuid):
    db = GudangMongoDB()
    gutils = GudangUtils()
    gs3 = GudangS3()
    # Prepare the stream
    out = BytesIO()
    workbook = xlsxwriter.Workbook(out)
    # Worksheets for this current device, consists of multiple sheets for each sensor
    worksheets = {}
    user_device = db.get_device_data_by_uuid(user_uuid=user_uuid,
                                             device_uuid=device_uuid)
    # Iterate through the sensor
    for index, user_sensor_uuid in enumerate(user_device['user_sensor_uuids']):
        # Start time
        start_time = timeit.default_timer()
        # Get user sensor data
        sensor = db.get_user_sensor_by_uuid(user_sensor_uuid=user_sensor_uuid)
        master_sensor = db.get_master_sensor_by_uuid(
            master_sensor_uuid=sensor['master_sensor_uuid'])
        master_sensor_reference = db.get_master_sensor_reference_by_uuid(
            master_sensor_reference_uuid=master_sensor[
                'master_sensor_reference_uuid'])
        # Add the worksheet
        worksheets[user_sensor_uuid] = workbook.add_worksheet(
            'Sensor {} data'.format(index + 1))
        # Widen the A and B and C column
        worksheets[user_sensor_uuid].set_column('A:A', 10)
        worksheets[user_sensor_uuid].set_column('B:B', 40)
        worksheets[user_sensor_uuid].set_column('C:C', 20)
        worksheets[user_sensor_uuid].set_column('D:D', 20)
        worksheets[user_sensor_uuid].set_column('E:E', 40)

        # Add rumahiot logo
        worksheets[user_sensor_uuid].insert_image(
            'A1',
            'rumahiot_gudang/apps/store/xlsxwriter_data/rumahiot-logo.png', {
                'x_scale': 0.49999999,
                'y_scale': 0.49999999,
                'y_offset': 30,
                'x_offset': 150
            })
        # Logo merge format
        logo_merge_format = workbook.add_format({
            'border': 1,
            'align': 'center',
            'valign': 'vcenter',
            'bold': 1,
        })
        center_text_format = workbook.add_format({
            'align': 'center',
            'border': 1,
        })
        left_text_format = workbook.add_format({
            'align': 'left',
            'border': 1,
        })
        # Merge 'Sensor Data' Cell
        worksheets[user_sensor_uuid].merge_range('A10:C10', 'Device Data',
                                                 logo_merge_format)
        # Bold format
        bold = workbook.add_format({'bold': True})
        # Merge the logo cell
        worksheets[user_sensor_uuid].merge_range('A1:C9', '',
                                                 logo_merge_format)

        # Date format
        date_format = "%d-%m-%Y %H:%M:%S %Z%z"

        # Write file information
        worksheets[user_sensor_uuid].write('D1', 'Device Name', bold)
        worksheets[user_sensor_uuid].write('D2', 'Time to Generate', bold)
        worksheets[user_sensor_uuid].write('D3', 'Sensor Model', bold)
        worksheets[user_sensor_uuid].write('D4', 'Sensor Name', bold)
        worksheets[user_sensor_uuid].write('D5', 'Value Type', bold)
        worksheets[user_sensor_uuid].write('D6', 'From', bold)
        worksheets[user_sensor_uuid].write('D7', 'To', bold)
        worksheets[user_sensor_uuid].write('D8', 'Timezone', bold)
        worksheets[user_sensor_uuid].write('D9', 'Generated At', bold)

        worksheets[user_sensor_uuid].write('E1', user_device['device_name'])
        # Add time to generate later
        worksheets[user_sensor_uuid].write(
            'E3', master_sensor_reference['sensor_model'])
        worksheets[user_sensor_uuid].write('E4', sensor['user_sensor_name'])
        worksheets[user_sensor_uuid].write(
            'E5', '{}, {}({})'.format(
                master_sensor['master_sensor_name'],
                master_sensor['master_sensor_default_unit_name'],
                master_sensor['master_sensor_default_unit_symbol']))
        worksheets[user_sensor_uuid].write(
            'E6',
            gutils.datetime_timezone_converter(
                datetime.datetime.fromtimestamp(from_time),
                time_zone).strftime(date_format))
        worksheets[user_sensor_uuid].write(
            'E7',
            gutils.datetime_timezone_converter(
                datetime.datetime.fromtimestamp(to_time),
                time_zone).strftime(date_format))
        worksheets[user_sensor_uuid].write('E8', time_zone)
        worksheets[user_sensor_uuid].write(
            'E9',
            gutils.datetime_timezone_converter(
                datetime.datetime.now(), time_zone).strftime(date_format))
        worksheets[user_sensor_uuid].write('A11', 'No.', center_text_format)
        worksheets[user_sensor_uuid].write('B11', 'Time', center_text_format)
        worksheets[user_sensor_uuid].write(
            'C11', 'Sensor Value {}({})'.format(
                master_sensor['master_sensor_default_unit_name'],
                master_sensor['master_sensor_default_unit_symbol']),
            center_text_format)

        # Get the sensor data
        sensor_datas = db.get_device_sensor_data_interval(
            device_uuid=user_device['device_uuid'],
            from_time=from_time,
            to_time=to_time,
            user_sensor_uuid=user_sensor_uuid)

        # Iterate through the data
        row_index = 11
        column_index = 0
        for index, sensor_data in enumerate(sensor_datas):
            worksheets[user_sensor_uuid].write(row_index, column_index,
                                               index + 1, left_text_format)
            worksheets[user_sensor_uuid].write(
                row_index, column_index + 1,
                gutils.datetime_timezone_converter(
                    datetime.datetime.fromtimestamp(sensor_data['time_added']),
                    time_zone).strftime(date_format), left_text_format)
            worksheets[user_sensor_uuid].write(
                row_index, column_index + 2,
                '{}'.format(sensor_data['sensor_datas']['user_sensor_value']),
                center_text_format)
            row_index += 1

        finish_time = timeit.default_timer() - start_time
        # Write time to generate
        worksheets[user_sensor_uuid].write('E2',
                                           '{} seconds'.format(finish_time))

    # Close the workbook
    workbook.close()
    # Start the stream from 0
    out.seek(0)
    # put the document into s3
    target_file = 'docs/xlsx/{}/{}.xlsx'.format(user_uuid, uuid4().hex)
    gs3.put_object(target_bucket=RUMAHIOT_UPLOAD_BUCKET,
                   target_file=target_file,
                   object_body=out.read())
    # Close the stream
    out.close()
    # Update db after document is ready
    db.update_user_exported_xlsx(
        user_exported_xlsx_uuid=user_exported_xlsx_uuid,
        document_link=RUMAHIOT_UPLOAD_ROOT + target_file)