87 lines
2.3 KiB
Go
87 lines
2.3 KiB
Go
package lib
|
|
|
|
import (
|
|
"encoding/json"
|
|
"fmt"
|
|
databases2 "node_rabbit_go/app/databases"
|
|
"node_rabbit_go/app/internals/logger"
|
|
"time"
|
|
)
|
|
|
|
type RequestController struct {
|
|
MySQL *databases2.Database
|
|
LoggerAndExceptionHandler *logger.LoggerAndExceptionHandler
|
|
Clickhouse *databases2.Clickhouse
|
|
STOMP *STOMPlib
|
|
deviceDebugList []string
|
|
}
|
|
|
|
func NewRequestController() *RequestController {
|
|
rc := &RequestController{
|
|
MySQL: databases2.NewSQLDatabase(),
|
|
LoggerAndExceptionHandler: logger.NewLoggerAndExceptionHandler(),
|
|
Clickhouse: databases2.NewClickhouse(),
|
|
STOMP: NewSTOMPlib(),
|
|
deviceDebugList: []string{},
|
|
}
|
|
// Запуск получения устройств
|
|
go rc.getDebugDeviceListPeriodically()
|
|
return rc
|
|
}
|
|
|
|
func (rc *RequestController) WriteLog(devID string, data interface{}, ts time.Time) {
|
|
if rc.CheckDeviceDebugMode(devID) {
|
|
jsonData, err := json.Marshal(data)
|
|
if err != nil {
|
|
rc.LoggerAndExceptionHandler.Error(fmt.Sprintf("Error marshaling data: %s", err.Error()))
|
|
return
|
|
}
|
|
err = rc.Clickhouse.Insert("node_device_logs", map[string]interface{}{
|
|
"dev_id": devID,
|
|
"cmd_id": 0,
|
|
"data": string(jsonData),
|
|
"ts": ts,
|
|
})
|
|
if err != nil {
|
|
rc.LoggerAndExceptionHandler.Error(fmt.Sprintf("Error inserting log into ClickHouse:", err.Error()))
|
|
}
|
|
}
|
|
}
|
|
|
|
func (rc *RequestController) getDebugDeviceList() error {
|
|
rows, err := rc.MySQL.Query("SELECT `id` FROM `device` WHERE `debug_mode`=1")
|
|
if err != nil {
|
|
rc.LoggerAndExceptionHandler.Error(fmt.Sprintf("Error querying debug devices:", err.Error()))
|
|
return err
|
|
}
|
|
|
|
rc.deviceDebugList = []string{}
|
|
for rows.Next() {
|
|
var devID string
|
|
if err := rows.Scan(&devID); err != nil {
|
|
rc.LoggerAndExceptionHandler.Error(fmt.Sprintf("Error scanning debug device row:", err.Error()))
|
|
continue
|
|
}
|
|
rc.deviceDebugList = append(rc.deviceDebugList, devID)
|
|
}
|
|
return nil
|
|
}
|
|
|
|
func (rc *RequestController) getDebugDeviceListPeriodically() {
|
|
for {
|
|
time.Sleep(2 * time.Second)
|
|
if err := rc.getDebugDeviceList(); err != nil {
|
|
rc.LoggerAndExceptionHandler.Error(err.Error())
|
|
}
|
|
}
|
|
}
|
|
|
|
func (rc *RequestController) CheckDeviceDebugMode(devID string) bool {
|
|
for _, id := range rc.deviceDebugList {
|
|
if id == devID {
|
|
return true
|
|
}
|
|
}
|
|
return false
|
|
}
|