Exemple #1
0
def update_status(request, dev_id):
    """
    Update device status and return device status to the
    device management table.
    :param request:
    :param dev_id:
    :return:
    """
    if request.method == 'GET':
        latest_data = get_latest_data(dev_id)

        if latest_data:
            print("Latest data: ", latest_data)
            device = Device.objects(device_id=dev_id).first()

            # Get time difference
            time_diff = datetime.datetime.now() - latest_data.timestamp
            print("Time difference: ", time_diff.days)

            if time_diff.days >= 1:
                # Time difference more than 1 day
                # Set status to offline
                device.status = "offline"
            else:
                # Time difference less than 1 day
                # Set status to online
                device.status = "online"

            device.save()

            return HttpResponse(device.status)
        else:
            return HttpResponse("Fail")

    return HttpResponseRedirect(reverse('dashboard:devices_management'))
Exemple #2
0
def device_dashboard(request, dev_id):
    """
    Display each device dashboard page.
    All charts for individual device will be shown.
    :param request: request object
    :param dev_id: device id
    :return:
    """
    # Get device object with device id = dev_id to ensure the
    # device id is valid
    current_device = Device.objects(device_id=dev_id)
    if not current_device:
        # if device_id not found, raise Http404
        raise Http404("Device ID \"" + dev_id + "\" does not exist")
    else:
        device_data = Devices.objects(device_id=dev_id).first()
        data_keys = {}
        if device_data:
            data_keys = device_data.data.keys()
            print("Data keys: ", data_keys)

        # if device_id is found, render the page
        return render(request, 'dashboard/device_dashboard.html', {
            'device_id': dev_id,
            'data_keys': list(data_keys)
        })
Exemple #3
0
def chart_detail(request, dev_id, which_data):
    """
    Display individual chart of a device_id with
    chart configuration/settings for personalization

    Param:
    :param request: request object
    :param dev_id: device id
    :param which_data: data field of a device
    :return:
    """
    device = Device.objects(device_id=dev_id).first()

    # Set default chart configuration
    dev_config = get_chart_config(device, which_data)

    if not device:
        # if device_id not found, raise Http404
        raise Http404("Device ID \"" + dev_id + "\" does not exist")
    elif not is_which_data_valid(dev_id, which_data):
        raise Http404("URL \"" + request.path + "\" does not exist")
    else:
        # if device_id is found, render the page
        return render(
            request, 'dashboard/chart_detail.html', {
                'dev_config': dev_config,
                'device_id': dev_id,
                'whichData': which_data,
                'colorList': colorList,
                'chartTypeList': chartTypeList,
                'timelineList': timelineList,
            })
Exemple #4
0
def do_enroll(request, api_hostname):
    code = request.POST['code']
    if code != request.session['enroll_code']:
        return HttpResponse(json.dumps({"status": "denied"}))

    userName = request.session.get('sig_dict', None)['content'][0]
    parent = request.session.get('parent', None)
    account = Account.objects.get(api_hostname=api_hostname)
    phone = request.session['phone']
    #防止重复提交表单,捕获实体完整性错误
    try:
        user = User.objects.create(uKey=User.new_user_key()['uKey'],
                                   user_name=userName,
                                   user_phone=phone,
                                   account=account)
        device = Device.objects.create(user=user,
                                       account=account,
                                       **Device.new_device(api_hostname))
    except IntegrityError as e:
        user = User.objects.get(user_name=userName)
        device = user.device_set.all()[0]
    return HttpResponse(
        json.dumps({
            "status": "succeed",
            "identifer": device.identifer
        }))
Exemple #5
0
def add_device(request):
    """
    Add new device function
    It handles both GET and POST request
    :param request:
    :return:
    """
    if request.method == 'GET':
        # GET request
        # display the form
        return render(request, 'dashboard/add_device.html')

    elif request.method == 'POST':
        # POST request
        # process the form data

        hasError = False
        error_message = ""

        # Get the POST data and create a new device object
        newDevice = Device(device_id=request.POST['device_id'])
        newDevice.device_name = request.POST['device_name']
        latitude = request.POST['latitude']
        longitude = request.POST['longitude']

        if latitude and longitude:
            # Set gps_loc if latitude and longitude field is not empty
            newDevice.gps_loc = [float(latitude), float(longitude)]

        # Create a default chart configuration object
        chart_config = ChartConfig(show_in_main=False)
        newDevice.default_config = chart_config

        # Validation
        if newDevice.device_id == "":
            # If device ID field is empty
            hasError = True
            error_message = "Device ID cannot be empty."
        else:
            # Check if new device id and name exist in database
            isExist = Device.objects(device_id=newDevice.device_id)

            if isExist:
                hasError = True
                error_message = "This Device ID or Name has been used."

        if hasError:
            # If error occurs, return error message
            return render(request, 'dashboard/add_device.html',
                          {'error_message': error_message})
        else:
            # Save the newly created device object
            newDevice.save()

        # Redirect to device management page
        return HttpResponseRedirect(reverse('dashboard:devices_management'))
Exemple #6
0
def create_device(device_id, device_name, gps_loc):
    new_device = Device(
        device_id=device_id,
        device_name=device_name,
        gps_loc=gps_loc,
    )

    return new_device
Exemple #7
0
def save_chart_config(request, dev_id, which_data):
    """
    To save or update the preferences configured by user
    :param request:
    :param dev_id:
    :param which_data:
    :return:
    """
    if request.method == 'POST':
        # Get the device object
        device = Device.objects(device_id=dev_id).first()

        # Get POST data
        threshold = request.POST['threshold']
        color = request.POST['color']
        chart_type = request.POST['chart_type']
        timeline = request.POST['timeline']

        # Create a ChartConfig object
        chart_config = ChartConfig(
            threshold=threshold,
            color=color,
            chart_type=chart_type,
            timeline=timeline,
        )

        # Check if the chart config for which_data is exists
        isExist = False

        for i, item in enumerate(device.chart_config):
            field = ''.join(item.keys())  # Get dictionary key
            if which_data == field:
                # If exists, update the values
                isExist = True

                # Replace with new values
                device.chart_config[i][field].threshold = threshold
                device.chart_config[i][field].color = color
                device.chart_config[i][field].chart_type = chart_type
                device.chart_config[i][field].timeline = timeline

                break

        if not isExist:
            # If chart configuration of which_data does not exists,
            # Add the configuration of which_data (Eg: Temperature)
            device.chart_config.append({which_data: chart_config})

        # Save the document
        device.save()

        return HttpResponseRedirect(
            reverse('dashboard:chart_detail',
                    kwargs={
                        'dev_id': dev_id,
                        'which_data': which_data
                    }))
Exemple #8
0
def init_db():
    acc1 = Account.objects.create(account_email="*****@*****.**",account_name="chris_whu",account_phone="15927432501", \
    **Account.new_account_hostname())
    acc2 = Account.objects.create(account_email="*****@*****.**",account_name="xiong_whu",account_phone="13979233017", \
    **Account.new_account_hostname())

    app1 = Application.objects.create(name='chris_sdk1',account=acc1,**Application.new_app(acc1.api_hostname))
    app2 = Application.objects.create(name='chris_sdk2',account=acc1,**Application.new_app(acc1.api_hostname))
    app3 = Application.objects.create(name='xiong_sdk1',account=acc2,**Application.new_app(acc2.api_hostname))
    app4 = Application.objects.create(name='xiong_sdk2',account=acc2,**Application.new_app(acc2.api_hostname))

    user1 = User.objects.create(user_name="xrb",user_phone="15927432501",account=acc1)
    user2 = User.objects.create(user_name="xrb",user_phone="15927432501",account=acc2)
    user3 = User.objects.create(user_name="xrb_2",user_phone="15927432501",account=acc1)

    device_user1_1 = Device.objects.create(user=user1,account=acc1,**Device.new_device(acc1.api_hostname))
    device_user1_2 = Device.objects.create(user=user1,account=acc1,**Device.new_device(acc1.api_hostname))
    device_user2 = Device.objects.create(user=user2,account=acc2,**Device.new_device(acc2.api_hostname))
Exemple #9
0
def update_device(old_dev_id, new_dev_id, new_device_name, new_gps_loc):
    # Create an old device for query
    device_id = "dev-001"
    device_name = "device-001"
    gps_loc = [10.5, 30.8]

    old_device = create_device(device_id, device_name, gps_loc)
    old_device.save()

    # Update device
    Device.objects(device_id=old_dev_id).update_one(
        set__device_id=new_dev_id,
        set__device_name=new_device_name,
        set__gps_loc=new_gps_loc,
    )
    old_device.reload()

    return old_device
Exemple #10
0
def update_show_in_main(request, dev_id, which_data):
    """
    Update the value of checkbox of 'Show in Main Dashboard'
    Via Ajax post request without reloading the page.
    :param request:
    :param dev_id:
    :param which_data:
    :return:
    """
    if request.method == 'POST':
        # Get the device object
        device = Device.objects(device_id=dev_id).first()

        isExist = False

        newValue = request.POST['show_in_main']
        toShow = True if newValue == 'true' else False

        print('New value: ', newValue)
        for i, item in enumerate(device.chart_config):
            field = ''.join(item.keys())  # Get dictionary key
            if which_data == field and toShow:
                # If exists, update the values
                isExist = True
                device.chart_config[i][field]['show_in_main'] = True
                break
            elif which_data == field and not toShow:
                device.chart_config[i][field]['show_in_main'] = False
                break
            elif not isExist and i == len(device.chart_config) - 1:
                # Create a ChartConfig object
                chart_config = ChartConfig(
                    threshold=device.default_config.threshold,
                    color=device.default_config.color,
                    chart_type=device.default_config.chart_type,
                    timeline=device.default_config.timeline,
                    show_in_main=toShow,
                )

                device.chart_config.append({which_data: chart_config})

        device.save()

    return HttpResponseRedirect(
        reverse('dashboard:chart_detail',
                kwargs={
                    'dev_id': dev_id,
                    'which_data': which_data
                }))
Exemple #11
0
    def test_delete_device(self):
        device_id = "dev-001"
        device_name = "device-001"
        gps_loc = [10.5, 30.8]

        new_device = create_device(device_id, device_name, gps_loc)
        new_device.save()

        delete_device(device_id)

        # Query the deleted device
        device = Device.objects(device_id=device_id).first()

        # Assert device object is none
        self.assertIsNone(device)
Exemple #12
0
def delete_device(request, dev_id):
    """
    View function to delete device
    :param request:
    :param dev_id:
    :return:
    """
    device = Device.objects(device_id=dev_id)

    if device:
        device.delete()
    else:
        raise Http404("Device not found")

    return HttpResponseRedirect(reverse('dashboard:devices_management'))
Exemple #13
0
    def test_create_device(self):
        device_id = "dev-001"
        device_name = "device-001"
        gps_loc = [10.5, 30.8]

        new_device = create_device(device_id, device_name, gps_loc)

        expected = Device(
            device_id=device_id,
            device_name=device_name,
            gps_loc=gps_loc
        )

        self.assertEqual(expected.device_id, new_device.device_id)
        self.assertEqual(expected.device_name, new_device.device_name)
        self.assertEqual(expected.gps_loc, new_device.gps_loc)
def add_device():
    form = DeviceForm()
    if form.validate_on_submit():
        api_key = secrets.token_urlsafe(32)
        hashed_key = bcrypt.generate_password_hash(api_key)
        device = Device(name=form.name.data,
                        mac=form.mac.data,
                        data_measured=form.data_measured.data,
                        api_key=hashed_key,
                        dam_id=current_user.works_at.id)
        db.session.add(device)
        db.session.commit()

        flash(f"API Key: {api_key}, Device Id: {device.id}", 'flash_success')

    return render_template("device.html", form=form)
Exemple #15
0
    def test_update_device(self):
        new_device_id = "dev-002"
        new_device_name = "device-002"
        new_gps_loc = [5.5, 8.5]

        expected = Device(
            device_id=new_device_id,
            device_name=new_device_name,
            gps_loc=new_gps_loc
        )

        updated_device = update_device(
            "dev-001",
            new_device_id,
            new_device_name,
            new_gps_loc
        )

        self.assertEqual(updated_device.device_id, expected.device_id)
        self.assertEqual(updated_device.device_name, expected.device_name)
        self.assertEqual(updated_device.gps_loc, expected.gps_loc)

        # delete the record
        updated_device.delete()
Exemple #16
0
def device_registration(request):
    form_saved = False
    if request.method == 'POST':
        registration_form = DeviceRegistrationForm(data=request.POST,
                                                   files=request.FILES,
                                                   request=request)
        if registration_form.is_valid():
            #Save the data
            device = Device()
            device.imei = registration_form.cleaned_data.get('imei')
            device.name = registration_form.cleaned_data.get('name')
            device.device_type = 'normal'
            device.protocol = registration_form.cleaned_data.get('protocol')
            device.icon = registration_form.cleaned_data.get('icon')
            device.imsi = registration_form.cleaned_data.get('imsi')
            device.stock_st = registration_form.cleaned_data.get('stock_st')
            device.tank_sz = registration_form.cleaned_data.get('tank_sz')
            #Get FuelTankType Instance
            fuelTankType = FuelTankType.objects.get(
                pk=registration_form.cleaned_data.get('fuel_tank'))
            device.fuel_tank = fuelTankType
            device.max_speed = registration_form.cleaned_data.get('max_speed')
            device.max_temp = registration_form.cleaned_data.get('max_temp')
            device.lowest_fuel = registration_form.cleaned_data.get(
                'lowest_fuel')
            device.rc_number = registration_form.cleaned_data.get('rc_number')
            device.rc_date = registration_form.cleaned_data.get('rc_date')
            device.insurance_number = registration_form.cleaned_data.get(
                'insurance_number')
            device.insurance_company = registration_form.cleaned_data.get(
                'insurance_company')
            device.insurance_date = registration_form.cleaned_data.get(
                'insurance_date')
            device.insurance_due_date = registration_form.cleaned_data.get(
                'insurance_due_date')
            device.insurance_premium = registration_form.cleaned_data.get(
                'insurance_premium')
            device.servicing_due_date = registration_form.cleaned_data.get(
                'servicing_due_date')
            device.servicing_due_km = registration_form.cleaned_data.get(
                'servicing_due_km')
            device.odometer_reading = registration_form.cleaned_data.get(
                'odometer_reading')
            device.driver_dp = registration_form.cleaned_data.get('driver_dp')
            device.driver_name = registration_form.cleaned_data.get(
                'driver_name')
            device.driver_addr = registration_form.cleaned_data.get(
                'driver_addr')
            device.driver_contact_no = registration_form.cleaned_data.get(
                'driver_contact_no')
            device.license_no = registration_form.cleaned_data.get(
                'license_no')
            device.contract_company = registration_form.cleaned_data.get(
                'contract_company')
            device.contract_amt = registration_form.cleaned_data.get(
                'contract_amt')
            device.contract_renewal_dt = registration_form.cleaned_data.get(
                'contract_renewal_dt')
            device.contract_date = registration_form.cleaned_data.get(
                'contract_date')
            device.license_exp_date = registration_form.cleaned_data.get(
                'license_exp_date')
            device.subscription_amt = registration_form.cleaned_data.get(
                'subscription_amt')
            #Get Customer instance
            owner = Customer.objects.get(
                login_name=registration_form.cleaned_data.get('owner'))
            device.owner = owner
            device.save()
            form_saved = True
            registration_form = DeviceRegistrationForm(request=request)
        else:
            logger.error('Errors are' + str(registration_form.errors))
    else:
        registration_form = DeviceRegistrationForm(request=request)
    sc = helper.get_site_conf()
    customer = Customer.objects.get(login_name=request.session["ln"])
    customer_list = customer.get_descendants()
    return render_to_response('device-registration.html', {
        'sconf': sc,
        'customer': customer,
        'form': registration_form,
        'saved': form_saved,
    },
                              context_instance=RequestContext(request))
Exemple #17
0
def delete_device(device_id):
    device = Device.objects(device_id=device_id).first()
    device.delete()
Exemple #18
0
def device_registration(request):
    form_saved = False
    if request.method == 'POST':
        registration_form = DeviceRegistrationForm(data=request.POST, files=request.FILES, request=request)
        if registration_form.is_valid():
            #Save the data
            device = Device()
            device.imei = registration_form.cleaned_data.get('imei')
            device.name = registration_form.cleaned_data.get('name')
            device.device_type = 'normal'
            device.protocol = registration_form.cleaned_data.get('protocol')
            device.icon = registration_form.cleaned_data.get('icon')
            device.imsi = registration_form.cleaned_data.get('imsi')
            device.stock_st = registration_form.cleaned_data.get('stock_st')
            device.tank_sz = registration_form.cleaned_data.get('tank_sz')
            #Get FuelTankType Instance
            fuelTankType = FuelTankType.objects.get(pk=registration_form.cleaned_data.get('fuel_tank'))
            device.fuel_tank = fuelTankType 
            device.max_speed = registration_form.cleaned_data.get('max_speed')
            device.max_temp = registration_form.cleaned_data.get('max_temp')
            device.lowest_fuel = registration_form.cleaned_data.get('lowest_fuel')
            device.rc_number = registration_form.cleaned_data.get('rc_number')
            device.rc_date = registration_form.cleaned_data.get('rc_date')
            device.insurance_number = registration_form.cleaned_data.get('insurance_number')
            device.insurance_company = registration_form.cleaned_data.get('insurance_company')
            device.insurance_date = registration_form.cleaned_data.get('insurance_date')
            device.insurance_due_date = registration_form.cleaned_data.get('insurance_due_date')
            device.insurance_premium = registration_form.cleaned_data.get('insurance_premium')
            device.servicing_due_date = registration_form.cleaned_data.get('servicing_due_date')
            device.servicing_due_km = registration_form.cleaned_data.get('servicing_due_km')
            device.odometer_reading = registration_form.cleaned_data.get('odometer_reading')
            device.driver_dp = registration_form.cleaned_data.get('driver_dp')
            device.driver_name = registration_form.cleaned_data.get('driver_name')
            device.driver_addr = registration_form.cleaned_data.get('driver_addr')
            device.driver_contact_no = registration_form.cleaned_data.get('driver_contact_no')
            device.license_no = registration_form.cleaned_data.get('license_no')
            device.contract_company = registration_form.cleaned_data.get('contract_company')
            device.contract_amt = registration_form.cleaned_data.get('contract_amt')
            device.contract_renewal_dt = registration_form.cleaned_data.get('contract_renewal_dt')
            device.contract_date = registration_form.cleaned_data.get('contract_date')
            device.license_exp_date = registration_form.cleaned_data.get('license_exp_date')
            device.subscription_amt = registration_form.cleaned_data.get('subscription_amt')
            #Get Customer instance
            owner = Customer.objects.get(login_name=registration_form.cleaned_data.get('owner'))
            device.owner = owner
            device.save()
            form_saved = True
            registration_form = DeviceRegistrationForm(request=request)
        else:
            logger.error('Errors are' + str(registration_form.errors))
    else:
        registration_form = DeviceRegistrationForm(request=request) 
    sc = helper.get_site_conf()
    customer = Customer.objects.get(login_name=request.session["ln"])
    customer_list = customer.get_descendants()
    return render_to_response('device-registration.html',{'sconf': sc,
                                                    'customer': customer,
                                                    'form': registration_form,
                                                    'saved': form_saved,
                                                    },context_instance=RequestContext(request))
Exemple #19
0
def update_device(request, dev_id):
    """
    Update existing device function
    It handles both GET and POST request
    :param request:
    :param dev_id:
    :return:
    """
    # Query the device using device ID
    device = Device.objects(device_id=dev_id)[0]

    if device is None:
        # If the device ID not found, raise Http404
        raise Http404("Device ID \"" + dev_id + "\" does not exist")
    else:
        # If device ID exists, check if a GET/POST request
        if request.method == 'GET':
            # GET request
            # display the form
            return render(request, 'dashboard/update_device.html',
                          {'device': device})
        elif request.method == 'POST':
            # POST request
            # process the form data

            hasError = False
            error_message = ""

            # Get the POST data
            device_id = request.POST['device_id']
            device_name = request.POST['device_name']
            latitude = request.POST['latitude']
            longitude = request.POST['longitude']
            gps_loc = None

            if latitude and longitude:
                # Set gps_loc if latitude and longitude field is not empty
                gps_loc = [float(latitude), float(longitude)]

            # Validation
            if device_id == "":
                # If device ID field is empty
                hasError = True
                error_message = "Device ID cannot be empty."
            elif device_id != dev_id:
                # Check if changed device id and name exist in database
                isExist = Device.objects(device_id=device_id)

                if isExist:
                    hasError = True
                    error_message = "This Device ID or Name has been used."

            if hasError:
                # If error occurs, return error message
                return render(request, 'dashboard/update_device.html', {
                    'device': device,
                    'error_message': error_message
                })
            else:
                # Update document
                if device_id == dev_id:
                    Device.objects(device_id=dev_id).update_one(
                        set__device_name=device_name,
                        set__gps_loc=gps_loc,
                    )
                else:
                    Device.objects(device_id=dev_id).update_one(
                        set__device_id=device_id,
                        set__device_name=device_name,
                        set__gps_loc=gps_loc,
                    )

                device.reload()

            # Redirect to device management page
            return HttpResponseRedirect(
                reverse('dashboard:devices_management'))