class SensorAlertStatus(db.Model):
    """Association table for sensors and alerts"""
    __tablename__ = 'sensor_alert_status'
    __table_args__ = (db.PrimaryKeyConstraint('sensor_id', 'alert_id'), )

    sensor_id = db.Column(db.Integer,
                          db.ForeignKey('sensors.id', ondelete="CASCADE"))
    alert_id = db.Column(db.Integer,
                         db.ForeignKey('alerts.id', ondelete="CASCADE"))
    last_execute = db.Column(db.DateTime)
    triggered = db.Column(db.Boolean)
class NetworkAlertAssociation(db.Model):
    """Association table for network alerts"""
    __tablename__ = 'network_alerts'
    __table_args__ = (db.PrimaryKeyConstraint('alert_id', 'network_id'), )

    network_id = db.Column(db.Integer,
                           db.ForeignKey('networks.id', ondelete="CASCADE"))
    alert_id = db.Column(db.Integer,
                         db.ForeignKey('alerts.id', ondelete="CASCADE"))

    networks = db.relationship("Network", back_populates="alerts")
    alert = db.relationship("Alert", back_populates="networks")
class CompanyUserAssociation(db.Model):
    """Association table for sensors and alerts"""
    __tablename__ = 'company_user'
    __table_args__ = (db.PrimaryKeyConstraint('user_id', 'company_id'), )

    user_id = db.Column(db.Integer,
                        db.ForeignKey('users.id', ondelete="CASCADE"))
    company_id = db.Column(db.Integer,
                           db.ForeignKey('companies.id', ondelete="CASCADE"))
    role = db.Column(db.String, default=C_ROLE_DEFAULT)

    user = db.relationship("User", back_populates="companies")
    company = db.relationship("Company", back_populates="users")
Example #4
0
class Event(db.Model):
    """Events model for scheduling

    unit if repeat is True
    """

    __tablename__ = "events"

    id = db.Column(db.String, primary_key=True)
    name = db.Column(db.String)
    company_id = db.Column(db.Integer, db.ForeignKey('companies.id'))
    is_active = db.Column(db.Boolean, default=True)

    repeat = db.Column(db.Boolean, default=False)
    unit = db.Column(db.String)  # day, week, month, year

    actuator_type = db.Column(db.String)
    config_field = db.Column(db.String)
    config_value = db.Column(db.String)

    start_date = db.Column(db.DateTime)
    next_runtime = db.Column(db.DateTime)
    created_at = db.Column(db.DateTime, default=datetime.utcnow)
    deleted_at = db.Column(db.DateTime)

    company = db.relationship("Company", back_populates="events")

    sensors = db.relationship("SensorEventAssociation",
                              back_populates="event",
                              cascade="all, delete-orphan")
Example #5
0
class SensorEventAssociation(db.Model):
    """
    Association table for sensors and events
    """
    __tablename__ = 'sensor_event'
    __table_args__ = (db.PrimaryKeyConstraint('sensor_id', 'event_id'), )

    sensor_id = db.Column(db.Integer,
                          db.ForeignKey('sensors.id', ondelete="CASCADE"))
    event_id = db.Column(db.String,
                         db.ForeignKey('events.id', ondelete="CASCADE"))
    # last_execute = db.Column(db.DateTime)
    # actuator_id = db.Column(db.Integer)

    sensor = db.relationship("Sensor", back_populates="events")
    event = db.relationship("Event", back_populates="sensors")
Example #6
0
class Network(StoredFileMixin, db.Model):
    """Network database model."""
    __tablename__ = 'networks'
    add_file_date_column = False
    file_required = False

    id = db.Column(db.Integer, primary_key=True)
    name = db.Column(db.String)
    company_id = db.Column(db.Integer, db.ForeignKey('companies.id'))
    deleted = db.Column(db.Boolean, default=False)
    uid = db.Column(db.String, unique=True)

    last_update = db.Column(db.DateTime, default=datetime.utcnow)
    created_at = db.Column(db.DateTime, default=datetime.utcnow)

    sensors = db.relationship("Sensor",
                              secondary=network_sensor_table,
                              back_populates="networks")
    company = db.relationship("Company", back_populates="networks")
    alerts = db.relationship("NetworkAlertAssociation",
                             back_populates="networks")

    def _build_storage_path(self):
        self.assign_id()
        path_segments = ['floormaps', (self.uid)]
        path = posixpath.join(*(path_segments +
                                ['{}_{}'.format(self.id, self.filename)]))
        return config.FLOORMAP_STORAGE, path
Example #7
0
class SensorType(db.Model):
    """
    Sensor types model.
    """
    __tablename__ = "sensor_types"

    # query_class = query_callable(regions)

    id = db.Column(db.Integer, primary_key=True)

    # Title for Sensor Type
    title = db.Column(db.String)

    # type for sensor type. lower case unique name
    type = db.Column(db.String, unique=True)

    # Inactivity duration after which sensor will be assumed as down.
    status_timeout = db.Column(db.Integer)

    # Is this sensor type is available to all users. Created by Admin User
    is_public = db.Column(db.Boolean, default=True)

    # Created by the user
    created_by = db.Column(db.Integer, db.ForeignKey('users.id'))

    value_fields = db.Column(db.JSON)
    config_fields = db.Column(db.JSON)
    created_at = db.Column(db.DateTime, default=datetime.utcnow)
    # TODO: Use deleted_at(Timestamp for soft deletes)
    deleted = db.Column(db.Boolean, default=False)
class Alert(db.Model):
    """
    Alerts database model.

    Table Name: alerts

    Columns:-
    id: Unique ID, Primary Key
    name: Name of the notification
    company_id: Company ID
    type: Alert type [ less_then, equal_to, grater_then, geo_in, geo_out, ... ]
    value: Compare Value
    between_start: Check for alerts between duration
    between_end: Check for alerts between duration
    send_to:
    send_method:

    created_at: Alert added on
    """
    __tablename__ = 'alerts'

    id = db.Column(db.Integer, primary_key=True)
    uid = db.Column(db.String, unique=True)
    name = db.Column(db.String)
    company_id = db.Column(db.Integer, db.ForeignKey('companies.id'))
    type = db.Column(db.String)
    sensor_type = db.Column(db.String)
    value = db.Column(db.String)
    field = db.Column(db.String)
    between_start = db.Column(db.Time)
    between_end = db.Column(db.Time)
    snooze = db.Column(db.Integer)
    threshold_duration = db.Column(
        db.Integer, default=0
    )  # Trigger only if alert is active for this duration in minutes
    alert_text = db.Column(db.String)
    recipients = db.Column(db.JSON)
    web_hooks = db.Column(db.JSON)
    alert_if = db.Column(db.String)  # Alert if point is inside or outside
    polygon = db.Column(db.JSON)
    is_active = db.Column(db.Boolean, default=True)
    deleted = db.Column(db.Boolean, default=False)

    action_type = db.Column(db.String, default=ALERT_ACTION_NITIFICATION)
    actuator_type = db.Column(db.String)
    config_field = db.Column(db.String)
    config_value = db.Column(db.String)

    created_at = db.Column(db.DateTime, default=datetime.utcnow)

    company = db.relationship("Company", back_populates="alerts")
    sensors = db.relationship("SensorAlertAssociation",
                              back_populates="alert",
                              cascade="all, delete-orphan")
    networks = db.relationship("NetworkAlertAssociation",
                               back_populates="alert",
                               cascade="all, delete-orphan")
class UserInvite(db.Model):
    __tablename__ = 'user_invites'

    id = db.Column(db.Integer, primary_key=True)
    company_id = db.Column(db.Integer, db.ForeignKey('companies.id'))
    email = db.Column(db.String(200))
    role = db.Column(db.String(20), default=C_ROLE_DEFAULT)
    status = db.Column(db.Boolean, default=False)
    created_at = db.Column(db.DateTime, default=datetime.utcnow)
class SensorAlertAssociation(db.Model):
    """
    Association table for sensors and alerts

    actuator_id: Change config value of Sensor on alert.
    If alert action is a trigger type the actuator_id will be required.
    """
    __tablename__ = 'sensor_alert'
    __table_args__ = (db.PrimaryKeyConstraint('sensor_id', 'alert_id'), )

    sensor_id = db.Column(db.Integer,
                          db.ForeignKey('sensors.id', ondelete="CASCADE"))
    alert_id = db.Column(db.Integer,
                         db.ForeignKey('alerts.id', ondelete="CASCADE"))
    last_execute = db.Column(db.DateTime)
    actuator_id = db.Column(db.Integer)

    sensor = db.relationship("Sensor", back_populates="alerts")
    alert = db.relationship("Alert", back_populates="sensors")
class UserMetaData(db.Model):
    """Database model for user meta details"""
    __tablename__ = 'users_meta_data'

    id = db.Column(db.Integer, primary_key=True)
    user_id = db.Column(db.Integer,
                        db.ForeignKey('users.id', ondelete="CASCADE"))
    key = db.Column(db.String)
    value = db.Column(db.String)
    description = db.Column(db.String)

    unique_user_key = db.UniqueConstraint('user_id', 'key')
Example #12
0
class Sensor(db.Model):
    """
    Sensor database model.

    This is a common model for all type of sensors. It have some general
    columns to save sensor details.

    """
    __tablename__ = 'sensors'
    __table_args__ = (db.UniqueConstraint(
        'company_id', 'hid', name="sensors_unique_company_id_hid"), )

    id = db.Column(db.Integer, primary_key=True)
    name = db.Column(db.String)
    type = db.Column(db.String(100))
    company_id = db.Column(db.Integer, db.ForeignKey('companies.id'))
    description = db.Column(db.String)
    location_lat = db.Column(db.Float)
    location_long = db.Column(db.Float)
    uid = db.Column(db.String, unique=True)
    hid = db.Column(db.String)
    # TODO: Key field size update.
    key = db.Column(db.String)
    is_down = db.Column(db.Boolean, default=False)
    is_inactive = db.Column(db.Boolean, default=False)
    deleted = db.Column(db.Boolean, default=False)
    ip = db.Column(db.String)
    last_update = db.Column(db.DateTime)
    created_at = db.Column(db.DateTime, default=datetime.utcnow)
    config_updated = db.Column(db.DateTime)

    value = db.Column(db.JSON)
    config = db.Column(db.JSON)

    time_start = db.Column(db.Time, default=time.min)
    time_end = db.Column(db.Time, default=time.max)

    # TODO: Add heart_beat(DateTime) field
    networks = db.relationship("Network",
                               secondary='network_sensor',
                               back_populates="sensors")
    company = db.relationship("Company", back_populates="sensors")

    alerts = db.relationship("SensorAlertAssociation", back_populates="sensor")

    events = db.relationship("SensorEventAssociation", back_populates="sensor")

    sensor_type = db.relationship("SensorType",
                                  foreign_keys=[type],
                                  primaryjoin='Sensor.type == SensorType.type')
class Company(db.Model):
    __tablename__ = 'companies'

    id = db.Column(db.Integer, primary_key=True)

    name = db.Column(db.String)

    owner_id = db.Column(db.Integer, db.ForeignKey('users.id'))

    deleted = db.Column(db.Boolean, default=False)

    uid = db.Column(db.String, unique=True)

    key = db.Column(db.String)

    owner = db.relationship("User",
                            back_populates="own_companies",
                            lazy="joined")

    sensors = db.relationship("Sensor",
                              back_populates="company",
                              cascade="all, delete, delete-orphan")

    networks = db.relationship("Network",
                               back_populates="company",
                               cascade="all, delete, delete-orphan")

    alerts = db.relationship("Alert",
                             back_populates="company",
                             cascade="all, delete, delete-orphan")

    events = db.relationship("Event",
                             back_populates="company",
                             cascade="all, delete, delete-orphan")

    users = db.relationship("CompanyUserAssociation", back_populates="company")

    def __repr__(self):
        return "<Company(uid='%s' name='%s')>" % (self.uid, self.name)
Example #14
0
# This file is part of SwarmSense IoT Platform
# Copyright (c) 2018, Baseapp Systems And Softwares Private Limited
# Authors: Gopal Lal
#
# License: www.baseapp.com/swarmsense-whitelabel-iot-platoform
"""Network Database Model"""
import posixpath
from datetime import datetime

from snms.core.db import db
from snms.core.storage import StoredFileMixin
from snms.core.config import config

network_sensor_table = db.Table(
    'network_sensor', db.Model.metadata,
    db.Column('network_id', db.Integer, db.ForeignKey('networks.id')),
    db.Column('sensor_id', db.Integer, db.ForeignKey('sensors.id')),
    db.PrimaryKeyConstraint('network_id', 'sensor_id'))


class Network(StoredFileMixin, db.Model):
    """Network database model."""
    __tablename__ = 'networks'
    add_file_date_column = False
    file_required = False

    id = db.Column(db.Integer, primary_key=True)
    name = db.Column(db.String)
    company_id = db.Column(db.Integer, db.ForeignKey('companies.id'))
    deleted = db.Column(db.Boolean, default=False)
    uid = db.Column(db.String, unique=True)
 def file_id(cls):
     return db.Column(db.Integer,
                      db.ForeignKey(
                          cls.stored_file_class.__table__.fullname + '.id',
                          use_alter=True),
                      nullable=True)