GoSungrow/cmd/cmd_mqtt.go

938 lines
24 KiB
Go
Raw Permalink Normal View History

2022-02-11 18:30:45 +11:00
package cmd
import (
2022-12-14 17:50:18 +11:00
"GoSungrow/iSolarCloud/WebAppService/getDevicePointAttrs"
2022-10-07 23:12:47 +11:00
"GoSungrow/iSolarCloud/api"
2022-12-13 22:25:28 +11:00
"GoSungrow/iSolarCloud/api/GoStruct/output"
2022-04-21 10:47:05 +10:00
"GoSungrow/mmHa"
2022-03-04 20:29:30 +11:00
"errors"
2022-02-11 18:30:45 +11:00
"fmt"
2022-11-28 22:27:18 +11:00
"github.com/MickMake/GoUnify/Only"
2022-10-07 23:12:47 +11:00
"github.com/MickMake/GoUnify/cmdHelp"
"github.com/MickMake/GoUnify/cmdLog"
2022-12-20 20:28:51 +11:00
mqtt "github.com/eclipse/paho.mqtt.golang"
2022-03-04 20:29:30 +11:00
"github.com/go-co-op/gocron"
2022-02-11 18:30:45 +11:00
"github.com/spf13/cobra"
2022-10-07 23:12:47 +11:00
"github.com/spf13/viper"
2022-12-13 22:25:28 +11:00
"path/filepath"
"regexp"
2022-03-04 20:29:30 +11:00
"strings"
2022-03-02 14:32:56 +11:00
"time"
2022-02-11 18:30:45 +11:00
)
2022-10-07 23:12:47 +11:00
const (
2022-12-13 22:25:28 +11:00
DefaultServiceName = "GoSungrow"
DefaultServiceArea = "Roof"
DefaultVendor = "MickMake"
2022-10-07 23:12:47 +11:00
flagMqttUsername = "mqtt-user"
flagMqttPassword = "mqtt-password"
2022-12-20 20:28:51 +11:00
flagMqttHost = "mqtt-host"
flagMqttPort = "mqtt-port"
2022-10-07 23:12:47 +11:00
)
2022-12-13 22:25:28 +11:00
2022-10-07 23:12:47 +11:00
//goland:noinspection GoNameStartsWithPackageName
type CmdMqtt struct {
CmdDefault
// HASSIO MQTT
MqttUsername string
MqttPassword string
MqttHost string
MqttPort string
2022-02-25 18:14:08 +11:00
2022-11-28 22:27:18 +11:00
Client *mmHa.Mqtt
2022-12-13 22:25:28 +11:00
endpoints MqttEndPoints
2022-12-14 17:50:18 +11:00
points getDevicePointAttrs.PointsMap
2022-12-20 20:28:51 +11:00
optionLogLevel int
optionSleepDelay time.Duration
optionFetchSchedule time.Duration
2022-02-11 18:30:45 +11:00
}
2022-02-25 18:14:08 +11:00
2022-10-07 23:12:47 +11:00
func NewCmdMqtt() *CmdMqtt {
var ret *CmdMqtt
2022-02-25 18:14:08 +11:00
2022-02-11 18:30:45 +11:00
for range Only.Once {
2022-10-07 23:12:47 +11:00
ret = &CmdMqtt {
CmdDefault: CmdDefault {
Error: nil,
cmd: nil,
SelfCmd: nil,
},
2022-12-20 20:28:51 +11:00
optionLogLevel: LogLevelInfo,
optionSleepDelay: time.Second * 40, // Takes up to 40 seconds for data to come in.
optionFetchSchedule: time.Minute * 5,
2022-03-04 20:29:30 +11:00
}
2022-10-07 23:12:47 +11:00
}
2022-03-04 20:29:30 +11:00
2022-10-07 23:12:47 +11:00
return ret
}
func (c *CmdMqtt) AttachCommand(cmd *cobra.Command) *cobra.Command {
for range Only.Once {
if cmd == nil {
2022-04-21 10:47:05 +10:00
break
}
2022-10-07 23:12:47 +11:00
c.cmd = cmd
// ******************************************************************************** //
var cmdMqtt = &cobra.Command{
Use: "mqtt",
Aliases: []string{""},
Short: fmt.Sprintf("Connect to a HASSIO broker."),
Long: fmt.Sprintf("Connect to a HASSIO broker."),
DisableFlagParsing: false,
DisableFlagsInUseLine: false,
PreRunE: nil,
RunE: c.CmdMqtt,
Args: cobra.MinimumNArgs(1),
}
cmd.AddCommand(cmdMqtt)
cmdMqtt.Example = cmdHelp.PrintExamples(cmdMqtt, "run", "sync")
// ******************************************************************************** //
var cmdMqttRun = &cobra.Command{
Use: "run",
Aliases: []string{""},
Short: fmt.Sprintf("One-off sync to a HASSIO broker."),
Long: fmt.Sprintf("One-off sync to a HASSIO broker."),
DisableFlagParsing: false,
DisableFlagsInUseLine: false,
PreRunE: func(cmd *cobra.Command, args []string) error {
cmds.Error = cmds.SunGrowArgs(cmd, args)
if cmds.Error != nil {
return cmds.Error
}
2022-12-13 22:25:28 +11:00
cmds.Error = cmds.Mqtt.MqttArgs(cmd, args)
2022-10-07 23:12:47 +11:00
if cmds.Error != nil {
return cmds.Error
}
return nil
},
2022-12-13 22:25:28 +11:00
RunE: cmds.Mqtt.CmdMqttRun,
2022-10-07 23:12:47 +11:00
Args: cobra.RangeArgs(0, 1),
}
cmdMqtt.AddCommand(cmdMqttRun)
cmdMqttRun.Example = cmdHelp.PrintExamples(cmdMqttRun, "")
// ******************************************************************************** //
var cmdMqttSync = &cobra.Command{
Use: "sync",
Aliases: []string{""},
Short: fmt.Sprintf("Sync to a HASSIO MQTT broker."),
Long: fmt.Sprintf("Sync to a HASSIO MQTT broker."),
DisableFlagParsing: false,
DisableFlagsInUseLine: false,
PreRunE: func(cmd *cobra.Command, args []string) error {
cmds.Error = cmds.SunGrowArgs(cmd, args)
if cmds.Error != nil {
return cmds.Error
}
2022-12-13 22:25:28 +11:00
cmds.Error = cmds.Mqtt.MqttArgs(cmd, args)
2022-10-07 23:12:47 +11:00
if cmds.Error != nil {
return cmds.Error
}
return nil
},
2022-12-13 22:25:28 +11:00
RunE: cmds.Mqtt.CmdMqttSync,
2022-10-07 23:12:47 +11:00
Args: cobra.RangeArgs(0, 1),
}
cmdMqtt.AddCommand(cmdMqttSync)
cmdMqttSync.Example = cmdHelp.PrintExamples(cmdMqttSync, "", "all")
}
return c.SelfCmd
}
2022-04-21 10:47:05 +10:00
2022-10-07 23:12:47 +11:00
func (c *CmdMqtt) AttachFlags(cmd *cobra.Command, viper *viper.Viper) {
for range Only.Once {
cmd.PersistentFlags().StringVarP(&c.MqttUsername, flagMqttUsername, "", "", fmt.Sprintf("HASSIO: mqtt username."))
viper.SetDefault(flagMqttUsername, "")
cmd.PersistentFlags().StringVarP(&c.MqttPassword, flagMqttPassword, "", "", fmt.Sprintf("HASSIO: mqtt password."))
viper.SetDefault(flagMqttPassword, "")
cmd.PersistentFlags().StringVarP(&c.MqttHost, flagMqttHost, "", "", fmt.Sprintf("HASSIO: mqtt host."))
viper.SetDefault(flagMqttHost, "")
cmd.PersistentFlags().StringVarP(&c.MqttPort, flagMqttPort, "", "", fmt.Sprintf("HASSIO: mqtt port."))
viper.SetDefault(flagMqttPort, "")
}
}
2022-12-13 22:25:28 +11:00
func (c *CmdMqtt) MqttArgs(_ *cobra.Command, _ []string) error {
2022-10-07 23:12:47 +11:00
for range Only.Once {
2022-12-20 20:28:51 +11:00
c.LogInfo("Connecting to MQTT HASSIO Service...\n")
2022-12-13 22:25:28 +11:00
c.Client = mmHa.New(mmHa.Mqtt {
ClientId: DefaultServiceName,
EntityPrefix: DefaultServiceName,
Username: c.MqttUsername,
Password: c.MqttPassword,
Host: c.MqttHost,
Port: c.MqttPort,
2022-03-02 14:32:56 +11:00
})
2022-12-13 22:25:28 +11:00
c.Error = c.Client.GetError()
if c.Error != nil {
2022-03-02 14:32:56 +11:00
break
}
2022-02-11 18:30:45 +11:00
2022-12-20 20:28:51 +11:00
c.LogInfo("Connecting to SunGrow...\n")
2022-12-13 22:25:28 +11:00
c.Client.SungrowDevices, c.Error = cmds.Api.SunGrow.GetDeviceList()
if c.Error != nil {
2022-03-02 14:32:56 +11:00
break
}
2022-10-11 17:26:26 +11:00
2022-12-20 20:28:51 +11:00
c.LogInfo("Found SunGrow %d devices\n", len(c.Client.SungrowDevices))
2022-12-13 22:25:28 +11:00
c.Client.DeviceName = DefaultServiceName
2022-12-20 20:28:51 +11:00
_, c.Error = c.Client.SetDeviceConfig(
c.Client.DeviceName, c.Client.DeviceName,
"virtual", "virtual", "", DefaultServiceName,
2022-12-13 22:25:28 +11:00
DefaultServiceArea,
2022-10-11 17:26:26 +11:00
)
2022-12-13 22:25:28 +11:00
if c.Error != nil {
2022-10-11 17:26:26 +11:00
break
}
2022-12-20 20:28:51 +11:00
_, c.Error = c.Client.SetDeviceConfig(
c.Client.DeviceName, c.Client.DeviceName,
"system", "system", "", DefaultServiceName,
2022-12-13 22:25:28 +11:00
DefaultServiceArea,
2022-11-16 22:16:01 +11:00
)
2022-12-13 22:25:28 +11:00
if c.Error != nil {
2022-11-16 22:16:01 +11:00
break
}
2022-12-13 22:25:28 +11:00
for _, psId := range c.Client.SungrowDevices {
// ca.Error = ca.Mqtt.Mqtt.SetDeviceConfig(DefaultServiceName, strconv.FormatInt(id, 10), DefaultServiceName, model[0], "Sungrow", DefaultServiceArea)
2022-10-11 17:26:26 +11:00
parent := psId.PsId.String()
if parent == psId.PsKey.Value() {
2022-12-13 22:25:28 +11:00
parent = c.Client.DeviceName
2022-10-11 17:26:26 +11:00
}
2022-12-13 22:25:28 +11:00
2022-12-20 20:28:51 +11:00
_, c.Error = c.Client.SetDeviceConfig(
DefaultServiceName, DefaultServiceName,
psId.PsId.String(), psId.FactoryName.Value(), psId.FactoryName.Value(), psId.FactoryName.Value(),
2022-12-13 22:25:28 +11:00
DefaultServiceArea,
)
if c.Error != nil {
2022-10-11 17:26:26 +11:00
break
}
2022-12-13 22:25:28 +11:00
2022-12-20 20:28:51 +11:00
_, c.Error = c.Client.SetDeviceConfig(
DefaultServiceName, parent,
psId.PsKey.Value(), psId.DeviceName.Value(), psId.DeviceModel.Value(), psId.FactoryName.Value(),
2022-12-13 22:25:28 +11:00
DefaultServiceArea,
2022-12-10 09:40:28 +11:00
)
2022-12-13 22:25:28 +11:00
if c.Error != nil {
2022-12-10 09:40:28 +11:00
break
}
2022-12-13 22:25:28 +11:00
c.Client.SungrowPsIds[psId.PsId] = true
2022-10-11 17:26:26 +11:00
}
2022-02-11 18:30:45 +11:00
2022-12-13 22:25:28 +11:00
c.Error = c.Client.Connect()
if c.Error != nil {
2022-03-04 20:29:30 +11:00
break
}
2022-12-14 17:50:18 +11:00
2022-12-20 20:28:51 +11:00
c.Error = c.Options()
if c.Error != nil {
break
}
c.LogInfo("Caching Sungrow metadata...\n")
2022-12-14 17:50:18 +11:00
c.Error = c.GetEndPoints()
if c.Error != nil {
break
}
c.points, c.Error = cmds.Api.SunGrow.DevicePointAttrsMap(nil, "")
if c.Error != nil {
break
}
2022-12-20 20:28:51 +11:00
c.LogInfo("Cached %d Sungrow data points...\n", len(c.points))
2022-03-04 20:29:30 +11:00
}
2022-12-13 22:25:28 +11:00
return c.Error
2022-03-04 20:29:30 +11:00
}
2022-10-07 23:12:47 +11:00
func (c *CmdMqtt) CmdMqtt(cmd *cobra.Command, _ []string) error {
2022-03-04 20:29:30 +11:00
return cmd.Help()
}
2022-12-13 22:25:28 +11:00
func (c *CmdMqtt) CmdMqttRun(_ *cobra.Command, _ []string) error {
2022-03-04 20:29:30 +11:00
for range Only.Once {
2022-12-13 22:25:28 +11:00
c.Error = c.Cron()
if c.Error != nil {
2022-03-02 18:21:34 +11:00
break
2022-02-11 18:30:45 +11:00
}
2022-03-02 14:32:56 +11:00
2022-12-20 20:28:51 +11:00
c.LogInfo("Starting ticker...\n")
c.LogInfo("Fetch Schedule: %s\n", c.GetFetchSchedule())
c.LogInfo("Sleep Delay: %s\n", c.GetSleepDelay())
resolution := time.Second * 10
updateCounter := int(c.optionFetchSchedule / resolution)
timer := time.NewTicker(resolution)
2022-03-02 14:32:56 +11:00
for t := range timer.C {
2022-12-20 20:28:51 +11:00
if updateCounter >= 0 {
updateCounter--
c.LogDebug("Sleeping: %d\n", updateCounter)
2022-03-02 14:32:56 +11:00
continue
}
2022-12-20 20:28:51 +11:00
updateCounter = int(c.optionFetchSchedule / resolution)
c.LogDebug("Update: %s\n", t.String())
2022-12-13 22:25:28 +11:00
c.Error = c.Cron()
if c.Error != nil {
2022-03-02 14:32:56 +11:00
break
}
2022-03-04 20:29:30 +11:00
}
}
2022-12-13 22:25:28 +11:00
return c.Error
2022-03-04 20:29:30 +11:00
}
2022-12-13 22:25:28 +11:00
func (c *CmdMqtt) CmdMqttSync(_ *cobra.Command, args []string) error {
2022-03-04 20:29:30 +11:00
for range Only.Once {
// */1 * * * * /dir/command args args
cronString := "*/5 * * * *"
if len(args) > 0 {
cronString = strings.Join(args[0:5], " ")
cronString = strings.ReplaceAll(cronString, ".", "*")
2022-03-02 18:21:34 +11:00
}
2022-03-04 20:29:30 +11:00
2022-10-07 23:12:47 +11:00
cron := gocron.NewScheduler(time.UTC)
cron = cron.Cron(cronString)
cron = cron.SingletonMode()
2022-03-04 20:29:30 +11:00
2022-12-13 22:25:28 +11:00
c.Error = c.Cron()
if c.Error != nil {
2022-03-02 18:21:34 +11:00
break
2022-03-02 14:32:56 +11:00
}
2022-10-07 23:12:47 +11:00
var job *gocron.Job
2022-12-13 22:25:28 +11:00
job, c.Error = cron.Do(c.Cron)
if c.Error != nil {
2022-03-04 20:29:30 +11:00
break
}
2022-10-07 23:12:47 +11:00
job.IsRunning()
2022-03-02 14:32:56 +11:00
2022-12-20 20:28:51 +11:00
c.LogInfo("Created job schedule using '%s'\n", cronString)
2022-10-07 23:12:47 +11:00
cron.StartBlocking()
2022-12-13 22:25:28 +11:00
if c.Error != nil {
2022-03-04 20:29:30 +11:00
break
}
2022-03-02 14:32:56 +11:00
}
2022-12-13 22:25:28 +11:00
return c.Error
2022-03-02 14:32:56 +11:00
}
2022-12-13 22:25:28 +11:00
2022-12-20 20:28:51 +11:00
// -------------------------------------------------------------------------------- //
2022-12-13 22:25:28 +11:00
func (c *CmdMqtt) Cron() error {
2022-03-04 20:29:30 +11:00
for range Only.Once {
2022-12-13 22:25:28 +11:00
if c == nil {
c.Error = errors.New("mqtt not available")
2022-03-04 20:29:30 +11:00
break
}
2022-03-02 14:32:56 +11:00
2022-12-13 22:25:28 +11:00
if cmds.Api.SunGrow == nil {
c.Error = errors.New("sungrow not available")
2022-03-04 20:29:30 +11:00
break
}
2022-03-02 14:32:56 +11:00
2022-12-13 22:25:28 +11:00
if c.Client.IsFirstRun() {
c.Client.UnsetFirstRun()
2022-03-04 20:29:30 +11:00
} else {
2022-12-20 20:28:51 +11:00
c.LogDebug("Sleeping for %s...\n", c.GetSleepDelay())
time.Sleep(c.optionSleepDelay)
2022-03-04 20:29:30 +11:00
}
2022-02-11 18:30:45 +11:00
2022-04-21 10:47:05 +10:00
newDay := false
2022-12-13 22:25:28 +11:00
if c.Client.IsNewDay() {
2022-04-21 10:47:05 +10:00
newDay = true
}
2022-12-13 22:25:28 +11:00
data := cmds.Api.SunGrow.NewSunGrowData()
2022-11-04 17:34:30 +11:00
data.SetPsIds()
2022-11-28 22:27:18 +11:00
if data.Error != nil {
2022-12-13 22:25:28 +11:00
c.Error = data.Error
2022-11-28 22:27:18 +11:00
break
}
2022-10-13 12:01:27 +11:00
2022-12-13 22:25:28 +11:00
data.SetEndpoints(c.endpoints.Names()...)
c.Error = data.GetData()
if c.Error != nil {
2022-11-04 17:34:30 +11:00
break
}
2022-04-21 10:47:05 +10:00
2022-12-05 21:33:52 +11:00
for _, result := range data.Results {
2022-12-13 22:25:28 +11:00
c.Error = c.Update(result.EndPointName.String(), result.Response.Data, newDay)
if c.Error != nil {
2022-11-04 17:34:30 +11:00
break
2022-10-11 17:26:26 +11:00
}
2022-04-21 10:47:05 +10:00
}
2022-12-13 22:25:28 +11:00
c.Client.LastRefresh = time.Now()
2022-04-21 10:47:05 +10:00
}
2022-12-13 22:25:28 +11:00
if c.Error != nil {
2022-12-20 20:28:51 +11:00
c.LogError("%s\n", c.Error)
2022-04-21 10:47:05 +10:00
}
2022-12-13 22:25:28 +11:00
return c.Error
2022-04-21 10:47:05 +10:00
}
2022-12-13 22:25:28 +11:00
func (c *CmdMqtt) Update(endpoint string, data api.DataMap, newDay bool) error {
2022-04-21 10:47:05 +10:00
for range Only.Once {
2022-03-04 20:29:30 +11:00
// Also getPowerStatistics, getHouseholdStoragePsReport, getPsList, getUpTimePoint,
2022-12-20 20:28:51 +11:00
c.LogInfo("Syncing %d entries with HASSIO from %s.\n", len(data.Map), endpoint)
2022-10-13 12:01:27 +11:00
2022-11-16 22:16:01 +11:00
for o := range data.Map {
2022-10-19 01:37:11 +11:00
entries := data.Map[o]
2022-10-07 23:12:47 +11:00
r := entries.GetEntry(api.LastEntry) // Gets the last entry
2022-11-28 22:27:18 +11:00
2022-12-13 22:25:28 +11:00
if !r.Point.Valid {
// cmdLog.LogPrintDate("\n[%s] - invalid value - %s ...\n", r.Current.FieldPath.String(), r.Value.String())
2022-12-20 20:28:51 +11:00
c.LogDebug("Invalid: [%s] = '%s'\n", r.EndPoint, r.Value.String())
c.LogPlainInfo("?")
2022-12-13 22:25:28 +11:00
continue
}
if !c.endpoints.IsOK(r) {
continue
2022-10-12 22:01:47 +11:00
}
2022-12-13 22:25:28 +11:00
2022-12-21 10:13:24 +11:00
// if strings.Contains(r.EndPoint, "p13149") {
// fmt.Println()
// }
2022-12-14 17:50:18 +11:00
_ = c.UpdatePoint(r)
2022-12-19 20:27:41 +11:00
r.Value.UnitValueFix() // @TODO - Fix this up properly
2022-12-14 17:50:18 +11:00
2022-12-21 10:13:24 +11:00
// if strings.Contains(r.EndPoint, "p13149") {
// fmt.Println()
// }
2022-12-13 22:25:28 +11:00
var id string
var name string
switch {
case r.Point.GroupName == "alias":
id = mmHa.JoinStringsForId(r.Parent.Key, r.Point.Parents.Index[0], r.Point.Id)
name = mmHa.JoinStringsForName(" - ", r.Parent.Key, r.Point.Parents.Index[0], r.Point.Id)
case r.Point.GroupName != "":
id = r.EndPoint
name = mmHa.JoinStringsForName(" - ", r.Parent.Key, r.Point.Id, r.Point.GroupName, r.Point.Description)
default:
id = r.EndPoint
name = r.EndPoint
}
2022-12-10 09:40:28 +11:00
if r.Point.Unit == "" {
r.Point.Unit = r.Point.ValueType
}
if r.Point.Unit == "Bool" {
r.Point.Unit = mmHa.LabelBinarySensor
}
2022-12-13 22:25:28 +11:00
if r.Point.ValueType == "Bool" {
r.Point.Unit = mmHa.LabelBinarySensor
}
2022-10-12 22:01:47 +11:00
re := mmHa.EntityConfig {
2022-12-13 22:25:28 +11:00
Name: name, // mmHa.JoinStringsForName(" - ", id), // r.Point.Name, // PointName,
2022-04-21 16:24:40 +10:00
SubName: "",
2022-04-29 16:36:18 +10:00
ParentId: r.EndPoint,
2022-10-12 22:01:47 +11:00
ParentName: r.Parent.Key,
2022-12-01 22:32:38 +11:00
UniqueId: r.Point.Id,
2022-04-29 16:36:18 +10:00
// UniqueId: r.Id,
2022-12-13 22:25:28 +11:00
FullId: id, // string(r.FullId), // WAS r.Point.FullId
2022-04-29 16:36:18 +10:00
// FullName: r.Point.Name,
Units: r.Point.Unit,
2022-12-20 20:28:51 +11:00
// ValueName: r.Point.Description,
// ValueName: r.Point.Id,
2022-04-21 16:24:40 +10:00
DeviceClass: "",
2022-10-19 01:37:11 +11:00
StateClass: r.Point.UpdateFreq,
2022-12-20 20:28:51 +11:00
Value: &r.Value,
2022-12-19 20:27:41 +11:00
Point: r.Point,
2022-04-21 10:47:05 +10:00
2022-12-13 22:25:28 +11:00
LastReset: r.Point.WhenReset(),
2022-10-12 22:01:47 +11:00
// LastResetValueTemplate: "",
2022-04-21 10:47:05 +10:00
}
2022-12-13 22:25:28 +11:00
switch {
case r.Point.IsTotal():
re.StateClass = "total"
default:
re.StateClass = "measurement"
}
2022-12-21 10:13:24 +11:00
// if strings.Contains(r.EndPoint, "p13149") {
// fmt.Println()
// }
2022-10-12 22:01:47 +11:00
if newDay {
2022-12-20 20:28:51 +11:00
c.LogDebug("Config: [%s]\n", r.EndPoint)
c.LogPlainInfo("C")
2022-12-13 22:25:28 +11:00
c.Error = c.Client.BinarySensorPublishConfig(re)
if c.Error != nil {
2022-04-21 10:47:05 +10:00
break
}
2022-12-13 22:25:28 +11:00
c.Error = c.Client.SensorPublishConfig(re)
if c.Error != nil {
2022-04-21 10:47:05 +10:00
break
}
}
2022-10-11 17:26:26 +11:00
2022-12-20 20:28:51 +11:00
c.LogDebug("Update: [%s] = '%s' %s\n", r.EndPoint, r.Value.String(), r.Value.Unit())
c.LogPlainInfo("U")
2022-12-13 22:25:28 +11:00
c.Error = c.Client.BinarySensorPublishValue(re)
if c.Error != nil {
2022-04-21 10:47:05 +10:00
break
}
2022-12-13 22:25:28 +11:00
c.Error = c.Client.SensorPublishValue(re)
if c.Error != nil {
2022-04-21 10:47:05 +10:00
break
}
}
2022-12-20 20:28:51 +11:00
c.LogPlainInfo("\n")
2022-12-13 22:25:28 +11:00
}
return c.Error
}
func (c *CmdMqtt) GetEndPoints() error {
for range Only.Once {
fn := filepath.Join(cmds.ConfigDir, "mqtt_endpoints.json")
2022-12-14 17:50:18 +11:00
if !output.FileExists(fn) {
c.Error = output.PlainFileWrite(fn, []byte(DefaultMqttFile), 0644)
if c.Error != nil {
break
}
}
2022-12-13 22:25:28 +11:00
c.Error = output.FileRead(fn, &c.endpoints)
if c.Error != nil {
break
}
2022-12-14 17:50:18 +11:00
// All := []string{ "queryDeviceList", "getPsList", "getPsDetailWithPsType", "getPsDetail", "getKpiInfo"}
// All := []string{ "queryDeviceList", "getPsList", "getPsDetailWithPsType", "getPsDetail", "getKpiInfo"} //, queryMutiPointDataList, getDevicePointMinuteDataList }
// All := []string{ "WebIscmAppService.getDeviceModel" }
2022-12-13 22:25:28 +11:00
for name := range c.endpoints {
2022-12-20 20:28:51 +11:00
_, c.Error = c.Client.SetDeviceConfig(
DefaultServiceName, DefaultServiceName,
name, DefaultServiceName + "." + name, DefaultServiceName, DefaultVendor,
2022-12-13 22:25:28 +11:00
DefaultServiceArea,
)
if c.Error != nil {
break
}
}
}
return c.Error
}
2022-12-14 17:50:18 +11:00
func (c *CmdMqtt) UpdatePoint(entry *api.DataEntry) error {
for range Only.Once {
if !c.points.Exists(entry.Point.Id) {
// fmt.Printf("entry.Point: %s - NOT FOUND\n", entry.Point.Id)
break
}
p := c.points.Get(entry.Point.Id)
if p == nil {
// fmt.Printf("entry.Point: %s - FOUND - EMPTY\n", entry.Point.Id)
break
}
// {
// fmt.Printf("entry.Point: %s - FOUND - %v\n", entry.Point.Id, p)
// // fmt.Printf("\tValue - Description:'-'\t\tUnit:'%s'\tGroupName:'-'\tValueType:'%s'\n",
// // r.Value.UnitValue, r.Point.ValueType)
// fmt.Printf("\tDescription:'%s'\tPointName:'%s' - SAME:%t\n",
// entry.Point.Description, entry.Current.DataStructure.PointName, entry.Current.DataStructure.PointName == entry.Point.Description)
// fmt.Printf("\tUnit:'%s'\tPointUnit:'%s' - SAME:%t\n",
// entry.Point.Unit, entry.Current.DataStructure.PointUnit, entry.Current.DataStructure.PointUnit == entry.Point.Unit)
// fmt.Printf("\tGroupName:'%s'\tPointGroupName:'%s' - SAME:%t\n",
// entry.Point.GroupName, entry.Current.DataStructure.PointGroupName, entry.Current.DataStructure.PointGroupName == entry.Point.GroupName)
// fmt.Printf("\tValueType:'%s'\tValueType:'%s' - SAME:%t\n",
// entry.Point.ValueType, entry.Current.DataStructure.ValueType, entry.Current.DataStructure.ValueType == entry.Point.ValueType)
// }
2022-12-19 20:27:41 +11:00
// If Point description matches ...
if p.Name.String() == entry.Point.Description {
break
}
// If Point unit matches ...
if p.Unit.String() == entry.Point.Unit {
break
}
// If Point group name is set ...
if entry.Point.GroupName != "" {
break
2022-12-14 17:50:18 +11:00
}
2022-12-19 20:27:41 +11:00
// ... update the Point.
entry.Point.Description = p.Name.String()
entry.Point.Unit = p.Unit.String()
entry.Point.GroupName = p.PointGroupName
entry.Point.ValueType = p.UnitType.String()
// if (p.Name.String() != entry.Point.Description) && (p.Unit.String() != entry.Point.Unit) && (entry.Point.GroupName == "") {
// // fmt.Printf("\nNOT SAME\n")
// // fmt.Println("BEFORE:")
// // fmt.Printf("\tName:'%s'\tDescription:'%s'\n", p.Name, entry.Point.Description)
// // fmt.Printf("\tPointGroupId:'%s'\tGroupName:'%s'\n", p.PointGroupId, entry.Point.GroupName)
// // fmt.Printf("\tUnitType:'%s'\tValueType:'%s'\n", p.UnitType, entry.Point.ValueType)
// // fmt.Printf("\tUnit:'%s'\tUnit:'%s'\n", p.Unit, entry.Point.Unit)
//
// entry.Point.Description = p.Name.String()
// entry.Point.Unit = p.Unit.String()
// entry.Point.GroupName = p.PointGroupName
// entry.Point.ValueType = p.UnitType.String()
//
// // fmt.Println("AFTER:")
// // fmt.Printf("\tName:'%s'\tDescription:'%s'\n", p.Name, entry.Point.Description)
// // fmt.Printf("\tPointGroupId:'%s'\tGroupName:'%s'\n", p.PointGroupId, entry.Point.GroupName)
// // fmt.Printf("\tUnitType:'%s'\tValueType:'%s'\n", p.UnitType, entry.Point.ValueType)
// // fmt.Printf("\tUnit:'%s'\tUnit:'%s'\n", p.Unit, entry.Point.Unit)
// // fmt.Println("")
// }
2022-12-14 17:50:18 +11:00
}
return c.Error
}
2022-12-13 22:25:28 +11:00
2022-12-20 20:28:51 +11:00
// -------------------------------------------------------------------------------- //
const (
LogLevelDebug = 0
LogLevelInfo = iota
LogLevelWarning = iota
LogLevelError = iota
LogLevelDebugStr = "debug"
LogLevelInfoStr = "info"
LogLevelWarningStr = "warning"
LogLevelErrorStr = "error"
)
func (c *CmdMqtt) SetLogLevel(level string) {
switch strings.ToLower(level) {
case LogLevelDebugStr:
c.optionLogLevel = LogLevelDebug
case LogLevelInfoStr:
c.optionLogLevel = LogLevelInfo
case LogLevelWarningStr:
c.optionLogLevel = LogLevelWarning
case LogLevelErrorStr:
c.optionLogLevel = LogLevelError
default:
cmdLog.LogPrintDate("Unknown log level, setting to default.")
c.optionLogLevel = LogLevelInfo
}
}
func (c *CmdMqtt) GetLogLevel() string {
var ret string
switch c.optionLogLevel {
case LogLevelDebug:
ret = LogLevelDebugStr
case LogLevelInfo:
ret = LogLevelInfoStr
case LogLevelWarning:
ret = LogLevelWarningStr
case LogLevelError:
ret = LogLevelErrorStr
default:
ret = LogLevelInfoStr
}
return ret
}
func (c *CmdMqtt) LogDebug(format string, args ...interface{}) {
if LogLevelDebug >= c.optionLogLevel {
cmdLog.LogPrintDate("DEBUG: " + format, args...)
}
}
func (c *CmdMqtt) LogInfo(format string, args ...interface{}) {
if LogLevelInfo >= c.optionLogLevel {
cmdLog.LogPrintDate("INFO: " + format, args...)
}
}
func (c *CmdMqtt) LogWarning(format string, args ...interface{}) {
if LogLevelWarning >= c.optionLogLevel {
cmdLog.LogPrintDate("WARNING: " + format, args...)
}
}
func (c *CmdMqtt) LogError(format string, args ...interface{}) {
if LogLevelError >= c.optionLogLevel {
cmdLog.LogPrintDate("ERROR: " + format, args...)
}
}
func (c *CmdMqtt) LogPlainDebug(format string, args ...interface{}) {
if LogLevelDebug >= c.optionLogLevel {
fmt.Print(cmdLog.LogSprintf(format, args...))
}
}
func (c *CmdMqtt) LogPlainInfo(format string, args ...interface{}) {
if LogLevelInfo >= c.optionLogLevel {
fmt.Print(cmdLog.LogSprintf(format, args...))
}
}
func (c *CmdMqtt) LogPlainWarning(format string, args ...interface{}) {
if LogLevelWarning >= c.optionLogLevel {
fmt.Print(cmdLog.LogSprintf(format, args...))
}
}
func (c *CmdMqtt) LogPlainError(format string, args ...interface{}) {
if LogLevelError >= c.optionLogLevel {
fmt.Print(cmdLog.LogSprintf(format, args...))
}
}
const (
OptionLogLevel = "loglevel"
OptionFetchSchedule = "fetchschedule"
OptionSleepDelay = "sleepdelay"
OptionServiceState = "servicestate"
)
func (c *CmdMqtt) Options() error {
for range Only.Once {
c.Error = c.Client.SetOption(OptionLogLevel, "Log Level",
c.optionFuncLogLevel,
LogLevelErrorStr, LogLevelWarningStr, LogLevelInfoStr, LogLevelDebugStr)
if c.Error != nil {
break
}
c.Error = c.Client.SetOptionValue(OptionLogLevel, c.GetLogLevel())
if c.Error != nil {
break
}
c.Error = c.Client.SetOption(OptionFetchSchedule, "Fetch Schedule",
c.optionFuncFetchSchedule,
"2m", "3m", "4m", "5m", "6m", "7m", "8m", "9m", "10m")
if c.Error != nil {
break
}
c.Error = c.Client.SetOptionValue(OptionFetchSchedule, c.GetFetchSchedule())
if c.Error != nil {
break
}
c.Error = c.Client.SetOption(OptionSleepDelay, "Sleep Delay After Schedule",
c.optionFuncSleepDelay,
"0s", "10s", "20s", "30s", "40s", "50s", "60s")
if c.Error != nil {
break
}
c.Error = c.Client.SetOptionValue(OptionSleepDelay, c.GetSleepDelay())
if c.Error != nil {
break
}
c.Error = c.Client.SetOption(OptionServiceState, "Service State",
c.optionFuncServiceState,
"Run", "Restart", "Stop")
if c.Error != nil {
break
}
c.Error = c.Client.SetOptionValue(OptionServiceState, "Run")
if c.Error != nil {
break
}
}
return c.Error
}
func (c *CmdMqtt) optionFuncLogLevel(_ mqtt.Client, msg mqtt.Message) {
for range Only.Once {
request := strings.ToLower(string(msg.Payload()))
c.LogInfo("Option[%s] set to '%s'\n", OptionLogLevel, request)
c.SetLogLevel(request)
c.Error = c.Client.SetOptionValue(OptionLogLevel, request)
if c.Error != nil {
c.LogError("%s\n", c.Error)
break
}
}
}
func (c *CmdMqtt) optionFuncFetchSchedule(_ mqtt.Client, msg mqtt.Message) {
for range Only.Once {
request := strings.ToLower(string(msg.Payload()))
c.LogInfo("Option[%s] set to '%s'\n", OptionFetchSchedule, request)
c.optionFetchSchedule, c.Error = time.ParseDuration(request)
if c.Error != nil {
c.LogError("%s\n", c.Error)
break
}
c.Error = c.Client.SetOptionValue(OptionFetchSchedule, c.GetFetchSchedule())
if c.Error != nil {
c.LogError("%s\n", c.Error)
break
}
}
}
func (c *CmdMqtt) GetFetchSchedule() string {
return fmt.Sprintf("%.0fm", c.optionFetchSchedule.Minutes())
}
func (c *CmdMqtt) optionFuncSleepDelay(_ mqtt.Client, msg mqtt.Message) {
for range Only.Once {
request := strings.ToLower(string(msg.Payload()))
c.LogInfo("Option[%s] set to '%s'\n", OptionSleepDelay, request)
c.optionSleepDelay, c.Error = time.ParseDuration(request)
if c.Error != nil {
c.LogError("%s\n", c.Error)
break
}
c.Error = c.Client.SetOptionValue(OptionSleepDelay, request)
if c.Error != nil {
c.LogError("%s\n", c.Error)
break
}
}
}
func (c *CmdMqtt) GetSleepDelay() string {
return fmt.Sprintf("%.0fs", c.optionSleepDelay.Seconds())
}
func (c *CmdMqtt) optionFuncServiceState(_ mqtt.Client, msg mqtt.Message) {
for range Only.Once {
request := strings.ToLower(string(msg.Payload()))
c.LogInfo("Option[%s] set to '%s'\n", OptionServiceState, request)
switch request {
case "Run":
case "Restart":
case "Stop":
}
c.Error = c.Client.SetOptionValue(OptionServiceState, request)
if c.Error != nil {
c.LogError("%s\n", c.Error)
break
}
}
}
// -------------------------------------------------------------------------------- //
2022-12-13 22:25:28 +11:00
type MqttEndPoints map[string]MqttEndPoint
type MqttEndPoint struct {
Include []string `json:"include"`
Exclude []string `json:"exclude"`
}
func (c *MqttEndPoints) Names() []string {
var ret []string
for name := range *c {
ret = append(ret, name)
}
return ret
}
func (c *MqttEndPoints) IsOK(check *api.DataEntry) bool {
var yes bool
for range Only.Once {
field := check.Current.GetFieldPath()
name := field.First()
var ep MqttEndPoint
if ep, yes = (*c)[name]; !yes {
yes = false
break
}
if len(ep.Include) == 0 {
yes = false
break
}
for _, reStr := range ep.Exclude {
reStr = strings.ReplaceAll(reStr, `.`, `\.`)
reStr = strings.ReplaceAll(reStr, `*`, `.*?`)
reStr = "^" + strings.TrimPrefix(reStr, "^")
re := regexp.MustCompile(reStr)
if re.MatchString(check.EndPoint) {
yes = false
break
}
if re.MatchString(check.Current.FieldPath.String()) {
yes = false
break
}
if re.MatchString(check.Current.DataStructure.Endpoint.String()) {
yes = false
break
}
}
for _, reStr := range ep.Include {
reStr = strings.ReplaceAll(reStr, `.`, `\.`)
reStr = strings.ReplaceAll(reStr, `*`, `.*`)
reStr = "^" + strings.TrimPrefix(reStr, "^")
re := regexp.MustCompile(reStr)
if re.MatchString(check.EndPoint) {
yes = true
break
}
if re.MatchString(check.Current.FieldPath.String()) {
yes = true
break
}
if re.MatchString(check.Current.DataStructure.Endpoint.String()) {
yes = true
break
}
}
2022-03-04 20:29:30 +11:00
}
2022-12-13 22:25:28 +11:00
return yes
2022-02-11 18:30:45 +11:00
}
2022-12-14 17:50:18 +11:00
const DefaultMqttFile = `{
"queryDeviceList": {
"include": [
"virtual.*"
],
"exclude": [
"queryDeviceList.*.devices.*",
"queryDeviceList.*.device_types.*"
]
},
"getPsList": {
"include": [
"virtual.*"
],
"exclude": [
]
2022-12-15 21:15:24 +11:00
},
2022-12-14 17:50:18 +11:00
"getPsDetail": {
"include": [
"virtual.*"
],
"exclude": [
]
}
}
2022-12-15 21:15:24 +11:00
`