示例#1
0
def delete_responsible(r_uuid):
    if Person.select().where(Person.uuid == UUID(r_uuid)).count() > 0:
        Person.get(uuid=UUID(r_uuid)).delete_instance()
    else:
        return json.dumps({'info': 'no person with this UUID'})

    return json.dumps({'info': 'success'})
示例#2
0
def update_responsible_wizard():
    wizards = Person.select().where(Person.wizard == True)

    for old in wizards:
        old.wizard = False
        old.save()

    person = Person.get(Person.uuid == request.form['replacement'])
    person.wizard = True
    person.save()

    MeshDedicatedDispatch().update('person', person.uuid)
    return json.dumps({'info': 'success'})
示例#3
0
文件: plant.py 项目: indietyp/IoP
def plant_responsible(p_uuid):
    # GET: select: email, wizard, username, full, default (full)
    responsible = Plant.get(uuid=p_uuid).person
    if request.method == 'GET':
        responsible = model_to_dict(responsible)
        responsible['uuid'] = str(responsible['uuid'])

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

        for selected in selector:
            if selected != 'full':
                used = [selected, 'uuid']
            else:
                used = list(responsible.keys())

            output = {}

            for key in used:
                if key not in ['id', 'preset']:
                    output[key] = responsible[key]

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

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

        return data_formatting(data=output)
    else:
        data, code = get_data(required=PLANT_RESPONSIBLE_POST,
                              restrictive=True)
        if code == 400:
            return data_formatting(400)

        if data['email'] != '' and data['name'] != '':
            responsible = Person.get(Person.email**data['email'],
                                     Person.name**data['name'])
        elif data['uuid'] != '':
            responsible = Person.get(uuid=data['uuid'])

        plant = Plant.get(uuid=p_uuid)
        plant.person = responsible
        plant.save()

        return data_formatting()
示例#4
0
def get_responsible(r_uuid):
    person = Person.get(Person.uuid == r_uuid)
    person = model_to_dict(person)
    del person['id']
    del person['preset']
    person['uuid'] = str(person['uuid'])

    return json.dumps(person)
示例#5
0
def update_responsible():
    person = Person.get(Person.uuid == request.form['uuid'])
    person.name = request.form['name']
    person.email = request.form['email']
    person.save()

    MeshDedicatedDispatch().update('person', person.uuid)
    return json.dumps({'info': 'success'})
示例#6
0
文件: insert.py 项目: indietyp/IoP
def create_plant_name():
  person = Person()
  person.name = request.form['name']
  person.email = request.form['email']
  person.wizard = True if request.form['wizard'] == 'True' else False
  person.save()

  return json.dumps({'info': 1})
示例#7
0
def update_plant_responsible(p_uuid):
    plant = Plant.get(Plant.uuid == p_uuid)
    person = Person.get(Person.email == request.form['email'],
                        Person.name == request.form['name'])

    plant.person = person
    plant.save()

    MeshDedicatedDispatch().update('plant', plant.uuid)
    return json.dumps({'info': 1})
示例#8
0
def get_responsible_persons():
    people = Person.select()
    # people = db.ResponsiblePerson.find()

    output = []
    for person in people:
        dict_person = model_to_dict(person)
        dict_person['uuid'] = str(dict_person['uuid'])
        del dict_person['id']
        del dict_person['preset']
        output.append(dict_person)

    return json.dumps(output)
示例#9
0
文件: insert.py 项目: indietyp/IoP
def create_plant(data):
  try:
    Plant.get(Plant.ip == data['ip'])
  except:
    from models.mesh import MeshObject
    discovered = MeshObject.get(ip=data['ip'])
    plant = Plant()
    plant.name = data['name'].lower()
    plant.location = data['location']
    plant.species = data['species']
    plant.interval = data['interval']
    plant.person = Person.get(Person.email == data['email'])
    plant.ip = data['ip']
    plant.sat_streak = 0

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

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

      plant.role = str(master.uuid)

    plant.save()

    local_plant = Plant.get(Plant.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()

    return plant
示例#10
0
文件: mailer.py 项目: indietyp/IoP
  def execute(self, data):
    """ data
          sensor - sensor object
          plant - plant object
          value - current value
          satisfaction - current satisfaction
    """
    local = Plant.get(Plant.localhost == True)
    online = VariousTools.offline_check('notification', hardware=False)
    if online and local.host:
      latest = SensorDangerMessage.select()\
                                  .where(SensorDangerMessage.sent == True) \
                                  .order_by(SensorDangerMessage.created_at.desc()) \
                                  .limit(1) \
                                  .dicts()

      latest = list(latest)

      now = datetime.datetime.now()
      interval = data['plant'].interval * 60 * 60
      if len(latest) == 0 or (now - latest[0]['created_at']).seconds >= interval:
        for person in Person.select():
          us = SensorDangerMessage.select() \
                                  .where(SensorDangerMessage.sent == False) \
                                  .where(SensorDangerMessage.plant << Plant.select().where(Plant.person == person)) \
                                  .order_by(SensorDangerMessage.created_at.asc())
          unsent = us

          if unsent.count() != 0:
            for partial in unsent:
              partial.sent = True
              partial.sent_time = now
              partial.save()

            message = ''
            message += self.format_messages(unsent)
            self.send_message(data, message)

      return True
    else:
      return False
示例#11
0
    plant = Plant()
    plant.name = input('How do you want to call your first plant? ').lower()
    plant.location = input('The location? ').lower()
    plant.species = input('The species? ').lower()

    def interval():
        int_interval = input('emailing interval? (int) (h) ')

        if int_interval.isdigit() is True:
            return int(int_interval)
        else:
            return interval()

    plant.interval = interval()

    person = Person()
    print('\nto:')
    person.name = input('     Name: ')
    person.email = input('    Email: ')
    person.wizard = True
    person.save()
    print('\n')

    plant.person = person

    s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
    s.connect(("gmail.com", 80))

    plant.ip = s.getsockname()[0]
    plant.localhost = True
示例#12
0
from models.plant import Plant, Person
from models.mesh import MeshMessage
from playhouse.shortcuts import model_to_dict

plant = Plant()
plant.name = 'marta'
plant.location = 'table'
plant.species = 'tulpe'
plant.interval = 6

plant.person = Person.get(Person.wizard == True)
plant.ip = '192.168.178.54'
plant.uuid = '91c9280b76c142a393eb85250065230f'
plant.localhost = True
# plant.id = 1

plant.sat_streak = 0
plant.save()
print(str(plant.uuid))
示例#13
0
def person(r_uuid):
    # GET: select: full, default (full)
    # POST: replaceable: email, name, wizard
    # DELETE
    person = Person.get(uuid=r_uuid)

    if request.method == 'GET':
        data, code = get_data(required=PERSON_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(person)
                del output['id']
                del output['preset']
                output['uuid'] = str(output['uuid'])

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

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

        return data_formatting(data=output)

    elif request.method == 'POST':
        data, code = get_data(required=PERSON_POST, restrictive=True)
        if code == 400:
            return data_formatting(400)

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

        if data['email'] != '':
            person.email = data['email']

        if data['wizard'] is not None:

            if data['wizard']:
                wizards = Person.filter(wizard=True)

                for old in wizards:
                    old.wizard = False
                    old.save()
            person.wizard = data['wizard']

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

    else:
        if Person.select().where(Person.uuid == r_uuid).count() > 0:
            Person.get(uuid=r_uuid).delete_instance()
        else:
            return data_formatting(304)

        return data_formatting()
示例#14
0
def persons():
    # GET: select: minimal, normal, detailed, extensive, default (normal)
    # GET: dict: Boolean

    if request.method == 'GET':
        data, code = get_data(required=PERSONS_GET,
                              restrictive=True,
                              hardmode=True)
        if code == 400:
            return data_formatting(400)

        mode = data['dict']
        selector = data['select']
        persons = Person.select().dicts()
        selectable = ['minimal', 'normal', 'detailed', 'extensive']
        collection = {}

        for selected in selector:
            output = []

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

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

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

                if selected in selectable[3:]:
                    used.append('wizard')

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

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

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

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

    else:
        data, code = get_data(required=PERSONS_PUT,
                              restrictive=True,
                              hardmode=True)
        if code == 400:
            return data_formatting(400)

        person = Person()

        person.name = data['name']
        person.email = data['email']

        person.wizard = data['wizard']

        if data['wizard']:
            wizards = Person.filter(wizard=True)
            for old in wizards:
                old.wizard = False
                old.save()

        person.save()
        return data_formatting()
示例#15
0
文件: plant.py 项目: indietyp/IoP
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()
示例#16
0
文件: plant.py 项目: indietyp/IoP
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()