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()
def test_get_sensor_log_when_sensor_has_logs(client): sensor_id = "some-id" Sensor.create(id=sensor_id, name="a name", sensor_type="temperature", next_update=datetime.max) log_row_1 = { "timestamp": 1547477541, "message": "some message to log here" } log_row_2 = { "timestamp": 1547478541, "message": "some other message to log here" } client.post(url_for("api.add_sensor_log", sensor_id=sensor_id), json=log_row_1) client.post(url_for("api.add_sensor_log", sensor_id=sensor_id), json=log_row_2) res = client.get(url_for("api.get_sensor_log", sensor_id=sensor_id)) assert res.status_code == 200 for row_in_res in res.json: assert "id" in row_in_res assert row_in_res["timestamp"] in [ "2019-01-14T14:52:21", "2019-01-14T15:09:01" ] assert row_in_res["message"] in log_row_1["message"] or log_row_2[ "message"]
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)
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)
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)
def add_sensor_value(sensor_type): temp_reading = request.get_json() if "timestamp" not in temp_reading: return bad_request("timestamp attribute missing") if "sensor" not in temp_reading: return bad_request("sensor attribute missing") if "value" not in temp_reading: return bad_request("value attribute missing") if "next_update" not in temp_reading: return bad_request("next_update attribute missing") sensor_id = temp_reading["sensor"].replace(":", "") sensor = Sensor.get_by_id(sensor_id) if sensor is not None and sensor.sensor_type != sensor_type: return bad_request("Sensor is already registered as another type") if sensor is None: sensor = Sensor.create(id=sensor_id, name=sensor_id, sensor_type=sensor_type) sensor.next_update = datetime.utcfromtimestamp( temp_reading["timestamp"] + temp_reading["next_update"] ) db.session.commit() reading = Reading( sensor=sensor_id, timestamp=datetime.utcfromtimestamp(temp_reading["timestamp"]), value=temp_reading["value"] * 100, ) db.session.add(reading) db.session.commit() return jsonify({"message": "thanks"}), 201
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
def test_reading_creation(self): res = self.client.post('/readings', data=self.readings1) res = self.client.post('/readings', data=self.readings2) self.assertEquals(res.status_code, 201) self.assertFalse(Sensor.get("sensor1") is None) self.assertFalse(Sensor.get("sensor2") is None) self.assertTrue(len(Reading.get_all()) is 5)
def test_sensor_add_sensor_log_when_timestamp_missing(client): sensor_id = "some-id" Sensor.create( id=sensor_id, name="the-name", sensor_type="temperature", next_update=datetime.max, ) log = {"message": "some message to log here"} res = client.post(url_for("api.add_sensor_log", sensor_id=sensor_id), json=log) assert res.status_code == 400
def test_sensor_add_sensor_log_when_message_length_over_256_chars(client): sensor_id = "some-id" Sensor.create( id=sensor_id, name="the-name", sensor_type="temperature", next_update=datetime.max, ) log = {"timestamp": 1567447541, "message": "*" * 257} res = client.post(url_for("api.add_sensor_log", sensor_id=sensor_id), json=log) assert res.status_code == 400
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)
def test_reading_creation(self): res = self.client.post('/readings', data=self.readings_1) self.assertEqual( res.data, '[\n {\n "calibration": true, \n "height": 0.94, \n "lat": -7.918233, \n "lat_lon_sd": 15.0, \n "lon": -33.412813, \n "sample_count": 100, \n "sensor_id": "sensor1", \n "time": 111.11, \n "uncal_pressure": 103242.0, \n "uncal_pressure_sd": 38.5, \n "uncal_temperature": 290.23, \n "uncal_temperature_sd": 1.2\n }, \n {\n "calibration": false, \n "height": 0.95, \n "lat": -7.918234, \n "lat_lon_sd": 16.0, \n "lon": -33.412812, \n "sample_count": 100, \n "sensor_id": "sensor1", \n "time": 222.22, \n "uncal_pressure": 103243.0, \n "uncal_pressure_sd": 38.6, \n "uncal_temperature": 290.24, \n "uncal_temperature_sd": 1.3\n }\n]\n' ) res = self.client.post('/readings', data=self.readings_2) self.assertEqual( res.data, '[\n {\n "calibration": true, \n "height": 0.96, \n "lat": -7.918235, \n "lat_lon_sd": 17.0, \n "lon": -33.412815, \n "sample_count": 100, \n "sensor_id": "sensor2", \n "time": 111.11, \n "uncal_pressure": 103247.0, \n "uncal_pressure_sd": 38.7, \n "uncal_temperature": 290.27, \n "uncal_temperature_sd": 1.7\n }, \n {\n "calibration": false, \n "height": 0.98, \n "lat": -7.918238, \n "lat_lon_sd": 18.0, \n "lon": -33.412818, \n "sample_count": 100, \n "sensor_id": "sensor2", \n "time": 222.22, \n "uncal_pressure": 103248.0, \n "uncal_pressure_sd": 38.8, \n "uncal_temperature": 290.28, \n "uncal_temperature_sd": 1.8\n }, \n {\n "calibration": false, \n "height": 0.99, \n "lat": -7.918239, \n "lat_lon_sd": 19.0, \n "lon": -33.412819, \n "sample_count": 100, \n "sensor_id": "sensor2", \n "time": 333.33, \n "uncal_pressure": 103249.0, \n "uncal_pressure_sd": 38.9, \n "uncal_temperature": 290.29, \n "uncal_temperature_sd": 1.9\n }\n]\n' ) self.assertEquals(res.status_code, 201) self.assertFalse(Sensor.get("sensor1") is None) self.assertFalse(Sensor.get("sensor2") is None) self.assertTrue(len(Reading.get_all()) is 5)
def test_get_sensors_with_sensors_returns_the_sensors(client): sensor = Sensor.create(id="the-id", name="the-name", sensor_type="temperature") res = client.get(url_for("api.get_sensors")) assert res.json == [sensor.to_json()]
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)
def test_get_sensor_when_sensor_exists(client): sensor = Sensor.create(id="the-id", name="the-name", sensor_type="temperature") res = client.get(url_for("api.get_sensor", sensor_id=sensor.id)) assert res.status_code == 200 assert res.json == sensor.to_json()
def get_dashboard(): sensors = Sensor.get_all() return render_template( "index.html", my_string="Wheeeee!", temp_sensors=[s for s in sensors if s.sensor_type == "temperature"], humidity_sensors=[s for s in sensors if s.sensor_type == "humidity"], )
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"))
def get_sensor_log(sensor_id): sensor = Sensor.get_by_id(sensor_id) if sensor is None: return not_found("Sensor not found") rows = LogRow.get_by_sensor_id(sensor_id) res = [] for row in rows: res.append(row.to_json()) return jsonify(res), 200
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()
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
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
def get_readings(sensor_id): page = request.args.get("page", 1, type=int) per_page = min(request.args.get("per_page", 25, type=int), 100) sensor = Sensor.query.get_or_404(sensor_id) data = Sensor.to_collection_dict(sensor.readings, page, per_page, "api.get_readings", sensor_id=sensor_id) return jsonify(data)
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)
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'])
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 = {}
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)
def readings(): # print('REQUEST: ', request, request.args, request.data) if request.method == "POST": result = Reading.save_readings_from_json(request) # generate server response response = jsonify(result) response.status_code = 201 # Created return response # GET else: sid = request.args.get('sensor_id', '', type=str) count = request.args.get('count', -1, type=int) # check if query contains count if count != -1: # query does not specify sensor id if sid == '': sensor_ids = Sensor.get_all_ids() filtered = [] for id in sensor_ids: one_sensors_readings = Reading.get_for_sensor( id.sensor_id, count) for r in one_sensors_readings: filtered.append(r) return create_readings_response(filtered) # query contains sensor id & count else: # return count readings from sensor with given sensor_id filtered = Reading.get_for_sensor(sid, count) return create_readings_response(filtered) # check if query contains sensor id, and start and end times else: start = request.args.get('start_time', -1, type=int) end = request.args.get('end_time', -1, type=int) if (start != -1) and (end != -1): if sid != '': filtered = Reading.get_sensor_range(sid, start, end) else: filtered = Reading.get_range(start, end) return create_readings_response(filtered) # parameters are missing response = jsonify({ 'error': 'Only the following queries are supported: count, sensor_id & count, start_time & end_time, sensor_id & start_time & end_time' }) response.status_code = 400 # Bad Request return response
def update_sensor(sensor_id): sensor = Sensor.get_by_id(sensor_id) if sensor is None: return not_found("Sensor not found") name_change = next(c for c in request.get_json() if { "op": "replace", "path": "/name" }.items() <= c.items()) if name_change is not None and "value" in name_change: sensor.name = name_change["value"] db.session.commit() return jsonify(sensor.to_json()), 200 return bad_request("Not able to parse any patch changes")
def test_update_sensor_when_sensor_exists_and_patch_changes_is_invalid(client): sensor = Sensor.create(id="the-id", name="the-name", sensor_type="temperature") res = client.patch( url_for("api.update_sensor", sensor_id=sensor.id), json=[{ "op": "replace", "path": "/name", "valu": "some-name" }], ) assert res.status_code == 400
def test_add_humidity_when_sensor_registered_as_other_type(client): sensor = Sensor.create(id="the-id", name="the-name", sensor_type="not-humidity") res = client.post( url_for("api.add_humidity"), json={ "timestamp": 1567447540, "sensor": sensor.id, "value": 75.2 }, ) assert res.status_code == 400