Exemple #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)
Exemple #2
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')
Exemple #3
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)
Exemple #4
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)
Exemple #5
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)
Exemple #6
0
def get_current_sensor_satifaction():
    output = {}
    sensors = Sensor.select()
    for plant in Plant.select():
        host = None
        if plant.role != 'master':
            host = Plant.get(Plant.uuid == plant.role)

        output[str(plant.uuid)] = {}
        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)
            if status.level.label not in output[str(plant.uuid)]:
                output[str(plant.uuid)][status.level.label] = []

            output[str(plant.uuid)][status.level.label].append(sensor.name)

    return json.dumps(output)
Exemple #7
0
def get_plant_sensors_range(p_uuid):
    plant = Plant.get(Plant.uuid == p_uuid)
    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})

    return json.dumps(output)
Exemple #8
0
def get_sensor_status_average_percent(p_uuid):
    plant = Plant.get(Plant.uuid == p_uuid)
    c = Sensor.select().count()
    sensor_count = SensorCount.select() \
                              .where(SensorCount.plant == plant)

    average = {'red': 0, 'yellow': 0, 'green': 0}

    for count in sensor_count:
        average[count.level.name_color] += count.count

    summary = 0
    for key, item in average.items():
        average[key] /= c
        summary += average[key]

    output = {}
    for key, item in average.items():
        try:
            output[key] = [round(item / summary * 100), item]
        except ZeroDivisionError:
            output[key] = [0, item]

    return json.dumps(output)
Exemple #9
0

def model(sensor):
    model_str = input('model: ')

    if sensor == 'temperature' or sensor == 'humidity':
        if model_str != 'DHT22' and model_str != 'DHT11':
            print(
                'temperature valid values - DHT11 and DHT22, pls try again\n')
            model(sensor)

    return model_str


for sensor in ['temperature', 'light', 'humidity', 'moisture']:
    if Sensor.select().where(Sensor.name == sensor).count() == 0:
        print('\n\nCREATE {}: \n\n'.format(sensor.upper()))
        db_sensor = Sensor()
        db_sensor.name = sensor
        db_sensor.model = model(sensor)
        db_sensor.unit = input('unit (only for display) ')
        db_sensor.min_value = input('minimum value? ')
        db_sensor.max_value = input('maximum value? ')
        db_sensor.persistant_offset = input('to persistant offset? ')

        db_sensor.save()

all_sensors = ['temperature', 'light', 'humidity', 'moisture']
if SensorHardware.select().count() == 0:
    print('doing some other stuff')
    hardware_collection = {
Exemple #10
0
def plant_status(p_uuid):
    # GET: select: average, online
    plant = Plant.get(uuid=p_uuid)
    data, code = get_data(required=PLANT_STATUS_GET, restrictive=True)
    if code == 400:
        return data_formatting(400)
    selector = data['select']
    collection = {}

    for selected in selector:
        if selected == 'average':
            c = Sensor.select().count()
            sensor_count = SensorCount.select() \
                                      .where(SensorCount.plant == plant)

            average = {'red': 0, 'yellow': 0, 'green': 0}

            for count in sensor_count:
                average[count.level.name_color] += count.count

            summary = 0
            for key, item in average.items():
                average[key] /= c
                summary += average[key]

            output = {}
            for key, item in average.items():
                try:
                    output[key] = [round(item / summary * 100), item]
                except ZeroDivisionError:
                    output[key] = [0, item]
        else:
            uptimes = PlantNetworkUptime.select() \
                                        .where(PlantNetworkUptime.plant == plant)

            output = {}
            summary = 0

            for uptime in uptimes:
                output[uptime.status.name] = [
                    0, uptime.overall, uptime.current
                ]
                summary += uptime.overall

            for key, uptime in output.items():
                print(type(output[key][1]))
                output[key][0] = round(output[key][1] / summary *
                                       100) if output[key][1] != 0 else 0

            if output == {}:
                output = {'online': [0, 0.0, 0.0], 'offline': [0, 0.0, 0.0]}

            if plant.localhost:
                output = {'online': [100, 1, 1], 'offline': [100, 1, 1]}

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

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

    return data_formatting(data=output)
Exemple #11
0
def plants():
    # GET: select: minimal, normal, detailed, extensive, master, satisfaction, default (normal)
    # GET: dict: Boolean
    if request.method == 'GET':
        data, code = get_data(required=PLANTS_GET,
                              restrictive=True,
                              hardmode=True)
        if code == 400:
            return data_formatting(400)

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

        for selected in selector:
            plants = root_plants.where(
                Plant.role ==
                'master') if selected == 'master' else root_plants
            plants = list(plants)

            output = []
            if selected not in ['satisfaction', 'sensorsatisfaction']:
                for plant in plants:
                    used = []
                    if selected in [
                            'minimal', 'normal', 'detailed', 'extensive',
                            'master'
                    ]:
                        used.append('uuid')

                    if selected in [
                            'normal', 'detailed', 'extensive', 'master'
                    ]:
                        used.append('name')

                    if selected in ['detailed', 'extensive', 'master']:
                        used.append('role')
                        used.append('localhost')

                    if selected in ['extensive', 'master']:
                        used.append('active')

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

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

            elif selected in ['satisfaction', 'sensorsatisfaction']:
                output = {}
                sensors = Sensor.select()
                for plant in plants:
                    host = None
                    if plant['role'] != 'master':
                        host = Plant.get(Plant.uuid == plant['role'])

                    if selected == 'satisfaction':
                        statuses = []
                    else:
                        output[str(plant['uuid'])] = {}

                    for sensor in sensors:
                        target = Plant.get(uuid=plant['uuid'])
                        if sensor.name not in slave_supported and host is not None:
                            target = host

                        status = SensorStatus.get(
                            SensorStatus.sensor == sensor,
                            SensorStatus.plant == target)
                        if selected == 'satisfaction':
                            inserted = 1
                            if status.level.label == 'threat':
                                inserted = 3
                            elif status.level.label == 'cautioning':
                                inserted = 2
                            statuses.append(inserted)
                        else:
                            if status.level.label not in output[str(
                                    plant['uuid'])]:
                                output[str(
                                    plant['uuid'])][status.level.label] = []

                            output[str(
                                plant['uuid'])][status.level.label].append({
                                    'name':
                                    sensor.name,
                                    'uuid':
                                    str(sensor.uuid)
                                })

                    if selected == 'satisfaction':
                        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
                        }

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

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

        return data_formatting(data=output)
    else:
        # PUT: register: true
        data, code = get_data(required=PLANTS_PUT, restrictive=True)
        if code == 400:
            return data_formatting(400)
        register = data['register']

        plants = list(Plant.select(Plant.ip == data['ip']).dicts())

        discovered = MeshObject.get(ip=data['ip'])
        if plants.count() == 0:
            return data_formatting(304)

        plant = Plant()
        plant.name = data['name']
        plant.location = data['location']
        plant.species = data['species']
        plant.interval = data['interval']
        plant.person = Person.get(email=data['email'])
        plant.ip = data['ip']
        plant.sat_streak = 0

        if data['uuid'] != '':
            plant.uuid = data['uuid']
        if data['persistant_hold'] != '':
            plant.persistant_hold = data['persistant_hold']

        if not discovered.master:
            if data['role'] == '':
                master = Plant.get(localhost=True)
            else:
                master = Plant.get(uuid=data['role'])

            plant.role = str(master.uuid)

        plant.save()

        local_plant = Plant.get(localhost=True)
        for model in [
                SensorStatus, SensorCount, SensorSatisfactionValue,
                PlantNetworkUptime
        ]:
            copy_model_instance_from_localhost(plant, model,
                                               model.plant == local_plant)

        for count in list(
                SensorCount.select().where(SensorCount.plant == plant)):
            count.count = 0
            count.save()

        for uptime in list(PlantNetworkUptime.select().where(
                PlantNetworkUptime.plant == plant)):
            uptime.overall = 0
            uptime.current = 0
            uptime.save()

        if register:
            MeshDedicatedDispatch().register(plant)

        return data_formatting()