Esempio n. 1
0
  def format_messages(self, messages):
    output = ''

    for part in messages:
      preset = part.plant.person.preset

      if isinstance(part.created_at, str):
        created_at = part.created_at.replace('+00:00', '')
        try:
          created_at = datetime.datetime.strptime(created_at, '%Y-%m-%d %H:%M:%S')
        except:
          created_at = datetime.datetime.strptime(created_at, "%Y-%m-%d %H:%M:%S.%f")
      else:
        created_at = part.created_at


      s = SensorSatisfactionLevel.get(SensorSatisfactionLevel.label == 'cautioning')
      c = SensorSatisfactionValue.select()\
                                 .where(SensorSatisfactionValue.level == s)\
                                 .where(SensorSatisfactionValue.plant == part.plant)\
                                 .where(SensorSatisfactionValue.sensor == part.sensor)[0]

      s = SensorSatisfactionLevel.get(SensorSatisfactionLevel.label == 'optimum')
      o = SensorSatisfactionValue.select()\
                                 .where(SensorSatisfactionValue.level == s)\
                                 .where(SensorSatisfactionValue.plant == part.plant)\
                                 .where(SensorSatisfactionValue.sensor == part.sensor)[0]

      tmp = preset.message

      for r in [['[sensor]', part.sensor.name],
                ['[plant]', part.plant.name],
                ['[date]', created_at.strftime('%d. %b')],
                ['[current]', str(part.value)],
                ['[time (12h)]', created_at.strftime('%I:%M %p')],
                ['[time (24h)]', created_at.strftime('%H:%M')],
                ['[name]', part.plant.person.name],
                ['[email]', part.plant.person.email],
                ['[ideal_min]', str(o.min_value)],
                ['[ideal_max]', str(o.max_value)],
                ['[warning_min]', str(c.min_value)],
                ['[warning_max]', str(c.max_value)],
                ['[unit]', part.sensor.unit]]:

        tmp = tmp.replace(r[0], r[1])

      output += tmp + '\n\n'

    return output
Esempio n. 2
0
    def run(self):
        result = VariousTools.offline_check('pump', hardware=False)
        if result:
            status = SensorStatus.get(SensorStatus.sensor == self.sensor,
                                      SensorStatus.plant == self.plant)

            optimum = SensorSatisfactionLevel.get(
                SensorSatisfactionValue.label == 'optimum')

            satisfaction = SensorSatisfactionValue.get(
                SensorSatisfactionValue.sensor == self.sensor,
                SensorSatisfactionValue.plant == self.plant,
                SensorSatisfactionValue.level == optimum)

            latest = SensorData.select(
                SensorData.sensor == self.sensor,
                SensorData.plant == self.plant).order_by(
                    SensorData.created_at.desc()).limit(1)[0]

            if status.level.label == 'threat' and latest.value < satisfaction.min_value:
                GPIO.setmode(GPIO.BCM)
                GPIO.setwarnings(False)
                GPIO.setup(17, GPIO.OUT)
                GPIO.setup(27, GPIO.OUT)
                GPIO.setup(22, GPIO.OUT)

                GPIO.output(27, True)
                GPIO.output(22, False)

                p = GPIO.PWM(17, 500)
                p.start(0)

                counter = 0
                dc = 0

                limited = False
                while dc <= 100 and not limited:
                    dc += 5
                    print(dc)
                    if dc > 100 and not limited:
                        dc = 100
                    else:
                        p.ChangeDutyCycle(dc)

                    counter += 1
                    if counter % 2 == 0:
                        limited = self.check(samples=3)
                    time.sleep(.1)

                for dc in range(dc, -1, -5):
                    p.ChangeDutyCycle(dc)
                    time.sleep(0.1)

                p.stop()
                GPIO.output(27, False)
                GPIO.output(22, False)
Esempio n. 3
0
def update_plant_ranges(p_uuid):
    plant = Plant.get(Plant.uuid == p_uuid)
    sensor = Sensor.get(Sensor.name == request.form['sensor'].lower())

    level_yellow = SensorSatisfactionLevel.get(
        SensorSatisfactionLevel.name_color == 'yellow')
    level_green = SensorSatisfactionLevel.get(
        SensorSatisfactionLevel.name_color == 'green')

    value_yellow = SensorSatisfactionValue.get(
        SensorSatisfactionValue.plant == plant,
        SensorSatisfactionValue.sensor == sensor,
        SensorSatisfactionValue.level == level_yellow)

    value_green = SensorSatisfactionValue.get(
        SensorSatisfactionValue.plant == plant,
        SensorSatisfactionValue.sensor == sensor,
        SensorSatisfactionValue.level == level_green)

    value_yellow.min_value = int(request.form.getlist('data[]')[0])
    value_green.min_value = int(request.form.getlist('data[]')[1])
    value_green.max_value = int(request.form.getlist('data[]')[2])
    value_yellow.max_value = int(request.form.getlist('data[]')[3])

    value_green.save()
    value_yellow.save()

    MeshDedicatedDispatch().update('plant satisfaction level', plant.uuid)
    if sensor.name == 'moisture' and plant.role != 'master':
        logger.info('executing slave update')
        information = {
            'min': value_yellow.min_value,
            'max': value_yellow.max_value
        }
        MeshDedicatedDispatch().slave_update(2, information, plant)

    return json.dumps({'info': 'success'})
Esempio n. 4
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)
Esempio n. 5
0
def get_plant_sensor_range(p_uuid, sensor):
    sensor = Sensor.get(Sensor.name == sensor)
    plant = Plant.get(Plant.uuid == p_uuid)

    ranges = SensorSatisfactionValue.select() \
                                    .where(SensorSatisfactionValue.plant == plant) \
                                    .where(SensorSatisfactionValue.sensor == sensor)

    output = {}
    for spectrum in ranges:
        output[spectrum.level.name_color] = {
            'max': spectrum.max_value,
            'min': spectrum.min_value
        }
        if spectrum.level.name_color == 'red':
            output[spectrum.level.name_color] = {
                'max': sensor.max_value,
                'min': sensor.min_value
            }

    return json.dumps(output)
Esempio n. 6
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)
Esempio n. 7
0
from models.sensor import SensorSatisfactionValue
import uuid

for person in SensorSatisfactionValue.select():
    person.uuid = uuid.uuid4()
    person.save()
Esempio n. 8
0
def plant_sensor(p_uuid, s_uuid):
    # GET: select: latest, prediction, data, current, range, extreme, message
    # GET: max: Boolean (extreme)
    # GET: ever: Boolean (extreme)
    # GET: backlog: Boolean (extreme)
    # GET: start: Integer (data)
    # GET: stop: Integer (data)
    # GET: count: Boolean (data)
    plant = Plant.get(uuid=p_uuid)
    try:
        sensor = Sensor.get(uuid=s_uuid)
    except Exception:
        sensor = Sensor.get(name=s_uuid)

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

    data, code = get_data(required=PLANT_SENSOR_GET, restrictive=True)
    if code == 400:
        return data_formatting(400)

    selector = data['select']
    maximum = data['max']
    backlog = data['backlog']
    start = data['start']
    stop = data['stop']
    ever = data['ever']
    collection = {}

    for selected in selector:
        if selected == 'timespan':
            start = datetime.datetime.min if start <= 0 else datetime.datetime.fromtimestamp(
                start)
            stop = datetime.datetime.max if stop >= 253402297200 else datetime.datetime.fromtimestamp(
                stop)

        if selected in [
                'latest', 'current', 'extreme', 'data', 'count', 'timespan'
        ]:
            data = 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.asc()) \
                             .dicts()
        elif selected in ['prediction']:
            data = SensorDataPrediction.select(SensorDataPrediction.value,
                                               fn.CAST(Clause(fn.strftime('%s', SensorDataPrediction.time), SQL('AS INT'))).alias('timestamp')) \
                                       .where(SensorDataPrediction.plant == plant) \
                                       .where(SensorDataPrediction.sensor == sensor) \
                                       .order_by(SensorDataPrediction.created_at.asc()) \
                                       .dicts()
        elif selected in ['range']:
            data = SensorSatisfactionValue.select() \
                                          .where(SensorSatisfactionValue.plant == plant) \
                                          .where(SensorSatisfactionValue.sensor == sensor)

        if selected in ['latest', 'current']:
            data = data.order_by(SensorData.created_at.desc()).limit(1)
            output = list(data)[0]
        elif selected == 'prediction':
            output = list(data)
        elif selected == 'range':
            output = {}
            for spectrum in data:
                output[spectrum.level.name_color] = {
                    'max': spectrum.max_value,
                    'min': spectrum.min_value
                }
                if spectrum.level.name_color == 'red':
                    output[spectrum.level.name_color] = {
                        'max': sensor.max_value,
                        'min': sensor.min_value
                    }
        elif selected == 'extreme':
            target = datetime.datetime.combine(datetime.date.today(),
                                               datetime.datetime.min.time())
            if backlog and not ever:
                output = None
                while output is None:
                    output = get_sensor_data_high_low(plant, sensor, maximum,
                                                      target)
                    target = target - datetime.timedelta(days=1)
            else:
                if ever:
                    target = None
                output = get_sensor_data_high_low(plant, sensor, maximum,
                                                  target)
        elif selected == 'count':
            output = data.count()
        elif selected == 'timespan':
            data = data.where(SensorData.created_at > start,
                              SensorData.created_at < stop)
            output = list(data)
        else:
            data = data.order_by(
                SensorData.created_at.desc()).offset(start).limit(stop - start)
            output = list(data)

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

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

    return data_formatting(data=output)
Esempio n. 9
0
def plant(p_uuid):
    if request.method == 'GET':
        # GET: select: intervals, created_at, type/species, survived, location, full, default (full)
        data, code = get_data(required=PLANT_GET,
                              restrictive=True,
                              hardmode=True)
        if code == 400:
            return data_formatting(400)

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

        for selected in selector:
            plant = list(
                Plant.select(
                    Plant,
                    fn.CAST(
                        Clause(fn.strftime('%s', Plant.created_at),
                               SQL('AS INT'))).alias('created_at')).where(
                                   Plant.uuid == p_uuid).dicts())[0]
            plant['uuid'] = str(plant['uuid'])

            if selected not in ['full', 'intervals', 'survived']:
                output = {selected: plant[selected]}
            elif selected in ['intervals']:
                output = {
                    'connection_lost': plant['connection_lost'],
                    'non_persistant':
                    int(plant['persistant_hold'] * 5 / 60 / 24),
                    'notification': plant['interval']
                }
            elif selected in ['survived']:
                difference = datetime.datetime.now(
                ) - datetime.datetime.fromtimestamp(plant['created_at'])
                output = float(difference.days +
                               round((difference.seconds // 3600) / 24, 1))
            else:
                output = plant

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

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

        return data_formatting(data=output)
    elif request.method == 'POST':
        # POST: replace: name, type, location, ranges, responsible
        # POST: mode: add, reset, online, offline
        # POST: new: DATA
        data, code = get_data(required=PLANT_POST, restrictive=True)
        if code == 400:
            return data_formatting(400)

        keys = list(data.keys())

        if data['mode'] == '':
            mode = 'add' if 'satisfaction' in keys else 'offline'
        else:
            mode = data['mode'].lower()

        plant = Plant.get(uuid=p_uuid)

        if data['name'] != '':
            plant.name = data['name']

        if data['species'] != '':
            plant.species = data['species']

        if data['location'] != '':
            plant.location = data['location']

        if data['ranges']:
            try:
                sensor = Sensor.get(name=data['sensor'])
            except Exception:
                try:
                    sensor = Sensor.get(uuid=data['sensor'])
                except Exception:
                    return data_formatting(400)

            level_yellow = SensorSatisfactionLevel.get(
                SensorSatisfactionLevel.name_color == 'yellow')
            level_green = SensorSatisfactionLevel.get(
                SensorSatisfactionLevel.name_color == 'green')

            value_yellow = SensorSatisfactionValue.get(
                SensorSatisfactionValue.plant == plant,
                SensorSatisfactionValue.sensor == sensor,
                SensorSatisfactionValue.level == level_yellow)

            value_green = SensorSatisfactionValue.get(
                SensorSatisfactionValue.plant == plant,
                SensorSatisfactionValue.sensor == sensor,
                SensorSatisfactionValue.level == level_green)

            value_yellow.min_value = int(request.form.getlist('range[]')[0])
            value_green.min_value = int(request.form.getlist('range[]')[1])
            value_green.max_value = int(request.form.getlist('range[]')[2])
            value_yellow.max_value = int(request.form.getlist('range[]')[3])

            value_green.save()
            value_yellow.save()

            MeshDedicatedDispatch().update('plant satisfaction level',
                                           plant.uuid)
            if sensor.name == 'moisture' and plant.role != 'master':
                # logger.info('executing slave update')
                information = {
                    'min': value_yellow.min_value,
                    'max': value_yellow.max_value
                }
                MeshDedicatedDispatch().slave_update(2, information, plant)

        if data['responsible']:
            person = Person.get(email=data['email'], name=data['firstname'])
            plant.person = person
            plant.save()

        if data['satisfaction']:
            if mode == 'add':
                plant.sat_streak += 1
            else:
                plant.sat_streak = 1

        if data['alive']:
            counterpart = 'online' if mode == 'offline' else 'offline'
            status = PlantNetworkStatus.get(name=mode)
            counterpart = PlantNetworkStatus.get(name=counterpart)

            if plant.role == 'master':
                return data_formatting()

            status = PlantNetworkUptime.get(plant=plant, status=status)
            counterpart = PlantNetworkUptime.get(plant=plant,
                                                 status=counterpart)

            if counterpart.current != 0:
                counterpart.current = 0
                counterpart.save()

            status.current += 1
            status.overall += 1
            status.save()

        if data['notification']:
            _, _, hours = time_request_from_converter(data)
            plant.interval = int(round(hours))

        if data['connection-lost']:
            _, minutes, _ = time_request_from_converter(data)
            plant.connection_lost = int(round(minutes))

        if data['non-persistant']:
            _, minutes, _ = time_request_from_converter(data)
            plant.persistant_hold = int(round(minutes / 5))

        plant.save()
        MeshDedicatedDispatch().update('plant', plant.uuid)
        return data_formatting()