Пример #1
0
    def run():
        plant = Plant.get(localhost=True)

        # PARSE PARAMETERS
        temperature = {
            'sensor': Sensor.select().where(Sensor.name == 'temperature')[0],
            'plant': plant
        }
        humidity = {
            'sensor': Sensor.select().where(Sensor.name == 'humidity')[0],
            'plant': plant
        }

        if temperature['sensor'].model == humidity['sensor'].model:
            sensor = Adafruit_DHT.DHT22 if temperature[
                'sensor'].model == 'DHT22' else Adafruit_DHT.DHT11
        pin = 26

        # FETCH DATA FROM SENSOR
        humidity['value'], temperature['value'] = Adafruit_DHT.read_retry(
            sensor, pin)
        if humidity is not None and temperature is not None:
            toolchain = ToolChainSensor()

            if toolchain.insert_data(temperature):
                toolchain.set_hardware(temperature)

            if toolchain.insert_data(humidity):
                toolchain.set_hardware(humidity)
	def get(self):
		args = self.parser.parse_args()
		sensor, sensor_name, sensor_attribute = None, None, None


		if 'sensor' in args and args['sensor'] is not None:
			sensor = args['sensor']
			if sensor != '':
				if sensor == 'all':
					sensors = Sensor.get_all()
					return [a.json() for a in sensors], 200
				else:
					return (Sensor.get_by_id(sensor)).json(), 200

		if 'sensorname' in args and args['sensorname'] is not None:
			sensor_name = args['sensorname']
			if sensor_name != '':
				_sensors = sensor_name.split(',')
				_by_name = Sensor.get_by_name_in(_sensors)
				return [a.json() for a in _by_name], 200

		if 'sensorattribute' in args and args['sensorattribute'] is not None:
			sensor_attribute = args['sensorattribute']
			if sensor_attribute != '':
				_sen_attrs_ids = sensor_attribute.split(',')
				_sen_attrs = SensorAttribute.get_by_id_in(_sen_attrs_ids)
				attrs_ids = [_id.a_id for _id in _sen_attrs]
				_attributes = Attributes.get_by_id_in(attrs_ids)
				return [a.json() for a in _attributes], 200

		

		return {
			"error": "error occured while processing request"
		}, 400
Пример #3
0
def sensor(s_uuid):
  # GET: select: range, unit, full, default (full)
  try:
    sensor = Sensor.get(uuid=s_uuid)
  except Exception:
    sensor = Sensor.get(name=s_uuid)

  data, code = get_data(required=SENSOR_GET, restrictive=True, hardmode=True)
  if code == 400:
    return data_formatting(400)
  selector = data['select']
  collection = {}

  for selected in selector:
    if selected == 'full':
      output = model_to_dict(sensor)
      del output['id']
      output['uuid'] = str(output['uuid'])

    elif selected == 'range':
      output = {'max_value': sensor.max_value, 'min_value': sensor.min_value}

    else:
      output = {selected: model_to_dict(sensor)[selected]}

    if len(selector) > 1:
      collection[selected] = output

  if len(collection.keys()) != 0:
    output = collection
  return data_formatting(data=output)
Пример #4
0
 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()
Пример #5
0
def delete_all():
    Sample.objects.all().delete()
    Collect.objects().all().delete()
    LoanHistory.objects().all().delete()
    Equipment.objects().all().delete()
    Sensor.objects().all().delete()
    Patient.objects().all().delete()
    return jsonify({'message': 'deleted with success.'})
Пример #6
0
def delete_all():
    db.session.delete(Sample.query.all())
    Collect.objects().all().delete()
    LoanHistory.objects().all().delete()
    Equipment.objects().all().delete()
    Sensor.objects().all().delete()
    Patient.objects().all().delete()
    db.session.commit()
    return jsonify({'message': 'deleted with success.'})
Пример #7
0
class Startup:

    PATH_FICHERO = "./sensor.txt"
    CREAR_MEDIDA_CONSTANTE = '1'
    SALIR_CONSTANTE = '2'
    _sensor = None

    def __init__(self):
        lista_medidas = []
        tipo = "Sensor de temperatura"
        self._sensor = Sensor(tipo, lista_medidas)
        self.iniciar_bucle()

    def iniciar_bucle(self):
        fichero = self.__crear_en_fichero()
        print("----- BIENVENIDO ------------")
        string_entrada = None

        while (string_entrada != self.SALIR_CONSTANTE):
            string_entrada = self.mostrar_en_pantalla()
            if (string_entrada == self.CREAR_MEDIDA_CONSTANTE):
                fichero = self.__abrir_fichero(fichero)
                valor = input('Introduce el valor de la medida: ')
                unidad = input('Introduce el tipo de unidad: ')
                medida = Medida(valor, unidad)
                self._sensor.lista_medidas.append(medida)
                fichero = self.__escribir_y_cerrar(fichero)
            self._sensor.mostrar_sensor()

    def mostrar_en_pantalla(self):
        print("1 ---> CREAR MEDIDA")
        print("2 ---> SALIR")
        string_entrada = input('Introduce la opcion: ')
        return string_entrada

    def __crear_en_fichero(self):
        fichero = open(self.PATH_FICHERO, "w+")
        return fichero

    def __abrir_fichero(self, fichero):
        fichero = open(self.PATH_FICHERO, "a+")
        return fichero

    def __escribir_y_cerrar(self, fichero):
        fichero.write(str(self._sensor.tipo) + ":")
        for i in range(len(self._sensor.lista_medidas)):
            fichero.write(
                str(self._sensor.lista_medidas[i].str_medida() + "%d\r\n" %
                    (i + 1)))
        fichero.close()
        return fichero
Пример #8
0
def get_sensor_overall(s_uuid):
    sensor = Sensor.get(Sensor.uuid == s_uuid)
    sensor = model_to_dict(sensor)
    del sensor['id']
    sensor['uuid'] = str(sensor['uuid'])

    return json.dumps(sensor)
Пример #9
0
def get_current_satifaction():
    output = {}
    sensors = Sensor.select()
    for plant in Plant.select():
        host = None
        if plant.role != 'master':
            host = Plant.get(Plant.uuid == plant.role)

        statuses = []
        for sensor in sensors:
            selected = plant
            if sensor.name not in slave_supported and host is not None:
                selected = host

            status = SensorStatus.get(SensorStatus.sensor == sensor,
                                      SensorStatus.plant == selected)
            inserted = 1
            if status.level.label == 'threat':
                inserted = 3
            elif status.level.label == 'cautioning':
                inserted = 2
            statuses.append(inserted)

        maximum = max(statuses)
        label = 'optimum'
        if maximum == 3:
            label = 'threat'
        elif maximum == 2:
            label = 'cautioning'

        output[str(plant.uuid)] = {'streak': plant.sat_streak, 'name': label}

    return json.dumps(output)
Пример #10
0
def rango_tiempo_dia():
    sensor_id = request.query.sensor_id
    hora_inicio = request.query.hora_inicio
    hora_fin = request.query.hora_fin
    dia_medicion = request.query.dia_medicion
    return json.dumps(Sensor().rango_tiempo_dia(sensor_id, dia_medicion,
                                                hora_inicio, hora_fin))
Пример #11
0
  def run():
    result = VariousTools.offline_check('ledbar', hardware=True, pins=[0, 1, 2, 3, 4, 5], mcp=True)
    if result:
      sensor = Sensor.get(Sensor.name == 'moisture')
      plant = Plant.get(localhost=True)
      status = SensorStatus.get(SensorStatus.sensor == sensor,
                                SensorStatus.plant == plant)

      bus = 1
      gpio_count = 16
      address = 0x20

      mcp = MCP230XX_GPIO(bus, address, gpio_count)

      # green color port: 2, 1
      # yellow color port: 4, 3
      # red color port: 6, 5
      led = 0
      for i in [['threat', 6, 5], ['cautioning', 4, 3], ['optimum', 2, 1]]:
        if status.level.label == i[0]:
          led = i[2] if status.status is True else i[1]

      pins = [0, 1, 2, 3, 4, 5]
      for pin in pins:
        mcp.setup(pin, mcp.OUT)

      for i in range(0, led - 1):
        mcp.output(i, 0)  # Pin Low
        time.sleep(round((1.35**i) / 10, 3))

      for i in range(5, led - 2, -1):
        mcp.output(i, 1)  # Pin High
        time.sleep(round((1.35**i) / 10, 3))
Пример #12
0
    def run(samples=10):
        GPIO.setmode(GPIO.BCM)
        GPIO.setwarnings(False)
        GPIO.setup(4, GPIO.OUT)
        GPIO.output(4, True)
        time.sleep(1)

        values = []
        for i in range(0, samples):
            values.append(mcp3002().read_pct(0, 1))
            time.sleep(.2)
        print(values)
        GPIO.output(4, False)

        average = sum(values) / float(len(values))
        if average != 0:
            toolchain = ToolChainSensor()
            plant = Plant.get(localhost=True)

            moisture = {
                'sensor': Sensor.get(Sensor.name == 'moisture'),
                'plant': plant,
                'value': average
            }

            if toolchain.insert_data(moisture):
                toolchain.set_hardware(moisture)
Пример #13
0
 def simulate(self):
     target = Plant.get(Plant.localhost == True)
     source = Plant.get(Plant.name == 'marta')
     for sensor in Sensor.select():
         logger.info(sensor.name)
         PlantSimulate().run(target, sensor, source)
     logger.info('finished')
Пример #14
0
    def _create_datasource(self,
                           headers=json.loads(HEADERS_K.replace("'", '"'))):
        super()._create_datasource(headers)

        self.df = self.create_dataframe(object_separator=None)

        self.df['latitude'] = 0.
        self.df['longitude'] = 0.

        for i in range(0, len(self.df)):
            lid = Sensor.get_by_name_in(
                [self.df.parkingSpotSensorCode.iloc[i]])[0].l_id
            loc = location.Location.get_by_id_in([lid])[0]
            self.df.set_value(i, 'latitude', loc.lat)
            self.df.set_value(i, 'longitude', loc.lon)

        self.df['api_timestamp_tag'] = pd.to_datetime(self.df['datetime'])
        self.df['api_timestamp_tag'] = self.df['api_timestamp_tag'].astype(int)
        loc = Location('latitude', 'longitude')

        self.create_datasource(dataframe=self.df,
                               sensor_tag='parkingSpotSensorCode',
                               attribute_tag=['state'],
                               unit_value=[],
                               bespoke_unit_tag=[],
                               description=['No Description'],
                               bespoke_sub_theme=[],
                               location_tag=loc,
                               sensor_prefix='',
                               api_timestamp_tag='api_timestamp_tag')
    def _create_datasource(self, headers: Union[str, None] = None) -> None:
        """
        Create DataSource
        :param headers: Request Headers
        """
        try:
            super()._create_datasource(headers)
            self.df = self.create_dataframe(ignore_object_tags=['fieldAliases', 'fields'])

            names = self.df['lotcode'].tolist()
            name_set = set()
            location_sensor = {}
            sensor_location = {}
            latitude = []
            longitude = []

            for s in names:
                name_set.add('smart_parking_2_' + str(s))

            sensors = Sensor.get_by_name_in(name_set)
            loc_ids = []
            for s in sensors:
                loc_ids.append(s.l_id)
                location_sensor[s.l_id] = s
            locations = location.Location.get_by_id_in(loc_ids)

            for loc in locations:
                if loc.id in location_sensor:
                    _sensor = location_sensor[loc.id]
                    sensor_location[_sensor.name] = loc

            for s in names:
                _s = 'smart_parking_2_' + str(s)
                if _s in sensor_location:
                    latitude.append(sensor_location[_s].lat)
                    longitude.append(sensor_location[_s].lon)

            self.df['latitude'] = latitude
            self.df['longitude'] = longitude

            self.df.rename(index=str, columns={'free': 'free_2',
                                               'isoffline': 'isoffline_2',
                                               'occupied': 'occupied_2'},
                           inplace=True)

            loc = Location('latitude', 'longitude')
            self.create_datasource(dataframe=self.df, sensor_tag='lotcode',
                                   attribute_tag=['free_2', 'isoffline_2', 'occupied_2'],
                                   unit_value=[], bespoke_unit_tag=[], description=[], bespoke_sub_theme=[],
                                   location_tag=loc,
                                   sensor_prefix='smart_parking_2_', api_timestamp_tag='run_time_stamp',
                                   is_dependent=True)

            self.importer_status.status = Status.success(__class__.__name__)

        except Exception as e:

            self.importer_status.status = Status.failure(__class__.__name__, e.__str__(), traceback.format_exc())
Пример #16
0
def get_plant_sensor_data_high_ever(sensor, p_uuid, mode):
    configuration = True if mode == 'high' else False
    plant = Plant.get(Plant.uuid == p_uuid)
    sensor = Sensor.get(Sensor.name == sensor)

    if plant.role != 'master' and sensor.name not in slave_supported:
        plant = Plant.get(Plant.uuid == UUID(plant.role))

    return json.dumps(get_sensor_data_high_low(plant, sensor, configuration))
Пример #17
0
 def get_sensors(self):
     """
     :return:  list of sensors
     """
     url = "{}/sensors/".format(BASE_URL)
     results = self.r.get(url, headers=self._get_auth_header()).json()
     sensors = []
     for sensor in results['sensors']:
         sensors.append(Sensor(**sensor))
     return sensors
Пример #18
0
def sensors():
  # GET: select: minimal, normal, detailed, extensive, default (normal)
  # GET: dict: Boolean
  selectable = ['minimal', 'normal', 'detailed', 'extensive']
  data, code = get_data(required=SENSORS_GET, restrictive=True, hardmode=True)
  if code == 400:
    return data_formatting(400)

  mode = data['dict']
  selector = data['select']
  sensors = Sensor.select().dicts()
  collection = {}

  for selected in selector:
    output = []

    if selected not in selectable:
      return data_formatting(400)

    for sensor in list(sensors):
      used = []
      if selected in selectable:
        used.append('uuid')

      if selected in selectable[1:]:
        used.append('name')

      if selected in selectable[2:]:
        used.append('unit')
        used.append('model')

      if selected in selectable[3:]:
        used.append('persistant_offset')
        used.append('min_value')
        used.append('max_value')

      data = [] if not mode else {}
      for use in used:
        if isinstance(sensor[use], UUID):
          sensor[use] = str(sensor[use])

        if not mode:
          data.append(sensor[use])
        else:
          data[use] = sensor[use]
      output.append(data)

    if len(selector) > 1:
      collection[selected] = output

  if len(collection.keys()) != 0:
    output = collection

  return data_formatting(data=output)
Пример #19
0
def get_plant_count(p_uuid, sensor):
    plant = Plant.get(Plant.uuid == p_uuid)
    sensor = Sensor.get(Sensor.name == sensor)
    if plant.role != 'master' and sensor.name not in slave_supported:
        plant = Plant.get(Plant.uuid == UUID(plant.role))

    sensor_data_set = SensorData.select() \
                                .where(SensorData.plant == plant) \
                                .where(SensorData.sensor == sensor)

    return json.dumps({'count': sensor_data_set.count()})
Пример #20
0
    def _create_datasource(self, headers: Union[str, None] = None) -> None:
        """
        Create DataSource
        :param headers: Request Headers
        """
        try:
            if not headers:
                headers = json.loads(self.HEADERS.replace("'", '"'))

            super()._create_datasource(headers)

            self.df = self.create_dataframe(object_separator=None)
            names = self.df['dev_eui'].tolist()
            name_set = set()
            location_sensor = {}

            for s in names:
                name_set.add(str(s))

            sensors = Sensor.get_by_name_in(name_set)
            loc_ids = []
            for s in sensors:
                loc_ids.append(s.l_id)
                location_sensor[s.l_id] = s
                locations = location.Location.get_by_id_in(loc_ids)

            d = dict(zip([n.name for n in sensors], locations))

            self.df['latitude'] = self.df['dev_eui'].apply(
                lambda x: d.get(x).lat)
            self.df['longitude'] = self.df['dev_eui'].apply(
                lambda x: d.get(x).lon)
            self.df['api_timestamp_tag'] = pd.to_datetime(self.df['data'])
            self.df['api_timestamp_tag'] = self.df['api_timestamp_tag'].astype(
                int)

            loc = Location('latitude', 'longitude')

            self.create_datasource(
                dataframe=self.df,
                sensor_tag='dev_eui',
                attribute_tag=['pressione', 'temperatura', 'umidita'],
                unit_value=[],
                bespoke_unit_tag=[],
                description=['No Description'],
                bespoke_sub_theme=[],
                location_tag=loc,
                sensor_prefix='',
                api_timestamp_tag='api_timestamp_tag')
            self.importer_status.status = Status.success(__class__.__name__)
        except Exception as e:
            self.importer_status.status = Status.failure(
                __class__.__name__, e.__str__(), traceback.format_exc())
Пример #21
0
def get_plant_sensor_data(p_uuid, sensor):
    plant = Plant.get(Plant.uuid == p_uuid)
    sensor = Sensor.get(Sensor.name == sensor)

    if plant.role != 'master' and sensor.name not in slave_supported:
        plant = Plant.get(Plant.uuid == UUID(plant.role))

    sensor_data_set = SensorData.select(SensorData.value, fn.CAST(Clause(fn.strftime('%s', SensorData.created_at), SQL('AS INT'))).alias('timestamp')) \
                                .where(SensorData.plant == plant) \
                                .where(SensorData.sensor == sensor) \
                                .order_by(SensorData.created_at.asc())

    content = list(sensor_data_set)
    return json.dumps(content)
Пример #22
0
def insert_sensor_data(json, status):
    try:
        insert = Sensor(regiao=json['tag'].split('.')[1],
                        timestamp=datetime.fromtimestamp(
                            json['timestamp'],
                            pytz.timezone("America/Sao_Paulo")),
                        tag=json['tag'],
                        valor=json['valor'],
                        status=status)

        session.add(insert)
        session.commit()
        session.refresh(insert)
    except Exception as err:
        print(err)
        session.rollback()
Пример #23
0
def plant_sensors(p_uuid):
    # GET: select: range (default), default
    plant = Plant.get(uuid=p_uuid)
    data, code = get_data(required=PLANT_SENSORS_GET,
                          restrictive=True,
                          hardmode=True)
    if code == 400:
        return data_formatting(400)

    selector = data['select']
    collection = {}

    for selected in selector:
        if selected == 'range':
            sensors = Sensor.select()

            output = []
            for sensor in sensors:
                ranges = SensorSatisfactionValue.select() \
                                                .where(SensorSatisfactionValue.plant == plant) \
                                                .where(SensorSatisfactionValue.sensor == sensor)

                tmp = {}
                for spectrum in ranges:
                    tmp[spectrum.level.name_color] = {
                        'max': spectrum.max_value,
                        'min': spectrum.min_value
                    }
                    if spectrum.level.name_color == 'red':
                        tmp[spectrum.level.name_color] = {
                            'max': sensor.max_value,
                            'min': sensor.min_value
                        }
                output.append({
                    'settings': tmp,
                    'sensor': sensor.name,
                    'uuid': str(sensor.uuid)
                })

        if len(selector) > 1:
            collection[selected] = output

    if len(collection.keys()) != 0:
        output = collection

    return data_formatting(data=output)
Пример #24
0
def get_plant_data_selective(p_uuid, sensor, start, stop):
    plant = Plant.get(uuid=p_uuid)
    sensor = Sensor.get(name=sensor)

    if plant.role != 'master' and sensor.name not in slave_supported:
        plant = Plant.get(uuid=plant.role)

    dataset = SensorData.select(SensorData.value, fn.CAST(Clause(fn.strftime('%s', SensorData.created_at), SQL('AS INT'))).alias('timestamp')) \
                        .where(SensorData.plant == plant) \
                        .where(SensorData.sensor == sensor) \
                        .order_by(SensorData.created_at.desc()) \
                        .offset(start) \
                        .limit(stop - start) \
                        .dicts()

    dataset = list(dataset)
    return json.dumps(dataset)
Пример #25
0
    def _create_datasource(self, headers=None):
        super()._create_datasource(headers)
        self.df  = self.create_dataframe(ignore_object_tags=['fieldAliases', 'fields'])

        names = self.df['lotcode'].tolist()
        name_set = set()
        location_sensor = {}
        sensor_location = {}
        latitude = []
        longitude = []

        for s in names:
            name_set.add('smart_parking_2_' + str(s))

        sensors = Sensor.get_by_name_in(name_set)
        loc_ids = []
        for s in sensors:
            loc_ids.append(s.l_id)
            location_sensor[s.l_id] = s
        locations = location.Location.get_by_id_in(loc_ids)

        for loc in locations:
            if loc.id in location_sensor:
                _sensor = location_sensor[loc.id]
                sensor_location[_sensor.name] = loc
       
        for s in names:
            _s = 'smart_parking_2_' + str(s)
            if _s in sensor_location:
                latitude.append(sensor_location[_s].lat)
                longitude.append(sensor_location[_s].lon)

        self.df['latitude'] = latitude
        self.df['longitude'] = longitude

        ### Renaming the columns so that they are not confused with GreenwichOCC
        self.df.rename(index=str, columns={'free': 'free_2',
                       'isoffline': 'isoffline_2',
                       'occupied' : 'occupied_2'}, 
                      inplace=True)

        loc = Location('latitude', 'longitude')
        self.create_datasource(dataframe= self.df, sensor_tag='lotcode', attribute_tag=['free_2', 'isoffline_2', 'occupied_2'], 
                                unit_value=[], bespoke_unit_tag=[], description=[], bespoke_sub_theme=[], location_tag=loc,
                                sensor_prefix='smart_parking_2_', api_timestamp_tag='run_time_stamp', is_dependent=True)
Пример #26
0
def get_plant_sensor_prediction(p_uuid, sensor):
    plant = Plant.get(Plant.uuid == p_uuid)
    sensor = Sensor.get(Sensor.name == sensor)

    if plant.role != 'master' and sensor.name not in slave_supported:
        plant = Plant.get(Plant.uuid == UUID(plant.role))

    sensor_prediction_set = SensorDataPrediction.select(SensorDataPrediction.value, SensorDataPrediction.time) \
                                                .where(SensorDataPrediction.plant == plant) \
                                                .where(SensorDataPrediction.sensor == sensor) \
                                                .order_by(SensorDataPrediction.created_at.asc()) \
                                                .dicts()
    sensor_prediction_set = list(sensor_prediction_set)
    for prediction in sensor_prediction_set:
        prediction['timestamp'] = prediction['time'].timestamp()
        del prediction['time']

    return json.dumps(sensor_prediction_set)
Пример #27
0
def get_latest_dataset(p_uuid, s_uuid):
    plant = Plant.get(Plant.uuid == p_uuid)
    sensor = Sensor.get(Sensor.name == s_uuid)

    if plant.role != 'master' and sensor.name not in slave_supported:
        plant = Plant.get(Plant.uuid == UUID(plant.role))

    sd = SensorData.select(SensorData.value,
                           SensorData.persistant,
                           fn.CAST(Clause(fn.strftime('%s', SensorData.created_at), SQL('AS INT'))).alias('timestamp')) \
                   .where(SensorData.plant == plant) \
                   .where(SensorData.sensor == sensor) \
                   .order_by(SensorData.created_at.desc()) \
                   .limit(1) \
                   .dicts()

    selected = list(sd)[0]
    return json.dumps(selected)
Пример #28
0
def get_plant_sensor_data_after(p_uuid, sensor, until):
    sensor = Sensor.get(Sensor.name == sensor)
    plant = Plant.get(Plant.uuid == p_uuid)

    if plant.role != 'master' and sensor.name not in slave_supported:
        plant = Plant.get(Plant.uuid == UUID(plant.role))

    date_time = datetime.datetime.fromtimestamp(until + 1)
    sensor_data_set = SensorData.select(SensorData.value,
                                        fn.CAST(Clause(fn.strftime('%s', SensorData.created_at), SQL('AS INT'))).alias('timestamp')) \
                                .where(SensorData.plant == plant) \
                                .where(SensorData.sensor == sensor) \
                                .where(SensorData.created_at > date_time) \
                                .order_by(SensorData.created_at.asc()) \
                                .dicts()

    sensor_data_set = list(sensor_data_set)
    return json.dumps(sensor_data_set)
Пример #29
0
def get_plant_current_sensor_data(p_uuid, sensor):
    plant = Plant.get(Plant.uuid == p_uuid)
    sensor = Sensor.get(Sensor.name == sensor)

    if plant.role != 'master' and sensor.name not in slave_supported:
        plant = Plant.get(Plant.uuid == UUID(plant.role))

    latest = SensorData.select() \
                       .where(SensorData.plant == plant) \
                       .where(SensorData.sensor == sensor) \
                       .order_by(SensorData.created_at.desc())[0]

    latest = model_to_dict(latest)
    del latest['id']
    del latest['plant']
    del latest['sensor']

    return json.dumps(latest, default=json_util.default)
Пример #30
0
    def _create_datasource(self,
                           headers=json.loads(HEADERS_SM.replace("'", '"'))):
        super()._create_datasource(headers)

        self.df = self.create_dataframe(object_separator=None)
        names = self.df['dev_eui'].tolist()
        name_set = set()
        location_sensor = {}
        sensor_location = {}
        sensor_name_location = {}

        latitude = []
        longitude = []

        for s in names:
            name_set.add(str(s))

        sensors = Sensor.get_by_name_in(name_set)
        loc_ids = []
        for s in sensors:
            loc_ids.append(s.l_id)
            location_sensor[s.l_id] = s
            locations = location.Location.get_by_id_in(loc_ids)

        d = dict(zip([n.name for n in sensors], locations))

        self.df['latitude'] = self.df['dev_eui'].apply(lambda x: d.get(x).lat)
        self.df['longitude'] = self.df['dev_eui'].apply(lambda x: d.get(x).lon)
        self.df['api_timestamp_tag'] = pd.to_datetime(self.df['data'])
        self.df['api_timestamp_tag'] = self.df['api_timestamp_tag'].astype(int)

        loc = Location('latitude', 'longitude')

        self.create_datasource(
            dataframe=self.df,
            sensor_tag='dev_eui',
            attribute_tag=['pressione', 'temperatura', 'umidita'],
            unit_value=[],
            bespoke_unit_tag=[],
            description=['No Description'],
            bespoke_sub_theme=[],
            location_tag=loc,
            sensor_prefix='',
            api_timestamp_tag='api_timestamp_tag')