Пример #1
0
    def test_get(self):
        # Create and insert two stations and two sensors into sqlite
        se1 = Sensor(reads='Humidity')
        se2 = Sensor(reads='Temprature')
        st1 = Station(name='Jx05t', active=True, sensors=[se1, se2])
        st2 = Station(name='Zy99p', active=True)
        db.session.add_all([st1, st2])
        db.session.commit()
        a1 = db.session.query(Station).filter_by(name=st1.name).one()
        a2 = db.session.query(Station).filter_by(name=st2.name).one()

        # Check if they are inserted
        self.assertEqual(a1, st1)
        self.assertEqual(a2, st2)

        # Check the relationship Stations -< Sensor
        self.assertEqual(a1.sensors.all(), [se1, se2])
        self.assertEqual(a2.sensors.all(), [])

        # Send an API request to get stations
        response = self.app.test_client().get('/stations')
        self.assertEqual(response.status_code, 200)
        data = json.loads(response.get_data(as_text=True))

        # Check if they exist in the response
        item_ids_returned = [item["id"] for item in data['data']]
        self.assertIn(a1.id, item_ids_returned)
        self.assertIn(a2.id, item_ids_returned)
        for item in data['data']:
            if (item["id"] == a1.id):
                self.assertEqual(item["name"], a1.name)
Пример #2
0
    def test_get_sensors(self):
        s1 = Sensor(description='foo',
                    latitude=0,
                    longitude=0,
                    gateway='asd',
                    power_perc=0,
                    vineyard_id=self.vineyard.id,
                    user_id=self.admin_user.id)
        s2 = Sensor(description='bar',
                    latitude=0,
                    longitude=0,
                    gateway='asd',
                    power_perc=0,
                    vineyard_id=self.vineyard.id,
                    user_id=self.admin_user.id)
        db.session.add(s1)
        db.session.add(s2)
        db.session.commit()

        response = self.client.get('/api/v1/sensors/',
                                   headers=self.get_admin_headers())
        self.assertEqual(response.status_code, 200)

        json_response = json.loads(response.get_data(as_text=True))
        self.assertEqual(json_response.get('count'), 2)
        self.assertEqual(len(json_response.get('sensors')), 2)
Пример #3
0
    def test_delete(self):
        # Create and insert stations and sensors into sqlite
        se1 = Sensor(reads='Humidity')
        se2 = Sensor(reads='Temprature')
        st1 = Station(name='Jx05t', active=True, sensors=[se1, se2])
        st2 = Station(name='Zy99p', active=True)
        db.session.add_all([st1, st2])
        db.session.commit()
        a1 = db.session.query(Station).filter_by(name=st1.name).one()
        a2 = db.session.query(Station).filter_by(name=st2.name).one()

        # Check if correctly inserted
        self.assertEqual(a1.name, st1.name)
        self.assertEqual(a2.name, st2.name)
        self.assertEqual(a1.sensors.count(), 2)

        # Request delete through the API
        response = self.app.test_client().delete('/stations/' + str(a1.id))

        # Retrieve items through sqlite
        a1 = db.session.query(Station).filter_by(name=st1.name).scalar()
        a2 = db.session.query(Station).filter_by(name=st2.name).scalar()
        ses = db.session.query(Sensor).count()

        # Check if correctly deleted
        self.assertEqual(a1, None)
        self.assertNotEqual(a2, None)

        # Check if deleting cascaddes to sensors correctly
        self.assertEqual(ses, 0)
Пример #4
0
    def test_cant_delete_sensor(self):
        r = Role.query.filter_by(name='Writer').first()
        u = User(email='*****@*****.**',
                 password='******',
                 confirmed=True,
                 role=r)
        db.session.add(u)
        db.session.commit()

        s = Sensor(description='foo',
                   latitude=0,
                   longitude=0,
                   gateway='asd',
                   power_perc=0,
                   vineyard_id=self.vineyard.id,
                   user_id=u.id)
        db.session.add(s)
        db.session.commit()

        response = self.client.delete('/api/v1/sensors/%d' % s.id,
                                      headers=self.get_writer_headers())

        self.assertEqual(response.status_code, 403)

        response = self.client.get('/api/v1/sensors/%d' % s.id,
                                   headers=self.get_api_headers(
                                       '*****@*****.**', 'cat'))
        self.assertEqual(response.status_code, 200)
Пример #5
0
def add_sensors_to_db():
    for sensor in SENSORS:
        s = Sensor()
        s.from_dict(sensor)
        db.session.add(s)
        db.session.commit()
        sensor["id"] = s.id
Пример #6
0
def index():
    st = ""
    if not current_user.is_authenticated:
        return redirect(url_for('login'))
    form = SensorSubmitForm()
    user_id = session["user_id"]
    user = User.query.filter_by(id=user_id).first()
    this_sensor = Sensor.query.filter_by(user_id=user_id).first()
    thisForm = SelectSensorForm(form_name='SelectSensorForm')
    thisForm.sensor_select.choices = [(row.id, row.name) for row in Sensor.query.filter_by(user_id=user_id).all()]
    if form.validate_on_submit():
        sensor = Sensor(name=form.sensor_name.data,user_id=user_id)
        db.session.add(sensor)
        db.session.commit()
        return redirect(url_for('index'))
    sensor_list = Sensor.query.filter_by(user_id=user_id).all()
    my_sensor = thisForm.sensor_select.data
    data = Data.query.filter_by(sensor_id=my_sensor).all()
    thisurl = plotGraph(data)
    if thisurl != 'none':
        print(thisurl)
        newstr = thisurl[:0] + thisurl[1:]
        st = newstr[:-1]
        print(st)
        return render_template('index.html',user=user,sensor_display=this_sensor,form=form,thisForm = thisForm,sensor_list = sensor_list,inurl = st)
    return render_template('index.html',user=user,sensor_display=this_sensor,form=form,thisForm = thisForm,sensor_list = sensor_list,inurl = st)
Пример #7
0
def test_update_sensor_set_name_when_sensor_exists(client):
    sensor = Sensor.create(
        id="the-id",
        name="the-name",
        sensor_type="temperature",
        next_update=datetime.max,
    )

    new_name = "some-name"
    res = client.patch(
        url_for("api.update_sensor", sensor_id=sensor.id),
        json=[{
            "op": "replace",
            "path": "/name",
            "value": new_name
        }],
    )
    expected = Sensor(
        id=sensor.id,
        name=new_name,
        sensor_type=sensor.sensor_type,
        next_update=datetime.max,
        firmware_version="",
    )
    assert res.status_code == 200
    assert res.json == expected.to_json()

    res = client.get(url_for("api.get_sensor", sensor_id=sensor.id))
    assert res.json == expected.to_json()
Пример #8
0
    def setUp(self):
        self.app = self.create_app()
        self.client = self.app.test_client()
        self.app_context = self.app.app_context()
        self.app_context.push()
        db.create_all()

        # Create some data to test against, but don't commit
        # Create a region
        maine = Region(name='Maine', slug='maine')
        db.session.add(maine)

        # Create a river
        andro = River(name='Androscoggin River',
                      slug='androscoggin')
        wild = River(name='Wild River of the Androsoggin',
                     slug='wild-androscoggin',
                     parent=andro)
        db.session.add(andro)
        db.session.add(wild)

        # Create a section
        wild_section = Section(name='Wild River from Hastings',
                               slug='wild-river',
                               river=wild,
                               putin='SRID=4326;POINT(-71.05996191501617 44.31595096222731)',
                               takeout='SRID=4326;POINT(-70.97963511943817 44.390833083196924)',
                               path='SRID=4326;LINESTRING(-71.05997800827026 44.316024368364864,-71.05881929397583 44.31798950769032,-71.05731725692749 44.31884923545022,-71.05444192886353 44.31851148676115,-71.05298280715942 44.31943261497028,-71.05096578598022 44.322687152160796,-71.05045080184937 44.32449856163325,-71.04984998703003 44.32495908054771,-71.04761838912964 44.325849406864485,-71.04568719863892 44.32649411748597,-71.04306936264038 44.32753791965937,-71.04049444198608 44.327138821021585,-71.03847742080688 44.32664761897048,-71.03607416152954 44.32572660403795,-71.03517293930054 44.32554239931617,-71.03431463241577 44.32594150881567,-71.03341341018677 44.32805981378074,-71.03264093399048 44.329103588092785,-71.02929353713989 44.32984035877702,-71.02843523025513 44.33008594694842,-71.02757692337036 44.33137526797721,-71.02804899215698 44.33309431859246,-71.02783441543579 44.33459844654652,-71.02543115615845 44.33582627750024,-71.02311372756958 44.33714616710255,-71.0210108757019 44.33926406740166,-71.01598978042603 44.34328479806066,-71.01294279098511 44.3441441551062,-71.00916624069214 44.346752840399844,-71.0082221031189 44.34972966884455,-71.00689172744751 44.35107993293547,-71.00551843643188 44.351171995263435,-71.00393056869507 44.350374116950185,-71.00148439407349 44.35000586175751,-70.9984803199768 44.350374116950185,-70.99642038345337 44.35163230473401,-70.99328756332397 44.354117913402796,-70.9923005104065 44.3552225945275,-70.99212884902954 44.35678752380721,-70.99401712417603 44.357830786775374,-70.99517583847046 44.3607763701854,-70.99680662155151 44.36571602660432,-70.99599123001099 44.368722570068854,-70.99448919296265 44.36961223191264,-70.99242925643921 44.37123813071097,-70.99054098129272 44.371422191881805,-70.98955392837524 44.372986688478704,-70.99075555801392 44.37507261892906,-70.98963975906372 44.37691308409485,-70.98848104476929 44.37832406821415,-70.9874939918518 44.38086988832067,-70.98470449447632 44.382403461463625,-70.98273038864136 44.384059675338044,-70.9810996055603 44.38531713976433,-70.97848176956177 44.3864825704798,-70.97749471664429 44.38746396782254,-70.97903966903687 44.38970271892836)',)
        db.session.add(wild_section)

        # Create a gage
        wild_gage = Gage(name='Wild River at Gilead',
                         slug='wild-river-gilead',
                         point='SRID=4326;POINT(-70.97963511943817 44.390833083196924)',
                         river=wild,
                         visible=True,
                         zipcode='04217',
                         local_town='Gilead, ME',
                         location='Wild River at Gilead above Rt 2',
                         key='password')
        db.session.add(wild_gage)

        # Create a sensor
        wild_sensor = Sensor(name='Gage Height',
                             stype='usgs-height',
                             local=False, remote_type='usgs',
                             remote_id='01054200',
                             gage=wild_gage)
        db.session.add(wild_sensor)

        # Create a sample
        wild_sample = Sample(sensor=wild_sensor,
                             datetime=datetime.datetime.now(),
                             value=5.8)
        db.session.add(wild_sample)
        db.session.commit()
Пример #9
0
 def test_fetch_remote_samples_error(self, delay=False):
     random_stage = Sensor(name='Canaseraga Creek',
                           stype='canaseraga-stage',
                           local=False, remote_type='random',
                           remote_id='DSVN6')
     db.session.add(random_stage)
     before = Sample.query.count()
     remote.fetch_remote_samples()
     after = Sample.query.count()
     assert after > before
Пример #10
0
    def setUp(self):
        self.app = create_app('testing')
        self.app_context = self.app.app_context()
        self.app_context.push()
        db.create_all()
        Role.insert_roles()
        self.client = self.app.test_client()

        # add regular user
        r = Role.query.filter_by(name='Writer').first()
        u = User(email='*****@*****.**', password='******', confirmed=True,
                 role=r)
        db.session.add(u)
        db.session.commit()
        self.writer_user = u

        # add a vineyard for the regular user
        v = Vineyard(name='foo', user_id=self.writer_user.id)
        db.session.add(v)
        db.session.commit()
        self.vineyard = v

        # add a sensor for the regular user
        s = Sensor(description='bar', latitude=0, longitude=0, gateway='asd',
                   power_perc=0, vineyard_id=self.vineyard.id, user_id=self.writer_user.id)
        db.session.add(s)
        db.session.commit()
        self.sensor = s

        # add a magnitude for the regular user
        m = Magnitude(layer='Surface', type='Temperature', sensor_id=self.sensor.id,
                      user_id=self.writer_user.id)
        db.session.add(m)
        db.session.commit()
        self.magnitude = m

        # add a read only user
        r = Role.query.filter_by(name='Reader').first()
        u = User(email='*****@*****.**', password='******', confirmed=True,
                 role=r)
        db.session.add(u)
        db.session.commit()
        self.reader_user = u

        # add an admin user
        r = Role.query.filter_by(name='Administrator').first()
        u = User(email='*****@*****.**', password='******', confirmed=True,
                 role=r)
        db.session.add(u)
        db.session.commit()
        self.admin_user = u

        self.tokens = {}
Пример #11
0
def regsensor(cid):
    if not current_user.is_authenticated:
        return redirect(url_for('index'))
    form = RegSensor()
    home = Casa.query.get(cid)
    if form.validate_on_submit():
        sen = Sensor(puerto=form.puerto.data, domicilio=home)
        db.session.add(sen)
        db.session.commit()
        flash('Felicidades, has registrado un sensor!')
        return redirect(url_for('index'))
    return render_template('regsensor.html', title='Registro sensor', home=home, form=form)
Пример #12
0
def add_sensor():
    did = request.args.get('did')
    form = SensorForm()
    if form.validate_on_submit():
        sensor = Sensor()
        sensor.name = form.name.data
        sensor.describe = form.describe.data
        sensor.unit = form.unit.data
        sensor.device_id = did
        db.session.add(sensor)
        db.session.commit()
        return redirect(url_for('main.device', did=did))
    return render_template('main/add_sensor.html', form=form)
Пример #13
0
def createsensor():
    device_name = request.json.get('device_name')
    hostname = request.json.get('hostname')
    ip_address = request.json.get('ip_address')
    location = request.json.get('location')
    protected_subnet = request.json.get('protected_subnet')
    external_subnet = request.json.get('external_subnet')
    oinkcode = request.json.get('oinkcode')
    company = g.user['company']
    sensor = Sensor(company=company, device_name=device_name,
                    hostname=hostname, ip_address=ip_address, location=location,
                    protected_subnet=protected_subnet)

    if external_subnet:
        sensor.set_oinkcode(oinkcode)
    if external_subnet:
        sensor.set_external_subnet(external_subnet)

    sensor.create_dev_id(device_name)
    sensor.create_topic_cmd()
    sensor.create_topic_resp()

    Sensor.create(company=sensor['company'],
                  device_id=sensor['device_id'],
                  device_name=sensor['device_name'],
                  hostname=sensor['hostname'],
                  ip_address=sensor['ip_address'],
                  location=sensor['location'],
                  protected_subnet=sensor['protected_subnet'],
                  external_subnet=sensor['external_subnet'],
                  oinkcode=sensor['oinkcode'],
                  topic_global=sensor['topic_global'],
                  topic_cmd=sensor['topic_cmd'],
                  topic_resp=sensor['topic_resp'],
                  sensor_key=sensor['sensor_key'],
                  time_created=sensor['time_created']
                  )

    app.session.execute(
        """
        INSERT INTO sensor_status (device_id, status, ts) 
        VALUES (%s, %s, %s)
        """,
        (sensor['device_id'], "STOPPED", datetime.now())
    )

    return jsonify({
        'device_id': sensor['device_id'],
        'device_name': sensor['device_name'],
        'sensor_key': sensor['sensor_key'],
    })
Пример #14
0
def add_cgq():
    id = request.args.get('id')
    sen = Device.query.filter_by(id=id).first()
    form = ChuanGanQiFrom()
    if form.validate_on_submit():
        sensor = Sensor()
        sensor.name = form.sensors_name.data
        sensor.describe = form.sensors_description.data
        sensor.unit = form.sensors_unit.data
        sensor.devices_id = sen.id
        db.session.add(sensor)
        db.session.commit()
        return redirect(url_for('auth.shebei'))
    return render_template('equipment/add-chuanganqi.html', form=form)
Пример #15
0
    def test_admin_can_get_others_sensor(self):
        s = Sensor(description='foo',
                   latitude=0,
                   longitude=0,
                   gateway='asd',
                   power_perc=0,
                   vineyard_id=self.vineyard.id,
                   user_id=self.writer_user.id)
        db.session.add(s)
        db.session.commit()

        response = self.client.get('/api/v1/sensors/%d' % s.id,
                                   headers=self.get_admin_headers())
        self.assertEqual(response.status_code, 200)
Пример #16
0
def addSensor():
    form = AddSensorForm()
    if form.validate_on_submit():
        sensor = Sensor(sensorID=form.sensorID.data,
                        sensorName=form.sensorName.data,
                        sensorAlarmValue=form.sensorAlarmValue.data,
                        sensorClass=form.sensorClass.data)
        db.session.add(sensor)
        db.session.commit()
        user = User.query.filter_by(username=current_user.username).first()
        if sensor.sensorAlarmValue > 0:
            send_sensor_trigger_email(user, sensor)
        flash(_('Your sensor has been added!'))
        return redirect(url_for('monitor'))
    return render_template('addSensor.html', title=_('Add Sensor'), form=form)
Пример #17
0
    def insert_data(data):
        """Insert dict sensor object to database"""
        print("[DEBUG]Insert to database sensor info {}".format(
            data['node_id']))
        sensor = Sensor()
        for field in SensorDB.dict_struct:
            if field in data:
                setattr(sensor, field, data[field])

        try:
            db.session.add(sensor)
            db.session.commit()
        except Exception as e:
            print("Error: {}".format(e))

        return sensor
Пример #18
0
    def test_get_sensor(self):
        s = Sensor(description='foo',
                   latitude=0,
                   longitude=0,
                   gateway='asd',
                   power_perc=0,
                   vineyard_id=self.vineyard.id,
                   user_id=self.writer_user.id)
        db.session.add(s)
        db.session.commit()

        response = self.client.get('/api/v1/sensors/%d' % s.id,
                                   headers=self.get_writer_headers())
        self.assertEqual(response.status_code, 200)

        json_response = json.loads(response.get_data(as_text=True))
        self.assertEqual(json_response.get('id'), s.id)
Пример #19
0
def addsensor():
    if request.is_json:
        req_data = request.get_json()

        try:
            emailData = req_data["email"]
            sensorNameData = req_data["sensorName"]
            hostnameData = req_data["hostname"]
            ipData = req_data["ipAddress"]
            interfaceData = req_data["netInterface"]
            locationData = req_data["location"]
            companyData = req_data["company"]
        except Exception as err:
            print("[Error] : {}".format(err))
            return nice_json(
                raise_json_code(400,
                                "Variable Error, Please Fill All the Field"))

        try:
            sensor = Sensor(hostname=hostnameData,
                            ip_address=ipData,
                            net_interfaces=interfaceData,
                            location=locationData,
                            company=companyData,
                            topic=Topic())
            sensor.set_sensor_name(sensorNameData)
            user = User.objects.get({'_id': emailData})
            user.add_sensor(sensor)
            user.save()
        except ValidationError as ve:
            print("[Error] : {}".format(ve.message))
            return nice_json(raise_json_code(400, "Paramter Not Valid"))
        except DuplicateKeyError:
            print("[Error] : Duplicate email")
            return nice_json(
                raise_json_code(
                    400, "There is already user with that email address."))

        return nice_json(
            raise_json_code_with_data(200, "Add Sensor Success",
                                      sensor.to_son().to_dict()))

    else:
        return nice_json(
            raise_json_code(400, "Please send proper request in json"))
Пример #20
0
def db_load_example_data(app, db):
    sensors = []
    for i in range(5):
        sensors.append(
            Sensor(id=b2a_hex(urandom(16)).decode('ascii'),
                   description="Sensor {}".format(i)))

    detections = []
    for i in range(20):
        detections.append(
            Detection(md5_mac=b2a_hex(urandom(16)).decode('ascii'),
                      timestamp=datetime.now(),
                      sensor_id=sensors[i % 5].id))

    with app.app_context():
        db.session.add_all(sensors)
        db.session.add_all(detections)
        db.session.commit()
Пример #21
0
def create_sensor():
    data = request.get_json() or {}
    if "name" not in data:
        return bad_request("must include name field")
    if "categories" not in data:
        return bad_request("must include categories field")
    if not Category.are_valid_categories(data["categories"]):
        return bad_request("invalid categor(y)/(ies) in included categories")
    if Sensor.query.filter_by(name=data["name"]).first():
        return bad_request("please use a different name")
    sensor = Sensor()
    sensor.from_dict(data)
    db.session.add(sensor)
    db.session.commit()
    response = jsonify(sensor.to_dict())
    response.status_code = 201
    response.headers["Location"] = url_for("api.get_sensor",
                                           sensor_id=sensor.id)
    return response
Пример #22
0
def handle_message(msg):
    now_temp = msg[6]
    temp_config = Config.query.filter_by(sensor_type='temp').first()
    fan0_config = Config.query.filter_by(sensor_type='fan0').first()
    # Temperature is too high
    if now_temp > temp_config.max_value:
        if fan0_config.status == 0:
            # Turn on fan0
            ser.on_send(b'\xfe\x05\xa3\x45\x03\x00\x11\xff')
            # Automatic operation is 0, and manual is 1
            fan0_config.where = 0
            fan0_config.status = 1
    else:
        if fan0_config.status == 1 and fan0_config.where == 0:
            # Turn off fan0
            ser.on_send(b'\xfe\x05\xa3\x45\x03\x00\x10\xff')
            fan0_config.status = 0

    db.session.add(Sensor("temp", now_temp, msg[7]))
    db.session.commit()
Пример #23
0
    def setUp():
        app.config.from_object(Config)
        db.create_all()

        # Possible sensor names
        sensorref = ['Temprature', 'Humidity', 'WindSpeed', 'UV']

        # Add 100 stations as example
        for x in range(100):
            # Create random number of random types of sensors
            sensors = [
                Sensor(reads=sample)
                for sample in random.sample(sensorref, random.randint(0, 4))
            ]

            # Random name assigned to station
            st = Station(name=str(uuid.uuid1()), active=True, sensors=sensors)
            db.session.add(st)

        db.session.commit()
Пример #24
0
def add_sensor():
    if request.method == "POST":

        # if request.form["type"]:
        s_type = request.form.get("type")
        location = request.form.get("location")
        inside = request.form.get("inside")

        print(s_type)
        print(location)
        print(inside)

        if (s_type != "") and (inside != None) and (location != ""):
            inside = True if inside == "inside" else False
            sensor = Sensor(location=location, type=s_type, inside=inside)
            db.session.add(sensor)
            db.session.commit()
        return redirect('/manage-sensors')
        # TODO:
        # sensor = Sensor(location='Room1Left', type="", inside=True)
    return render_template('add_sensor.html')
Пример #25
0
 def test_to_json(self):
     u = User(email='*****@*****.**', password='******')
     db.session.add(u)
     db.session.commit()
     v = Vineyard(name='foo', user_id=u.id)
     db.session.add(v)
     db.session.commit()
     s = Sensor(description='foo', latitude=2.4, longitude=1.2, gateway='bar', power_perc=100,
                vineyard_id=v.id, user_id=u.id)
     db.session.add(s)
     db.session.commit()
     with self.app.test_request_context('/'):
         json_sensor = s.to_json()
     expected_keys = ['id', 'description', 'latitude', 'longitude', 'gateway', 'power_perc',
                      'url', 'user_url', 'vineyard_url', 'magnitudes', 'magnitudes_url', 'created_at']
     self.assertEqual(sorted(json_sensor.keys()), sorted(expected_keys))
     self.assertEqual('/api/v1/sensors/' + str(s.id), json_sensor['url'])
     self.assertEqual('/api/v1/users/' + str(u.id), json_sensor['user_url'])
     self.assertEqual('/api/v1/vineyards/' + str(v.id), json_sensor['vineyard_url'])
     self.assertEqual('/api/v1/sensors/' + str(v.id) + '/magnitudes/',
                      json_sensor['magnitudes_url'])
Пример #26
0
def add_sensor():
    form = AddSensor()
    did = request.args.get('did')
    if did is None:
        abort(404)
    device = current_user.devices.filter_by(id=did).first()
    if device is None:
        abort(404)
    if form.validate_on_submit():
        sensor = Sensor()
        sensor.type = form.type.data
        sensor.name = form.name.data
        sensor.about = form.about.data
        sensor.unit = form.unit.data
        sensor.max = form.max.data
        sensor.min = form.min.data
        sensor.device_id = did
        db.session.add(sensor)
        db.session.commit()
        return redirect(url_for('main.device_info', did=did))
    return render_template('main/add_sensor.html', form=form)
Пример #27
0
    def test_vineyard_sensors(self):
        v = Vineyard(name='foo', user_id=self.writer_user.id)
        db.session.add(v)
        db.session.commit()
        s = Sensor(description='bar',
                   latitude=0,
                   longitude=0,
                   gateway='asd',
                   power_perc=0,
                   vineyard_id=v.id,
                   user_id=self.writer_user.id)
        db.session.add(s)
        db.session.commit()

        response = self.client.get('/api/v1/vineyards/%d/sensors/' % v.id,
                                   headers=self.get_writer_headers())

        self.assertEqual(response.status_code, 200)
        json_response = json.loads(response.get_data(as_text=True))
        self.assertEqual(json_response['count'], 1)
        self.assertEqual(json_response['sensors'][0]['id'], s.id)
Пример #28
0
def index():
    app.logger.info('successfully posted')
    print("making a post request....")
    # logger.debug("making a post request....")
    content = request.get_json()
    if content:
        print(content)
        # logger.debug(content)
        value = int(content.get("sensorValue"))
        college = str(content.get("college"))
        machineLabel = str(content.get("machineLabel"))

        sensor = Sensor(sensorValue=value, college=college, machineLabel=machineLabel)

        db.session.add(sensor)
        db.session.commit()

        print(get_latest_sensor_value(college=college, machineLabel=machineLabel))

        return "STORE SUCCESS "
    return render_template('index.html', content=content)
Пример #29
0
def accept_data(token):
    """ Register sensor if it's new sensor and send data to metrics storage """
    # Check token
    user = User.query.filter_by(token=token).first()

    if not user:
        return bad_request("Unregistered token")

    data = request.get_json() or {}

    if 'serial' not in data:
        return bad_request("Request must includes 'serial' field")

    # Register sensor if not registered
    sensor = Sensor.query.filter_by(token=token,
                                    serial_number=data.get('serial')).first()

    if not sensor:
        sensor = Sensor()
        sensor.serial_number = data.get('serial')
        sensor.token = token
        sensor.user = user.id

        # Commit changes to db
        db.session.add(sensor)
        db.session.commit()

    metric = FlowerMetric()
    metric.time = datetime.datetime.now()
    metric.sensor = sensor.id
    logging.info(f"Received metric: {data}")
    metric.temperature = float(data.get('temperature', -1.0))
    metric.light = 500.0 - float(data.get('light', -1.0))
    metric.soilMoisture = 100.0 - float(data.get('soilMoisture', -1.0)) / 10.0

    # Commit changes to db
    db.session.add(metric)
    db.session.commit()

    return create_response_from_data_with_code({}, 204)
Пример #30
0
 def test_to_json(self):
     u = User(email='*****@*****.**', password='******')
     db.session.add(u)
     db.session.commit()
     v = Vineyard(name='foo', user_id=u.id)
     db.session.add(v)
     db.session.commit()
     s = Sensor(description='foo', latitude=2.4, longitude=1.2, gateway='bar', power_perc=100,
                vineyard_id=v.id, user_id=u.id)
     db.session.add(s)
     db.session.commit()
     m = Magnitude(layer='Surface', type='Temperature', sensor_id=s.id, user_id=u.id)
     db.session.add(m)
     db.session.commit()
     with self.app.test_request_context('/'):
         json_magnitude = m.to_json()
     expected_keys = ['id', 'layer', 'type', 'url', 'user_url', 'sensor_id', 'sensor_url', 'metrics_url', 'created_at']
     self.assertEqual(sorted(json_magnitude.keys()), sorted(expected_keys))
     self.assertEqual('/api/v1/magnitudes/' + str(s.id), json_magnitude['url'])
     self.assertEqual('/api/v1/users/' + str(u.id), json_magnitude['user_url'])
     self.assertEqual('/api/v1/magnitudes/' + str(v.id) + '/metrics/',
                      json_magnitude['metrics_url'])