models

package
v0.0.0-...-13b120a Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Feb 5, 2024 License: BSD-3-Clause Imports: 38 Imported by: 0

Documentation

Index

Constants

This section is empty.

Variables

View Source
var ControllerEvent = "controller"
View Source
var DatasetEvent = "dataset"
View Source
var GLOBALCONFIG map[string]interface{}
View Source
var SWITCH_OFF = 0
View Source
var SWITCH_ON = 1
View Source
var SernsorEvent = "sensor"
View Source
var SwitchDefaultValues = `[{
	"item_description": "",
	"on": false
}]`

SwitchDefaultValues initial state

View Source
var SystemEvent = "system"

system event such as start, stop etc

View Source
var ThresholdswitchDefaultValues = `
[{
	"item_description": "",
	"datasource": "",
	"operation": "",
	"threshold_limit": null,
	"on": false
}]`

ThresholdswitchDefaultValues initial state

View Source
var TimeFormat = "2006-01-02 15:04:05"
View Source
var TimesSwitchDefaultValues = `
[{
	"item_description": "",
	"time_on": "",
	"time_off": "",
	"duration": null,
	"repeat": false,
	"on": false
}]
`

TimesSwitchDefaultValues initial state

View Source
var TimesSwitchRepeatDefaultValues = `` /* 130-byte string literal not displayed */
View Source
var WebCamEvent = "webcam"
View Source
var WebcamStreamTimelapseDefaultValues = `
[{
	"hostname": "",
	"interval": 300,
	"project_name": "",
	"output_name": "",
	"next_capture_time": ""
}]
`

Functions

func ClearRegisteredMetrics

func ClearRegisteredMetrics(db *sqlx.DB) error

ClearRegisteredMetrics clears all the registered metrics in the database.

func NewCollection

func NewCollection(list []PreDefinedMetric, db *sqlx.DB) *iotCollector

NewCollector creates a new instance of iotCollector with a database connection.

func RegisterPrefinedMetrics

func RegisterPrefinedMetrics(db *sqlx.DB, list []PreDefinedMetric) error

RegisterPrefinedMetrics registers predefined metrics into the database. Before registering, it clears all the existing metrics. If it fails to clear before registering, it returns an error. TODO: add insert to a transaction

func RetrieveDBMetricsToMap

func RetrieveDBMetricsToMap(db *sqlx.DB) (map[string]PreDefinedMetric, error)

RetrieveDBMetricsToMap retrives stored metrics in the database into a map. The key is the metric name

func SetTimeZone

func SetTimeZone(tz string)

Types

type Controller

type Controller struct {
	ID          int              `db:"id" json:"id"`
	SensorID    int              `db:"sensor_id" json:"sensor_id"`
	Category    string           `db:"category" json:"category"`
	Title       string           `db:"title" json:"title"`
	Description string           `db:"description" json:"description"`
	Switch      int              `db:"switch" json:"switch"`
	Items       *json.RawMessage `db:"items" json:"items"`
	Alert       bool             `db:"alert" json:"alert"`
	Active      bool             `db:"active" json:"active"`
	CreatedAt   time.Time        `db:"created_at" json:"created_at"`
	// contains filtered or unexported fields
}

Controller data structure

func GetControllerByID

func GetControllerByID(db *sqlx.DB, cid int) (Controller, error)

GetControllerByID loads a specific controller from database by given ID

func (*Controller) CheckThresholdSwitchEntries

func (c *Controller) CheckThresholdSwitchEntries(dataPoint float64, db *sqlx.DB)

CheckThresholdEntries checks if a list of threshold switches is within the boundaries of a given condition and turns them ON or OFF. Supported operations: greather than, less than, equal and not equal.

func (*Controller) CheckTimeSwitchEntries

func (c *Controller) CheckTimeSwitchEntries(db *sqlx.DB)

CheckTimeSwitchEntries checks if a list of time switches is within a specified timeframe and toggles their state between ON and OFF.

func (*Controller) CheckWebCamStreamEntries

func (c *Controller) CheckWebCamStreamEntries(db *sqlx.DB, storageLocation string)

CheckWebCamStreamEntries checks webcam entries in our controller and captures a timelapse image

func (*Controller) UpdateDynamicControllerSwitchState

func (c *Controller) UpdateDynamicControllerSwitchState(db *sqlx.DB, switchState int) error

UpdateDynamicControllerSwitchState updates a switch state of a controller based on telemetry data. If the telemetry data indicates that the controller should be switched on/off, this function will update the controller's switch state to on/off.

type ControllerList

type ControllerList []*Controller

func GetControllersListFromDB

func GetControllersListFromDB(db *sqlx.DB) (ControllerList, error)

GetControllersList returns a list of all available controllers, including those that are not currently active.

type Dataset

type Dataset struct {
	ID          int                  `db:"id" json:"id"`
	SensorID    int                  `db:"sensor_id" json:"sensor_id"`
	Title       string               `db:"title" json:"title"`
	Description string               `db:"description" json:"description"`
	Reference   string               `db:"reference" json:"reference"`
	IntervalSec int                  `db:"intervalsec" json:"intervalsec"`
	Fields      *json.RawMessage     `db:"fields" json:"fields"`
	Types       *json.RawMessage     `db:"types" json:"types"`
	Showcharts  *json.RawMessage     `db:"showcharts" json:"showcharts"`
	Icon        string               `db:"icon" json:"icon"`
	CreatedAt   time.Time            `db:"created_at" json:"created_at"`
	SensorTitle string               `db:"sensor_title" json:"sensor_title"`
	Telemetry   string               `db:"telemetry" json:"telemetry"`
	Data        sensor.RawSensorData `json:"datapoints,omitempty"`
}

Dataset ....

func GetDatasetsList

func GetDatasetsList(db *sqlx.DB) []Dataset

type NewDevice

type NewDevice struct {
	Title       string `json:"title"`
	Description string `json:"description"`
}

type PreDefinedMetric

type PreDefinedMetric struct {
	ID        int
	Reference string // dataset reference
	Name      string
	Help      string
	Value     float64
}

PreDefinedMetric.

type SensorData

type SensorData struct {
	ID            int              `db:"id" json:"id"`
	SensorID      int              `db:"sensor_id" json:"sensor_id"`
	DatasetID     int              `db:"dataset_id" json:"dataset_id"`
	Data          *json.RawMessage `db:"data" json:"data"`
	RecordingTime time.Time        `db:"time" json:"time"`
}

A structure that holds Sensor data

type SensorDevice

type SensorDevice struct {
	ID          int       `db:"id" json:"id"`
	Title       string    `db:"title" json:"title"`
	Description string    `db:"description" json:"description"`
	ArduinoKey  string    `db:"arduino_key" json:"arduino_key"`
	CreatedAt   time.Time `db:"created_at" json:"created_at"`
	// nullString because selecting a device without reference
	// will produce records with empty values
	DatasetTelem *sql.NullString `db:"dataset_telemetry" json:"dataset_telemetry"`
	SensorIP     string          `db:"sensor_ip" json:"sensor_ip"`
}

Sensor meta information

func GetSensorsList

func GetSensorsList(db *sqlx.DB) []SensorDevice

type SensorRawJSONData

type SensorRawJSONData struct {
	ID   int              `json:"id"`
	Data *json.RawMessage `json:"data"`
	Time time.Time        `json:"time"`
}

Data JSON payload

type Server

type Server struct {
	DB *sqlx.DB
	// Server JSON config file
	Config map[string]interface{}
	Router *chi.Mux

	//Hub to keep track of socket connection
	// for live monitoring of datasets.
	Hub             *hub.Hub
	Telemetry       *Telemetry
	StorageLocation string

	Debug bool

	// Prometheus metrics
	PromRegistry *prometheus.Registry
	// contains filtered or unexported fields
}

Server ....

func New

func New(path string, automigrate bool, debug bool) *Server

New initialize server and opens a database connection.

func (*Server) API_URL

func (s *Server) API_URL() string

func (*Server) AddMetricEndpoint

func (s *Server) AddMetricEndpoint(w http.ResponseWriter, r *http.Request)

func (*Server) AddNewControllerEndpoint

func (s *Server) AddNewControllerEndpoint(w http.ResponseWriter, r *http.Request)

AddNewControllerEndpoint adds a new controller to the database with an initial switch state of OFF and alert set to false. The method also updates the memory with new controller values.

func (*Server) AddNewDevice

func (s *Server) AddNewDevice(w http.ResponseWriter, r *http.Request)

AddNewDevice adds a fresh device to the database

func (*Server) AreaChartDataSeries

func (s *Server) AreaChartDataSeries(w http.ResponseWriter, r *http.Request)

AreaChartDataSeries will generate a data structure that is fitted to ngx-charts.

func (*Server) DashboardInfoEndpoint

func (s *Server) DashboardInfoEndpoint(w http.ResponseWriter, r *http.Request)

func (*Server) DeleteCameraEndpoint

func (s *Server) DeleteCameraEndpoint(w http.ResponseWriter, r *http.Request)

func (*Server) DeleteControllerByIDEndpoint

func (s *Server) DeleteControllerByIDEndpoint(w http.ResponseWriter, r *http.Request)

DeleteControllerByIDEndpoint deletes the controller record with the specified ID from the database without any confirmation. Note that caution is advised when deleting controllers as it may have an impact on the IoT system.

func (*Server) DeleteDatasetByIDEndpoint

func (s *Server) DeleteDatasetByIDEndpoint(w http.ResponseWriter, r *http.Request)

DeleteDatasetByIDEndpoint deletes dataset and any sensor data associated with it. WARNING!!! THIS IS IRREVERSIBLE!

func (*Server) ExportSensorDataToCSVEndpoint

func (s *Server) ExportSensorDataToCSVEndpoint(w http.ResponseWriter, r *http.Request)

ExportSensorDataToCSVEndpoint for exporting datasets used to create CSV report

func (*Server) GetCameraByIDEndpoint

func (s *Server) GetCameraByIDEndpoint(w http.ResponseWriter, r *http.Request)

func (*Server) GetCameraListEndpoint

func (s *Server) GetCameraListEndpoint(w http.ResponseWriter, r *http.Request)

func (*Server) GetControllerByIDEndpoint

func (s *Server) GetControllerByIDEndpoint(w http.ResponseWriter, r *http.Request)

GetControllerByIDEndpoint retrieves a specific controller from the database using the ID provided in the request body.

func (*Server) GetControllersListEndpoint

func (s *Server) GetControllersListEndpoint(w http.ResponseWriter, r *http.Request)

GetControllersListEndpoint returns a list of all available controllers.

func (*Server) GetDatasetByReference

func (s *Server) GetDatasetByReference(w http.ResponseWriter, r *http.Request)

GetDatasetByReference fetches a dataset based on a reference

func (*Server) GetDatasetsListEndpoint

func (s *Server) GetDatasetsListEndpoint(w http.ResponseWriter, r *http.Request)

GetDatasetsList fetches a list of all datasets

func (*Server) GetEventLogListEndpoint

func (s *Server) GetEventLogListEndpoint(w http.ResponseWriter, r *http.Request)

GetEventLogListEndpoint fetches a list of events with a limite from GET param count

func (*Server) GetSensorByReference

func (s *Server) GetSensorByReference(w http.ResponseWriter, r *http.Request)

GetSensorByReference is looking up a particular sensor based on a arduino_key

func (*Server) GetSensorDataByReferenceEndpoint

func (s *Server) GetSensorDataByReferenceEndpoint(w http.ResponseWriter, r *http.Request)

GetSensorDataByReferenceEndpoint fetches a dataset by a reference

func (*Server) GetSensorsListEndpoint

func (s *Server) GetSensorsListEndpoint(w http.ResponseWriter, r *http.Request)

GetSensorsList fetches a list of all available sensors in the database

func (*Server) GetTemperatureReport

func (s *Server) GetTemperatureReport(w http.ResponseWriter, r *http.Request)

func (*Server) HealthCheckHandler

func (s *Server) HealthCheckHandler(w http.ResponseWriter, r *http.Request)

func (*Server) InsertCameraEndpoint

func (s *Server) InsertCameraEndpoint(w http.ResponseWriter, r *http.Request)

InsertCameraEndpoint inserts a new camera into the database and returns the new camera.

func (*Server) InsertTestdata

func (s *Server) InsertTestdata() error

InsertTestdata insert data needed for tests to run

func (*Server) LineChartDataSeries

func (s *Server) LineChartDataSeries(w http.ResponseWriter, r *http.Request)

LineChartDataSeries will generate a data structure that is fitted to ng2-charts.

func (*Server) NewDataset

func (s *Server) NewDataset(w http.ResponseWriter, r *http.Request)

NewDataset adds a new dataset to db

func (*Server) RegisterMetricsDBValue

func (s *Server) RegisterMetricsDBValue(data SensorData) error

func (*Server) ResetControllerSwitchValueEndpoint

func (s *Server) ResetControllerSwitchValueEndpoint(w http.ResponseWriter, r *http.Request)

ResetControllerSwitchValueEndpoint resets the active configuration (raw JSON) for a given controller to its default state. Additionally, the method sets the controller switch state to OFF and inactive to prevent unwanted situations when IoT equiment is running in an active envionment.

func (*Server) Run

func (srv *Server) Run(ctx context.Context)

Run starts the webserver

func (*Server) SERVER_URL

func (s *Server) SERVER_URL() string

func (*Server) SaveSensorReading

func (s *Server) SaveSensorReading(w http.ResponseWriter, r *http.Request)

SaveSensorReading is registering sensor readings (json) to database.

func (*Server) SetControllerAlertStateEndpoint

func (s *Server) SetControllerAlertStateEndpoint(w http.ResponseWriter, r *http.Request)

SetControllerAlertStateEndpoint allows the caller to change alert state to either on or off, but for only active controllers. The method updates both the memory values and the database. It also writes a event log message to indicate a state changed.

func (*Server) SetControllerStateEndpoint

func (s *Server) SetControllerStateEndpoint(w http.ResponseWriter, r *http.Request)

SetControllerStateEndpoint changes the state of a controller to either on or off. The method updates both the memory values and the database. It also writes a event log message to indicate a state changed.

func (*Server) SetControllerSwitchStateEndpoint

func (s *Server) SetControllerSwitchStateEndpoint(w http.ResponseWriter, r *http.Request)

SetControllerSwitchState allows the caller to change the switch state to either on or off, but for only active controllers. The method updates both the memory values and the database. It also writes a event log message to indicate a state changed.

func (*Server) SetupEndpoints

func (s *Server) SetupEndpoints()

func (*Server) StartSim

func (s *Server) StartSim(sim *Sim)

Start starts a ticker with 1 second duration

func (*Server) Stop

func (s *Server) Stop(ctx context.Context)

Stop stops the webserver by shutting down context.Background

func (*Server) StopSim

func (s *Server) StopSim()

func (*Server) SyncSensorData

func (s *Server) SyncSensorData(w http.ResponseWriter, r *http.Request)

SyncDataset ... this is not in use.

func (*Server) TestCheckWebhooks

func (s *Server) TestCheckWebhooks(w http.ResponseWriter, r *http.Request)

func (*Server) UpdateCameraEndpoint

func (s *Server) UpdateCameraEndpoint(w http.ResponseWriter, r *http.Request)

func (*Server) UpdateControllerByIDEndpoint

func (s *Server) UpdateControllerByIDEndpoint(w http.ResponseWriter, r *http.Request)

UpdateControllerByIDEndpoint updates the database and memory values for a controller item by its ID. Note that the method does not validate the *json.RawMessage.

func (*Server) UpdateDataset

func (s *Server) UpdateDataset(w http.ResponseWriter, r *http.Request)

func (*Server) UpdateDevice

func (s *Server) UpdateDevice(w http.ResponseWriter, r *http.Request)

UpdateDevice updates sensor metadata fields

type Sim

type Sim struct {
	// contains filtered or unexported fields
}

func NewSim

func NewSim() *Sim

type Telemetry

type Telemetry struct {
	// contains filtered or unexported fields
}

A telemetry struct holds various telemetry components in memory.

func (*Telemetry) CheckControllersTelemetry

func (t *Telemetry) CheckControllersTelemetry()

CheckControllersTelemetry ...

func (*Telemetry) CheckDatasetTelemetry

func (t *Telemetry) CheckDatasetTelemetry()

UpdateDatasetTelemetry updates the telemetry data for a given dataset. It also checks if the telemetry data is overdue by more than 60 seconds, and if so, marks the dataset as offline.

func (*Telemetry) CheckWebcamTelemetry

func (t *Telemetry) CheckWebcamTelemetry()

CheckWebcamTelemetry ...

func (*Telemetry) GetInMemDatasetInfoByID

func (t *Telemetry) GetInMemDatasetInfoByID(id int) Dataset

GetInMemDatasetByID returns a dataset from memory by id, if id is not found an empty dataset is returned.

func (*Telemetry) UpdateTelemetryLists

func (t *Telemetry) UpdateTelemetryLists()

UpdateTelemetryLists updates sensors and dataset lists TODO: remove t.init method

type TemperatureReport

type TemperatureReport struct {
	Description string                 `json:"description"`
	DateFrom    string                 `json:"date_from"`
	DateTo      string                 `json:"date_to"`
	HighDate    string                 `json:"high_date"`
	LowDate     string                 `json:"low_date"`
	High        float64                `json:"high"`
	Low         float64                `json:"low"`
	Average     float64                `json:"average"`
	Datapoints  int                    `json:"datapoints"`
	Data        []sensor.RawSensorData `json:"data,omitempty"`
}

type TemperatureReportRequest

type TemperatureReportRequest struct {
	DateFrom    string `json:"date_from"`
	DateTo      string `json:"date_to"`
	DatasetID   int    `json:"dataset_id"`
	DatasetRef  string `json:"dataset_ref"`
	DataColumn  string `json:"data_column"`
	IncludeData bool   `json:"include_data"`
}

type Thresholdswitch

type Thresholdswitch struct {
	Description    string  `json:"item_description"`
	Datasource     string  `json:"datasource"`
	Operation      string  `json:"operation"`
	ThresholdLimit float64 `json:"threshold_limit"`
}

type Timeswitch

type Timeswitch struct {
	Description string `json:"item_description"`
	TimeOn      string `json:"time_on"`
	TimeOff     string `json:"time_off"`
	// Cutoff used for timeswitchrepeat
	Cutoff   string `json:"cutoff,omitempty"`
	Duration string `json:"duration"`
	Repeat   bool   `json:"repeat"`
	On       bool   `json:"on"`
}

type WebcamStreamTimelapse

type WebcamStreamTimelapse struct {
	Hostname        string    `json:"hostname"`
	Interval        int       `json:"interval"`
	ProjectName     string    `json:"project_name"`
	OutputName      string    `json:"output_name"`
	NextCaptimeTime time.Time `json:"next_capture_time"`
}

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL