def test_send_message(self): headers = {'Device-ID': 'BLABLA'} # Without sending the data we expect a BadRequest response response = self.client.post("/send", headers=headers) self.assert400(response) # Since the device isn't in the database we expect a 404 headers['Content-Type'] = 'application/json' response = self.client.post("/send", headers=headers, data='{"message": "test"}') self.assert404(response) Device(device_id=headers['Device-ID'], receiver_id='TEST').save() Device(device_id='TEST', receiver_id=headers['Device-ID']).save() response = self.client.post("/send", headers=headers, data='{"message": "test"}') self.assert200(response) inserted_message = Device.objects(device_id='TEST').first().messages[0] self.assertIsNotNone(inserted_message) self.assertEqual(inserted_message.message, 'test') headers.pop('Content-Type', None) response = self.client.get('/ping', headers={ 'Firmware-Version': '1', 'Device-ID': 'TEST' }) self.assert200(response) try: data = json.loads(response.data) self.assertEqual(data['message'], 'test') except ValueError: self.assertTrue(False, 'No json is returned from the ping request')
def run(self): self.register_routes() self.database_connect() # Fake data because of quick prototype :) Device(device_id="test1234", receiver_id="test").save() Device(device_id="test", receiver_id="test1234").save() self.app.run(debug=True, host='0.0.0.0', port=8888) return self.app
def patch_device(device_id): assert(request.headers['Content-Type'] == 'application/json') updated_device = request.json f = Device().toFullDict() g = copy(f) for k in f: if k in updated_device: g[k] = updated_device[k] print("updating ", device_id, " to ", g) device = device_repo.patch_device(device_id, Device(**g)) return jsonify(device.toFullDict())
def computedevice(request): """HTTP Cloud Function. Parameters: request (flask.Request): The request object. if in query string the x and y are present as valid coordinates it will process that point otherwise if no args are passed in the query string it will process the standard points (0,0), (100, 100), (15,10) and (18, 18). <http://flask.pocoo.org/docs/1.0/api/#flask.Request> Returns: A json array compose by the strings: “Best link station for point x,y is x,y with power z” Or “No link station within reach for point x,y” """ # All the print are logged automatically on stackdriver x_args = request.args.get('x') y_args = request.args.get('y') if not x_args or not y_args: print('the query string is not in the expected format or is empty', request) devices_to_process = [ Device(0, 0), Device(100, 100), Device(15, 10), Device(18, 18) ] else: try: x = float(x_args) y = float(y_args) except ValueError as vError: print('the x and y params inputs are not valid coordinates', vError) return 'the X and Y inputs are not valid coordinates (float)' else: devices_to_process = [Device(x, y)] results = [] for device_to_process in devices_to_process: max_power, station_point = compute.process_suitable_link( device_to_process) if (max_power > 0): result = f'Best link station for point {device_to_process.get_x()},{device_to_process.get_y()} is {station_point[0]},{station_point[1]} with power {max_power}' else: result = f'No link station within reach for point {device_to_process.get_x()},{device_to_process.get_y()}' print(result) results.append(result) # flask.jsonify doesn't allow to serialize list # https://github.com/pallets/flask/issues/170 return make_response(dumps(results))
def post(self): data = dict() args = post_parser.parse_args() try : appVersion = AppVeriosn() minv, recentv = appVersion.getLatestVersion() deviceModel = Device() device = deviceModel.getDeviceByDeviceId(args) if args['token'] == device.token.token and datetime.now() < device.token.expiry: fb_url = "https://graph.facebook.com/me?access_token="+device.token.fb_token+"&fields=id,email,first_name,last_name,name,gender" res = requests.get(fb_url) if res.status_code == 200 : device.token.updateToken(device.token.id, False) data['token'] = device.token.token data['min'] = minv data['recent'] = recentv userModel = User() user = userModel.getUserById({'id' : device.user_id}) user = sqlAlchemyObjToDict(user) data.update(user) else: raise ErrorWithCode(401, 'Facebook access token is not valid.') else: raise ErrorWithCode(401, 'Token is invalid.') return marshal(data, resource_fields), 200 except Exception, e: data['message'] = str(e) return data, e.code if hasattr(e, 'code') else 500
def index(): """ Method associated to both routes '/' and '/index' and accepts post requests for when a user logs in. Updates the user of the session to the person who logged in. Also populates 3 tables for game invites, games in progress, and games finished by the logged in user (if there is one). """ if request.method == "POST": return redirect('/index') matchingDevices = controller.getDevicesWithQuery("CardioCare") print Device(matchingDevices[0]) results = [Device(device) for device in matchingDevices] return render_template("index.html", results=results)
def create_fixtures(self): """Create a device with two sensors.""" self.device1 = Device(name="ToF-1") self.sensor1 = Sensor(name="S-1", device=self.device1) self.sensor2 = Sensor(name="S-2", device=self.device1) self.session.add_all([self.device1, self.sensor1, self.sensor2]) self.session.commit()
def test_device_100_100(self): max_power, station_point = self.compute.process_suitable_link( Device(100, 100)) self.assertEqual( max_power, 0, msg='there is not a most suitable link to device(100, 100)')
def add_device(): device_data = devices_schema.load(request.json) for device in device_data: new_device = Device(**device) db.session.add(new_device) db.session.commit() return jsonify({"Devices added": len(device_data)})
def register_device(json_req, user): device_type = json_req['deviceType'] device_desc = json_req['deviceDescription'] device_code = json_req['deviceCode'] fcm_id = json_req['fcmID'] if device_type not in (ANDROID, IOS, OTHERS): raise ValueError('Invalid deviceType') if fcm_id and fcm_id.strip(): fcm_id = fcm_id.strip() else: raise ValueError('Invalid FCM ID') user_id = user.UserID device = db_session.query(Device).filter_by(DeviceType=device_type, UserID=user_id).first() if device: device.DeviceDesc = device_desc device.DeviceCode = device_code device.FcmID = fcm_id db_session.commit() else: new_device = Device(DeviceType=device_type, DeviceDesc=device_desc, DeviceCode=device_code, UserID=user_id, FcmID=fcm_id) db_session.add(new_device) db_session.commit() return jsonify(status=1, message='success')
def test_device_not_found(self): response = self.client.get('/ping', headers={ 'Firmware-Version': '1', 'Device-ID': 'ABC' }) self.assert404(response) device = Device(device_id='ABC', receiver_id='CBA').save() response = self.client.get('/ping', headers={ 'Firmware-Version': '1', 'Device-ID': device.device_id }) self.assert200(response) try: data = json.loads(response.data) self.assertFalse('message' in data) except ValueError: self.assertTrue(False, "The ping request didn't return json") device.messages = [Message(message='This is a test')] device.save() response = self.client.get('/ping', headers={ 'Firmware-Version': '1', 'Device-ID': device.device_id }) self.assert200(response) try: data = json.loads(response.data) self.assertEqual(data['message'], 'This is a test') except ValueError: self.assertTrue(False, "The ping request didn't return json")
def validateToken(token): deviceModel = Device() device = deviceModel.getDevice({'token': token}) if device is None: raise ValueError("This is an invalid token.") data = dict() data['device'] = device return data
def get_user_input_device(): user_input_x = input('Enter the X for the device you want to process: ') user_input_y = input('Enter the Y for the device you want to process: ') try: x = float(user_input_x) y = float(user_input_y) return Device(x, y) except ValueError: print('The inputs are not valid coordinates') return sys.exit(0)
def get_devices_on_network(self) -> List[Device]: devices: List[Device] = [] devices_str = os.popen('arp -a') for line in devices_str: words = line.split(' ') d = Device(ip=words[0], ip_local=self.remove_par(words[1]), mac_address=words[3]) devices.append(d) return devices
def get_device(self, device_id): s = self.database.child('devices').child(device_id).get().val() if s is None: return None else: return Device(area_id=s['area_id'], id=device_id, name=s['name'], position=s['position'], mac=s['mac'])
def handleBatteryUpdate(item): device = Device.get_device(item['device_id']) if not device: device = Device(item['device_id'], item['recorded_at']) db.session.add(device) battery_status = item['data']['value'] recorded_at = item['recorded_at'] return device.update_battery_status(battery_status, recorded_at)
def connect_device(): mac = request.form['scanned'] user = current_user # add device into database if not added before if not Device.objects(mac=mac).first(): device = Device(mac=mac, owner=User.objects(email=user.email).first()) device.save() result = app.hub.connectDevice(mac) return json.dumps({'success': result}), 200, { 'ContentType': 'application/json' }
def get_devices(self): devices = self.database.child('devices').get() devices = [ Device(area_id=device.val()['area_id'], id=device.key(), name=device.val()['name'], position=device.val()['position'], mac=device.val()['mac']) for device in devices.each() if device.val() is not None ] return devices
def handle_robot_app_deployed(json): print('received json: ' + str(json)) logging.warning(json) json = loads(json) pkg = json["package"] ver = json["version"] serial = json["serial"] imei = json.get("imei") wifi_mac = json.get("wifi_mac") ext_ip = json.get("ext_ip") lan_ip = json.get("lan_ip") dev = Device(serial=serial, imei=imei, wifi_mac=wifi_mac, ext_ip=ext_ip, lan_ip=lan_ip) appstore.notice_device_app(dev, pkg, ver)
def handleLocationUpdate(item): device = Device.get_device(item['device_id']) if not device: device = Device(item['device_id'], item['recorded_at']) db.session.add(device) recorded_at = item['recorded_at'] data = item['data'] geometry = data['geometry'] location_type = geometry['type'] longitude = geometry['coordinates'][0] latitude = geometry['coordinates'][1] altitude = geometry['coordinates'][2] return device.update_location(location_type, longitude, latitude, altitude, recorded_at)
def test__model__device__serialize(self): device = Device(uuid="unique device identifier", name="a nice device", owner="the owner", powered_on=True) expected_result = { "uuid": "unique device identifier", "name": "a nice device", "owner": "the owner", "powered_on": True, } serialized = device.serialize self.assertEqual(expected_result, serialized) serialized["name"] = "other name" self.assertEqual(expected_result, device.serialize)
def post(self, *args, **kwargs): data = json.loads(self.request.body.decode("utf-8")) nickname = self.get_current_nickname() ip = data.get('ip', None) buy_time = data.get('buy_time', '') device_brand = data.get('device_brand', '') device_id = data.get('idc', '') device_ip = data.get('device_ip', '') device_place = data.get('device_place', '') device_sn = data.get('device_sn', '') device_softs = data.get('device_softs', '') device_type = data.get('device_type', '') maintenance_company = data.get('maintenance_company', '') maintenance_et = data.get('maintenance_et', '') maintenance_st = data.get('maintenance_st', '') # if not hostname or not ip or not port: # return self.write(dict(code=-1, msg='关键参数不能为空')) # # if not check_ip(ip): # return self.write(dict(code=-1, msg="IP格式不正确")) with DBContext('r') as session: exist_id = session.query(Device.id).filter(Device.device_id == device_id).first() exist_sn = session.query(Device.id).filter(Device.device_sn == device_sn).first() if exist_id or exist_sn: return self.write(dict(code=-2, msg='不要重复记录')) with DBContext('w', None, True) as session: new_device = Device(buy_time=datetime.now(), device_brand=device_brand, device_id=device_id, device_ip=device_ip, device_place=device_place, device_sn=device_sn, device_type=device_type, maintenance_company=maintenance_company, maintenance_et=datetime.now(), maintenance_st=datetime.now()) session.add(new_device) all_soft = session.query(Soft.id).filter(Soft.soft_name.in_(device_softs)).order_by(Soft.id).all() # print('all_tags', all_tags) if all_soft: for soft_id in all_soft: session.add(DeviceSoft(device_id=new_device.id, soft_id=soft_id[0])) session.commit() return self.write(dict(code=0, msg='添加成功'))
def test_device_20_20(self): max_power, station_point = self.compute.process_suitable_link( Device(20, 20)) self.assertEqual(max_power, 25, msg='wrong max_power calculation for device(20,20)') # another option would be to use np.testing.assert_array_equal self.assertEqual( station_point[0], 20, msg= 'the X coordinate station is not the most suitable for device(20,20)' ) self.assertEqual( station_point[1], 20, msg= 'the Y coordinate station is not the most suitable for device(20,20)' )
def post(self): data = dict() args = post_parser.parse_args() try: userModel = User() tokenModel = Token() deviceModel = Device() appVersion = AppVeriosn() minv, recentv = appVersion.getLatestVersion() user = userModel.isUserExist(args) if user: device = None for d in user.devices: if args['device_id'] == d.device_id: device = d break if device is None: token = tokenModel.createNewToken(args) args['user_id'] = user.id args['token_id'] = token.id newDevice = deviceModel.addDevice(args) else: device.token.updateToken(device.token.id, True, args) token = device.token data = {"token": token.token} user = sqlAlchemyObjToDict(user) data.update(user) else: newUser = userModel.addUser(args) newToken = tokenModel.createNewToken(args) args['user_id'] = newUser.id args['token_id'] = newToken.id newDevice = deviceModel.addDevice(args) data = {"token": newToken.token} newUser = sqlAlchemyObjToDict(newUser) data.update(newUser) data['min'] = minv data['recent'] = recentv return marshal(data, resource_fields), 200 except Exception, e: data['message'] = str(e) return data, 400
def post(self): if not request.data: abort(400, 'json required') data = request.get_json() uuid_check = Device.query.filter_by(uuid=data['uuid']).first() if uuid_check: return {'message': 'UUID already in use'}, 400 uuid = data['uuid'] name = data['name'] type = data['type'] device = Device(name, type, uuid) db.session.add(device) db.session.commit() result = device_schema.dump(device) return {'status': 'succcess', 'data': result}, 201
def create_device(): data = request.get_json() deviceid = data['deviceid'] socketid = None if 'socketid' in data: socketid = data['socketid'] if Device.find_by_deviceid(deviceid): return { 'message': f"Existe un medidor con el identificador '{deviceid}'." }, 500 device = Device(deviceid, data['brand'], data['model'], data['serial'], socketid) try: device.save_to_db() except Exception: return {"message": "ocurrio un error en la creacion del medidor."}, 500 return device.json(), 201
def put(self): data = dict() args = post_parser.parse_args() try: deviceModel = Device() device = deviceModel.getDevice(args) imgfile = args['image'] ext = fileAllowed(imgfile.filename) if ext is None: raise ErrorWithCode(403, "File type not allowed") imagename = md5(datetime.now().strftime( "%b%d%Y%h%m%s%f")).hexdigest() + "." + ext workingdir = os.getcwd() imagePath = os.path.join(workingdir, 'images', imagename) imgfile.save(imagePath) self.resizeImage(imagePath) data['imagename'] = imagename return data, 200 except Exception, e: data['message'] = str(e) return data, e.code if hasattr(e, 'code') else 500
def init_all(session): # TODO: init from json or csv file plant = Plant(name=u"Plant") session.add(plant) device = Device(name="Raspberry Pi") session.add(device) session.commit() for factor in PlantGrowthFactor: channel = DeviceChannel(device_id=device.id) session.add(channel) session.commit() plant_factor = PlantFactor(plant_id=plant.id, factor_type=factor, channel_id=channel.id) session.add(plant_factor) session.commit() pump_controller = DeviceController(device_id=device.id, controller_type=PlantControllerType.PUMP) session.add(pump_controller) led_controller = DeviceController(device_id=device.id, controller_type=PlantControllerType.LED) session.add(led_controller) session.commit()
def register(): uuid = request.form.get('uuid') public_key = request.form.get('public_key') name = request.form.get('name') message_type = request.form.get('message_type') error = None if not uuid: error = 'uuid is required.' elif not name: error = 'name is required.' elif not message_type: error = 'message_type is required.' elif Device.query.filter(Device.uuid == uuid).first() is not None: error = 'uuid {} is already registered.'.format(uuid) if error is None: device = Device(uuid=uuid, public_key=public_key, name=name, message_type=message_type) db.session.add(device) db.session.commit() return jsonify(device.dict()) return 'Registration Failed: {}'.format(error)
def get(self): data = dict() args = parser.parse_args() try: deviceModel = Device() device = deviceModel.getDevice(args) lat_lng = args['lat_lng'] lat = lat_lng.split(',')[0].strip() lng = lat_lng.split(',')[1].strip() locationModel = Location() data['inlocation'] = locationModel.getLocationFromPosition({ 'lat': lat, 'lng': lng }) data['avllocation'] = locationModel.getAllLocations() return marshal( data, resource_fields), 404 if data['inlocation'] is None else 200 except Exception, e: data['message'] = str(e) return data, e.code if hasattr(e, 'code') else 500