Exemple #1
0
 def setUp(self):
     scheduler.start()
     self.app = create_app('testing')
     self.client = self.app.test_client
     self.devices = {'name': 'test'}
     with self.app.app_context():
         db.create_all()
         db.session.add(Device(name='Test Fan', device_id='L-20', device_type=DeviceType.FAN))
         db.session.add(Device(name='Test RF', device_id='101-1', device_type=DeviceType.RF))
         db.session.commit()
Exemple #2
0
def cpanel_open(request):
    user = request.user
    device_choices = Device.get_device_choices(Device())
    os_choices = Device.get_os_choices(Device())
    problem_choices = Report.get_problem_choices(Report())
    return render_to_response('cpanel/open.html', {
        'user': user,
        'device_choices': device_choices,
        'os_choices': os_choices,
        'problem_choices': problem_choices
    },
                              context_instance=RequestContext(request))
Exemple #3
0
def create():
    devices = db.session.query(Device).all()
    """View for create devices"""
    if request.method == 'POST':

        tag = request.form['tag']
        name = request.form['name']
        is_gateway = request.form.get('is_gateway', False)
        description = request.form['description']
        ip = request.form['ip']
        device_parent = request.form['device_parent']
        error = None

        if is_gateway:
            is_gateway = True

        if not tag or not name:
            error = 'No mandatory property is set.'
        else:
            device = Device.query.filter_by(tag=tag).first()
            if device is not None:
                error = "The tag is already exist."

        if error is not None:
            flash(error)
        else:
            try:
                directory = "device_data/" + tag
                if not os.path.exists(directory):
                    os.makedirs(directory)
                if device_parent != "null":
                    device = Device(tag=tag,
                                    name=name,
                                    description=description,
                                    is_gateway=is_gateway,
                                    ipv4_address=ip,
                                    device_parent=device_parent)
                else:
                    device = Device(tag=tag,
                                    name=name,
                                    is_gateway=is_gateway,
                                    ipv4_address=ip,
                                    description=description)
                db.session.add(device)
                db.session.commit()
                return redirect(url_for('device.device_index'))

            except OSError as e:
                flash("Creation of the directory %s failed" % tag)
            except Exception as e:
                flash("DB Creation Failed")

    return render_template('device/create.html', devices=devices)
Exemple #4
0
def device_record(db):
    device = Device(**device_mock)

    db.session.add(device)
    db.session.commit()

    return device
Exemple #5
0
def index():
    index_form = request.form
    current_app.logger.info(request.form)
    search = False

    q = request.args.get('q')
    if q:
        search = True
    try:
        page = int(request.args.get('page', 1))
    except ValueError:
        page = 1
    device_obj = Device()
    total = device_obj.get_count()
    devices = device_obj.paginate(page, 8).items
    pagination = Pagination(css_framework='bootstrap3',
                            link_size='sm',
                            show_single_page=False,
                            page=page,
                            per_page=8,
                            total=total,
                            search=search,
                            record_name='devices',
                            format_total=True,
                            format_number=True)

    template_data = {
        'form': index_form,
        'devices': devices,
        'pagination': pagination
    }

    return render_template("/device/index.html", **template_data)
Exemple #6
0
def report_metrics(request):

    # default failure
    response = HttpResponse("{success:false}", content_type='application/json')

    if request.method == 'POST':
        payload = request.body
        if request.META.get('HTTP_CONTENT_ENCODING', 'None') == 'gzip':
            payload = zlib.decompress(payload, zlib.MAX_WBITS | 32)
        data = json.loads(payload)
        device_name = data["log"]["hardware"]["deviceName"]
        test_time = data["log"]["session"]["reportTime"]

        try:
            device = Device.objects.get(pk=device_name)
        except Device.DoesNotExist:  # catch the DoesNotExist error
            device = Device(name=device_name)
        device.last_update = test_time
        device.save()

        metric = PerformanceMetrics.objects.create(device=device,
                                                   time=test_time,
                                                   data=payload)
        metric.save()

        response = HttpResponse('{success:true}',
                                content_type='application/json')

    return response
def get_all_devices(tenant):
    model = Device(tenant)
    results = model.get_devices()
    return [
        device for device in results if device.get("isActive") or (
            device.get("mobility") and device.get("powerType"))
    ]
Exemple #8
0
def keep_fetch_device_save():
    id = '1022947'
    imei = '328532726131986'
    count = 0
    # 创建DBSession类型:
    DBSession = sessionmaker(bind=engine)
    # 创建session对象:
    session = DBSession()
    while True:
        try:
            ret = get_device(id, imei)
            model = ret['model']
            getDeviceId = ret['getDeviceId']
            print('model: {}'.format(model))
            # Duplicate removal
            query = session.query(Device).filter(
                Device.model == model,
                Device.getDeviceId == getDeviceId).all()
            if query:
                print('已经存在: {}'.format(model))
            else:
                # save
                device_new = Device()
                for key, value in ret.items():
                    setattr(device_new, key, value)
                session.add(device_new)
                session.commit()
                count += 1
                print('保存成功: {}, 一共: {}'.format(device_new, count))
            time.sleep(0.2)
        except Exception as e:
            print(traceback.format_exc())
            print(ret)
            break
Exemple #9
0
    def post(self):
        db = self.application.db
        data = json.loads(self.request.body.decode("utf8"))
        location = "location" in data and data["location"] is not None\
                   and data["location"] != ''\
                   and data["location"] or "The Dark Void"
        try:
            device = db.query(Device).filter(
                Device.gcm_id == data["gcm_id"]).one()
            device.location = location
            response = {
                "message": "Device location updated",
                "response": SUCCESS
            }
        except NoResultFound:
            device = Device(gcm_id=data["gcm_id"], location=location)
            response = {
                "message": "Successfully registered",
                "response": SUCCESS
            }
        gcm_message = {
            'message': "New news item in your location.",
            'timestamp': time.strftime('%Y-%m-%d %H:%M:%S', time.gmtime())
        }

        db.query(News).filter(News.location == location).count() > 0\
            and send_gcm(db, location, gcm_message, gcm_id=device.gcm_id)
        db.add(device)
        db.commit()
        db.close()

        self.write(json.dumps(response))
Exemple #10
0
def addnewdevice():
    if 'username' not in session:
        return redirect(url_for('login'))

    data = request.get_data()
    data = str(data)
    data = data.strip('b').split('&')
    x, y = [], []
    if request.method == 'POST':
        for i in data:
            #print(i.split('=')[1].rstrip("'").replace("+", " "))
            x.append(i.split('=')[1].rstrip("'").replace("+", " "))
        ip, name, desc = x[0], x[1], x[2]
        print(ip, name, desc)
        newdevice = Device(ip, name, desc)
        try:
            db.session.add(newdevice)
            db.session.commit()
            return render_template('addnewdevice.html',
                                   success_msg="Device added successfully")
        except:
            return render_template(
                'addnewdevice.html',
                fail_msg="Error occured. Can not add device")
    return render_template('addnewdevice.html',
                           header="Add New Device",
                           submitvalue="Add Device")
Exemple #11
0
def register_device(version, deviceLibraryIdentifier, passTypeIdentifier,
                    serialNumber):
    recievedAuth = request.headers.get('Authorization').split(" ")[1]
    aPass = Card.query.filter_by(id=serialNumber).first()
    # Verify that version and pass type ID is correct,
    # that serial number on pass exists, and the
    # authentication token is correct
    # If not, return 401 Unauthorized
    if (version != 'v1') or (passTypeIdentifier != 'pass.org.conservatory.phipps.membership') or (aPass is None) \
            or (aPass.authenticationToken != recievedAuth):
        return not_authorized("Device registration could not be completed.")
    else:
        # Check if device is already registered, and if not
        # then register device
        if db.session.query(Device).filter(
            (Device.device_lib_id == deviceLibraryIdentifier)
                & (Device.push_token == request.values.get('pushToken'))
        ).first() is None:
            newDevice = Device(date_registered=datetime.now().astimezone(
                timezone('EST5EDT')).strftime("%Y-%m-%dT%H:%M:%S"),
                               device_lib_id=deviceLibraryIdentifier,
                               push_token=request.get_json().get('pushToken'))
            aPass.devices.append(newDevice)
            db.session.add(aPass)
            db.session.commit()
            return json.dumps({'success': True}), 201, {
                'ContentType': 'application/json'
            }
        else:
            return json.dumps({'success': False}), 200, {
                'ContentType': 'application/json'
            }
Exemple #12
0
def update_device():
    if request.method == 'POST':
        info = request.json
        if not info['sn']:
            abort(400)
        device = Device.query.filter(Device.sn == info['sn']).scalar()

        if device:
            app.logger.debug("Device already exists!")
            if info.get('brand'):
                device.brand = info.get('brand')
            if info.get('model'):
                device.model = info.get('model')
            device.latitude = info.get('latitude')
            device.longitude = info.get('longitude')
            device.timestamp = datetime.now()
        else:
            app.logger.debug("Device doesn't exist!")
            device = Device(sn=info['sn'])
            device.brand = info.get('brand')
            device.model = info.get('model')
            device.latitude = info.get('latitude')
            device.longitude = info.get('longitude')

        device.timestamp = datetime.now()
        db.session.add(device)
        db.session.commit()
        return jsonify(device.to_json())

    else:
        return "Please use 'post' method!"
Exemple #13
0
def edit(device_id):
    edit_form = request.form
    current_app.logger.info(request.form)
    if device_id == 0:
        return
    device_obj = Device()
    device = device_obj.get_by_id(device_id)
    if device is None:
        return

    if request.method == 'POST':
        try:
            device.hospital = request.form['hospital']
            device.device_model = request.form['device_model']
            device.device_index = request.form['device_index']
            device.owner = request.form['owner']
            device.status = request.form['status']
            device.update_user = request.form['update_user']
            print device
            device.save()
            return redirect('/device/index')

        except Exception, e:
            print e
            flash(u'编辑维修部品失败')
            current_app.logger.error(u'编辑维修部品失败')
Exemple #14
0
def login():
    form = LoginForm(request.form)
    if request.method == 'POST':
        username = request.form['username']
        password = request.form['password']
        # A complex query
        # SELECT * FROM Users WHERE username = ? OR email = ?
        user = User.query.filter(
            or_(User.username == username, User.email == username)).first()
        if user or user_email:
            if user.check_password(password):
                active_user = ActiveUser.query.filter_by(
                    user_id=user.id).first()
                if not active_user:
                    active = ActiveUser(user_id=user.id)
                    db.session.add(active)
                    db.session.commit()
                client_UUID = str(uuid.uuid4())
                device = Device(uuid=client_UUID, user_id=user.id)
                db.session.add(device)
                db.session.commit()
                session['device_uuid'] = client_UUID
                session['device_id'] = device.id
                session['logged_in'] = True
                session['user_id'] = user.id
                session['user_username'] = user.username
                flash("Log in successful", "success")
                return redirect(url_for('chat'))
            flash("Passwords do not match!", "error")
            return render_template('login.html', form=form)
        flash("Username not found, consider registering?", "error")
        return render_template('login.html', form=form)
    return render_template('login.html', form=form)
Exemple #15
0
def register_device(request):
	"""
	Request handler when a new device installs the app
	We will need:
	1. Device id
	2. Device type
	3. Push notification id
	these will ensure proper communication with the device
	"""
	if request.method == 'POST':
		json_data = json.loads(request.body)

		try:
			device_id = json_data['device_id']
			device_model = json_data['model']
			device_os = json_data['os']
		except KeyError:
			print "Error: A posted question did not have a JSON object with the required properties"
		else:
			# See if the device id already exists
			try:
				device = Device.objects.get(device_id=device_id)
			except Device.DoesNotExist:
				device = None
			if device:
				return HttpResponse(json.dumps({ 'valid_id' : False }), content_type="application/json")
			else:
				device = Device(device_id=device_id, model=device_model, os=device_os)
				device.save()
				return HttpResponse(json.dumps({ 'valid_id' : True }), content_type="application/json")
Exemple #16
0
def plant_full_setup(app):
    testPlantType = PlantType(plantName, requiredWater, waterFrequency,
                              minTemp, maxTemp, minHumidity, maxHumidity,
                              minMoisture, maxMoisture, idealMoistureLevel,
                              minLightIntensity, maxLightIntensity)

    device = Device(testMACAddress, testTime)

    client = app.test_client()

    db.session.add(device)
    db.session.add(testPlantType)
    db.session.commit()

    testPlant = Plant(type=testPlantType.id,
                      level=testLevel,
                      location=testLocation)
    print(testPlantType.id)
    db.session.add(testPlant)
    db.session.commit()

    yield ""
    db.session.delete(testPlant)
    db.session.delete(testPlantType)
    db.session.delete(device)

    # num_rows_deleted = db.session.query(Plant).delete()

    db.session.commit()
Exemple #17
0
 def get_device_by_id(self, device_id):
     """
     request device by id
     """
     response = requests.get(self._base_url + 'do=/devices/' + str(device_id), timeout=SHORT_TIMEOUT)
     data = json.loads(response.content)
     device = data['device']
     return Device(device)
def create_device(current_user, ):
    data = request.get_json()

    new_device = Device(name=data['name'], organization_id=current_user.id)
    db.session.add(new_device)
    db.session.commit()

    return jsonify({"message": "Device has been created."})
Exemple #19
0
def load_registered_devices():
    if os.path.isfile(registration_file):
        with open(registration_file, mode="r+") as f:
            registration_data = json.loads(f.read())
            for device_json in registration_data:
                d = Device(device_json["id"], device_json["nickname"])
                registered_devices.append(d)
                device_index[device_json["id"]] = d
Exemple #20
0
def _save_device(cd):
    device = Device()
    device.id = cd['id'] or None
    device.description = cd['description']
    device.patrimony_number = cd['patrimony_number']
    device.category = cd['category']
    device.save()
    return device
def save_device_uptime(tenant):
    device_model = Device(tenant)
    devices = device_model.get_all_devices()
    records = []
    futures = []
    executor = ThreadPoolExecutor()
    active_device_count = 0

    for device in devices:
        if device.get('isActive'):
            active_device_count += 1

        channel_id = device["device_number"]
        device_name = device["name"]

        if not (channel_id and device_name):
            print("this device could not be processed", device_name)
            continue
        futures.append(
            executor.submit(get_device_records, tenant, channel_id,
                            device_name, device.get('isActive')))
    for future in futures:
        try:
            records.append(future.result())
        except Exception as e:
            import sys
            from traceback import print_tb, print_exc
            from colored import fg, attr
            color_warning = fg('#FF6600')
            reset = attr('reset')
            print("error occurred while fetching data -", e)
            print(color_warning)
            print_exc(file=sys.stdout)
            print(reset)

    network_uptime = 0.0
    if records:
        network_uptime = (sum(
            record.get("uptime", 0.0)
            for record in records if record.get('is_active')) /
                          active_device_count)

    device_uptime_model = DeviceUptime(tenant)
    device_uptime_model.save_device_uptime(records)

    created_at = datetime.utcnow()
    created_at = created_at.replace(tzinfo=UTC)

    network_uptime_record = {
        "network_name": tenant,
        "uptime": network_uptime,
        "created_at": created_at
    }

    print("network uptime", network_uptime_record)
    network_uptime_model = NetworkUptime(tenant)
    network_uptime_model.save_network_uptime([network_uptime_record])
Exemple #22
0
 def get_devices(self):
     devices = Device.query.all()
     if len(devices) < self.min_devices:
         for x in range(0, self.min_devices - len(devices)):
             k, c = self.generate_device()
             d = Device(key=k, checksum=c)
             db.session.add(d)
         db.session.commit()
         devices = Device.query.all()
     return devices
Exemple #23
0
 def parse_obj(self, obj):
     d = Device()
     d.id_ = obj[0]
     d.name = obj[1]
     d.user = obj[2]
     d.ip = obj[3]
     d.model = obj[4]
     d.created_at = obj[5]
     d.instance_id = obj[6]
     return d
Exemple #24
0
def delete(device_id):
    #delete_form = request.form
    current_app.logger.info(request.form)
    if device_id == 0:
        return
    device_obj = Device()
    result = device_obj.delete(device_id)
    if not result:
        return

    return redirect('/device/index')
Exemple #25
0
def register_device(socket_conn, client_message):
    new_device_registration = client_message['registration']

    if new_device_registration not in device_index:
        dev = Device(new_device_registration)
        registered_devices.append(dev)
        device_index[new_device_registration] = dev
    else:
        dev = device_index[new_device_registration]
    conn_to_device[socket_conn] = dev
    save_registered_devices()
def add_device(friendly_name, ip, netmiko_driver, authentication_user):
    authentication_user = get_user(authentication_user)
    device = Device(
        friendly_name=friendly_name,
        ip=ip,
        netmiko_driver=netmiko_driver,
        authentication_user=authentication_user.id if authentication_user else None
    )
    db.session.add(device)
    db.session.commit()
    return device
    def create(self, request):       
        d = Device(
            name=request['name'],
            user=request['user'],
            ip=request['ip'],
            instance_id=request['instanceId'],
            model=request['model'])

        d.save()

        return jsonify(d.to_json())
 def update(self, request):
     d = Device(
         id_=request['id'],
         name=request['name'],
         user=request['user'],
         ip=request['ip'],
         instance_id=request['instanceId'],
         model=request['model']
     )
     Device.update(d)
     return jsonify(d.to_json())
Exemple #29
0
def addDevice():
    name = request.form['name']
    type = request.form['type']
    addr = request.form['address']
    passwd = request.form['passwd']
    new_device = Device(name, type, addr, passwd)
    from myapp import db
    db.session.add(new_device)
    db.session.commit()
    return jsonify({"name":name, "type":type,
            "addr":addr, "passwd":passwd})
Exemple #30
0
def deviceAdd(client, userdata, msg):
    # unpack json payload
    json_data = msg.payload
    raw_data = json.loads(str(json_data, encoding="utf-8"))

    with app.app_context():
        device = Device(raw_data["serial-number"], raw_data["type"],
                        raw_data["address"], raw_data["passwd"])
        db.session.add(device)
        db.session.commit()
    print(datetime.datetime.now(), "new device added:",
          raw_data["serial-number"])