diff options
author | JeffB42 <10328858+JeffB42@users.noreply.github.com> | 2022-04-10 18:53:08 +0300 |
---|---|---|
committer | JeffB42 <10328858+JeffB42@users.noreply.github.com> | 2022-04-10 18:53:08 +0300 |
commit | d0a5cc9cd7fd80ba2eb67192afead58f1a76282b (patch) | |
tree | 3a825bbe6b6c0dfd2611e6271443c167c40dddca | |
parent | 42e3607c1f99f699405c4244674b9b07cb860d14 (diff) |
consilodated code into createBackgroundTask(), added GetExperimentalFrequency(), overhauled ui.go to use ConnectionManager
-rwxr-xr-x | ui/ConnectionPanel.go | 61 | ||||
-rwxr-xr-x | ui/IdleStatusPanel.go | 35 | ||||
-rwxr-xr-x | ui/NetworkPanel.go | 37 | ||||
-rwxr-xr-x | ui/PrintStatusPanel.go | 55 | ||||
-rwxr-xr-x | ui/ui.go | 223 | ||||
-rwxr-xr-x | utils/BackgroundTask.go | 30 | ||||
-rwxr-xr-x | utils/ConnectionManager.go | 176 | ||||
-rwxr-xr-x | utils/SystemDHeartbeat.go | 39 |
8 files changed, 359 insertions, 297 deletions
diff --git a/ui/ConnectionPanel.go b/ui/ConnectionPanel.go index 6bffac3..accbeb6 100755 --- a/ui/ConnectionPanel.go +++ b/ui/ConnectionPanel.go @@ -2,11 +2,11 @@ package ui import ( "fmt" - "os" - "strconv" + // "os" + // "strconv" // "strings" // "sync" - "time" + // "time" "github.com/gotk3/gotk3/gdk" "github.com/gotk3/gotk3/gtk" @@ -45,6 +45,7 @@ func GetConnectionPanelInstance( IsCheckingConnection: true, } instance.initialize() + instance.createBackgroundTask() connectionPanelInstance = instance } @@ -97,8 +98,6 @@ func (this *connectionPanel) initialize() { box.Add(this.ActionBar) this.Grid().Add(box) - this.createBackgroundTask() - logger.TraceLeave("ConnectionPanel.initialize()") } @@ -108,7 +107,7 @@ func (this *connectionPanel) createActionBar() { this.ActionBar = utils.MustBox(gtk.ORIENTATION_HORIZONTAL, 5) this.ActionBar.SetHAlign(gtk.ALIGN_END) - this.RetryButton = utils.MustButtonImageStyle("Retry", "refresh.svg", "color-none", this.attemptToConnect) + this.RetryButton = utils.MustButtonImageStyle("Retry", "refresh.svg", "color-none", this.initializeConnectionState) this.RetryButton.SetProperty("width-request", this.Scaled(100)) this.ActionBar.Add(this.RetryButton) @@ -132,26 +131,13 @@ func (this *connectionPanel) displayButtons(display bool) { func (this *connectionPanel) createBackgroundTask() { logger.TraceEnter("ConnectionPanel.createBackgroundTask()") - // Default timeout of 10 seconds. - duration := time.Second * 10 - - // Experimental, set the timeout based on config setting, but only if the config is pressent. - updateFrequency := os.Getenv("EXPERIMENTAL_CONNECTION_PANEL_UPDATE_FREQUENCY") - if updateFrequency != "" { - logger.Infof("ConnectionPanel.createBackgroundTask() - EXPERIMENTAL_CONNECTION_PANEL_UPDATE_FREQUENCY is present, frequency is %s", updateFrequency) - val, err := strconv.Atoi(updateFrequency) - if err == nil { - duration = time.Second * time.Duration(val) - } else { - logger.LogError("ConnectionPanel.createBackgroundTask()", "strconv.Atoi()", err) - } - } + this.initializeConnectionState() + // Default timeout of 5 seconds. + duration := utils.GetExperimentalFrequency(5, "EXPERIMENTAL_CONNECTION_PANEL_UPDATE_FREQUENCY") this.backgroundTask = utils.CreateBackgroundTask(duration, this.update) this.backgroundTask.Start() - this.attemptToConnect() - logger.TraceLeave("ConnectionPanel.createBackgroundTask()") } @@ -159,48 +145,53 @@ func (this *connectionPanel) update() { logger.TraceEnter("ConnectionPanel.update()") connectionManager := utils.GetConnectionManagerInstance(this.UI.Client) - connectionManager.UpdateStatus() + // connectionManager.UpdateStatus() msg := "" if connectionManager.IsConnectedToOctoPrint != true { - if connectionManager.ConnectAttempts > utils.MAX_CONNECTION_ATTEMPTS { + if connectionManager.ConnectAttempts >= utils.MAX_CONNECTION_ATTEMPTS { msg = fmt.Sprintf("Unable to connect to OctoPrint") this.displayButtons(true) + } else if connectionManager.ConnectAttempts == 0 { + msg = fmt.Sprintf("Attempting to connect to OctoPrint") } else { - msg = fmt.Sprintf("Attempting to connect to OctoPrint...%d", connectionManager.ConnectAttempts) + msg = fmt.Sprintf("Attempting to connect to OctoPrint...%d", connectionManager.ConnectAttempts + 1) } } else if connectionManager.IsConnectedToPrinter != true { - if connectionManager.ConnectAttempts > utils.MAX_CONNECTION_ATTEMPTS { + if connectionManager.ConnectAttempts >= utils.MAX_CONNECTION_ATTEMPTS { msg = fmt.Sprintf("Unable to connect to the printer") this.displayButtons(true) + } else if connectionManager.ConnectAttempts == 0 { + msg = fmt.Sprintf("Attempting to connect to the printer") } else { - msg = fmt.Sprintf("Attempting to connect to the printer...%d", connectionManager.ConnectAttempts) + msg = fmt.Sprintf("Attempting to connect to the printer...%d", connectionManager.ConnectAttempts + 1) } + } + + if msg != "" { + this.Label.SetText(msg) + connectionManager.UpdateStatus() } else { currentPanel := this.UI.PanelHistory.Peek().(interfaces.IPanel) if currentPanel.Name() == "ConnectionPanel" { this.UI.Update() this.UI.GoToPanel(GetIdleStatusPanelInstance(this.UI)) - logger.TraceLeave("ConnectionPanel.update()") } - return } - this.Label.SetText(msg) - logger.TraceLeave("ConnectionPanel.update()") } -func (this *connectionPanel) attemptToConnect() { - logger.TraceEnter("ConnectionPanel.attemptToConnect()") +func (this *connectionPanel) initializeConnectionState() { + logger.TraceEnter("ConnectionPanel.initializeConnectionState()") this.displayButtons(false) this.Label.SetText("Attempting to connect to OctoPrint") connectionManager := utils.GetConnectionManagerInstance(this.UI.Client) - connectionManager.InitializeConnectionState() + connectionManager.ReInitializeConnectionState() - logger.TraceLeave("ConnectionPanel.attemptToConnect()") + logger.TraceLeave("ConnectionPanel.initializeConnectionState()") } func (this *connectionPanel) showSystem() { diff --git a/ui/IdleStatusPanel.go b/ui/IdleStatusPanel.go index f911b6a..e9b4e61 100755 --- a/ui/IdleStatusPanel.go +++ b/ui/IdleStatusPanel.go @@ -3,10 +3,10 @@ package ui import ( // "encoding/json" // "fmt" - "os" - "strconv" + // "os" + // "strconv" // "sync" - "time" + // "time" "github.com/Z-Bolt/OctoScreen/octoprintApis" "github.com/Z-Bolt/OctoScreen/octoprintApis/dataModels" @@ -34,22 +34,9 @@ func GetIdleStatusPanelInstance(ui *UI) *idleStatusPanel { CommonPanel: CreateTopLevelCommonPanel("IdleStatusPanel", ui), } - // Default timeout of 20 seconds. - duration := time.Second * 20 - - // Experimental, set the timeout based on config setting, but only if the config is pressent. - updateFrequency := os.Getenv("EXPERIMENTAL_IDLE_UPDATE_FREQUENCY") - if updateFrequency != "" { - logger.Infof("Ui.New() - EXPERIMENTAL_IDLE_UPDATE_FREQUENCY is present, frequency is %s", updateFrequency) - val, err := strconv.Atoi(updateFrequency) - if err == nil { - duration = time.Second * time.Duration(val) - } else { - logger.LogError("Ui.New()", "strconv.Atoi()", err) - } - } - - instance.backgroundTask = utils.CreateBackgroundTask(duration, instance.update) + // TODO: revisit... in some places the background task is created and then initialize() is called, + // and others places initialize() is called and then the background task is created + instance.createBackgroundTask() instance.initialize() idleStatusPanelInstance = instance @@ -58,6 +45,16 @@ func GetIdleStatusPanelInstance(ui *UI) *idleStatusPanel { return idleStatusPanelInstance } +func (this *idleStatusPanel) createBackgroundTask() { + logger.TraceEnter("IdleStatusPanel.createBackgroundTask()") + + // Default timeout of 20 seconds. + duration := utils.GetExperimentalFrequency(20, "EXPERIMENTAL_IDLE_UPDATE_FREQUENCY") + this.backgroundTask = utils.CreateBackgroundTask(duration, this.update) + + logger.TraceLeave("IdleStatusPanel.createBackgroundTask()") +} + func (this *idleStatusPanel) initialize() { logger.TraceEnter("IdleStatusPanel.initialize()") diff --git a/ui/NetworkPanel.go b/ui/NetworkPanel.go index e3894f7..0e70d5c 100755 --- a/ui/NetworkPanel.go +++ b/ui/NetworkPanel.go @@ -3,9 +3,9 @@ package ui import ( "fmt" "net" - "os" - "strconv" - "time" + // "os" + // "strconv" + // "time" "pifke.org/wpasupplicant" "github.com/gotk3/gotk3/gtk" @@ -35,23 +35,8 @@ func GetNetworkPanelInstance( CommonPanel: CreateCommonPanel("NetworkPanel", ui), } instance.initialize() + instance.createBackgroundTask() - // Default timeout of 30 seconds. - duration := time.Second * 30 - - // Experimental, set the timeout based on config setting, but only if the config is pressent. - updateFrequency := os.Getenv("EXPERIMENTAL_NETWORK_UPDATE_FREQUENCY") - if updateFrequency != "" { - logger.Infof("Ui.New() - EXPERIMENTAL_NETWORK_UPDATE_FREQUENCY is present, frequency is %s", updateFrequency) - val, err := strconv.Atoi(updateFrequency) - if err == nil { - duration = time.Second * time.Duration(val) - } else { - logger.LogError("Ui.New()", "strconv.Atoi()", err) - } - } - - instance.backgroundTask = utils.CreateBackgroundTask(duration, instance.update) networkPanelInstance = instance } @@ -66,15 +51,25 @@ func (this *networkPanel) initialize() { this.overrideForDebugging = false; } +func (this *networkPanel) createBackgroundTask() { + logger.TraceEnter("NetworkPanel.createBackgroundTask()") + + // Default timeout of 30 seconds. + duration := utils.GetExperimentalFrequency(30, "EXPERIMENTAL_NETWORK_UPDATE_FREQUENCY") + this.backgroundTask = utils.CreateBackgroundTask(duration, this.update) + + logger.TraceLeave("NetworkPanel.createBackgroundTask()") +} + func (this *networkPanel) update() { - logger.TraceEnter("networkPanel.update()") + logger.TraceEnter("NetworkPanel.update()") utils.EmptyTheContainer(&this.listBox.Container) this.setNetStatusText() this.setNetworkItems() this.listBox.ShowAll() - logger.TraceLeave("networkPanel.update()") + logger.TraceLeave("NetworkPanel.update()") } func (this *networkPanel) setNetStatusText() { diff --git a/ui/PrintStatusPanel.go b/ui/PrintStatusPanel.go index 72c87ec..fcee0ac 100755 --- a/ui/PrintStatusPanel.go +++ b/ui/PrintStatusPanel.go @@ -2,8 +2,8 @@ package ui import ( "fmt" - "os" - "strconv" + // "os" + // "strconv" "strings" "time" @@ -45,24 +45,9 @@ func GetPrintStatusPanelInstance(ui *UI) *printStatusPanel { CommonPanel: CreateTopLevelCommonPanel("PrintStatusPanel", ui), } - // Default timeout of 20 seconds. - duration := time.Second * 20 - - // Experimental, set the timeout based on config setting, but only if the config is pressent. - updateFrequency := os.Getenv("EXPERIMENTAL_PRINT_UPDATE_FREQUENCY") - if updateFrequency != "" { - logger.Infof("Ui.New() - EXPERIMENTAL_PRINT_UPDATE_FREQUENCY is present, frequency is %s", updateFrequency) - val, err := strconv.Atoi(updateFrequency) - if err == nil { - duration = time.Second * time.Duration(val) - } else { - logger.LogError("Ui.New()", "strconv.Atoi()", err) - } - } - - // TODO: revisit... some set the background task and then initialize - // and others initialize and then set the background task - instance.backgroundTask = utils.CreateBackgroundTask(duration, instance.update) + // TODO: revisit... in some places the background task is created and then initialize() is called, + // and others places initialize() is called and then the background task is created + instance.createBackgroundTask() instance.initialize() printStatusPanelInstance = instance } @@ -70,6 +55,12 @@ func GetPrintStatusPanelInstance(ui *UI) *printStatusPanel { return printStatusPanelInstance } +func (this *printStatusPanel) createBackgroundTask() { + // Default timeout of 20 seconds. + duration := utils.GetExperimentalFrequency(20, "EXPERIMENTAL_PRINT_UPDATE_FREQUENCY") + this.backgroundTask = utils.CreateBackgroundTask(duration, this.update) +} + func (this *printStatusPanel) initialize() { defer this.Initialize() @@ -183,7 +174,7 @@ func (this *printStatusPanel) createPauseButton() gtk.IWidget { logger.Info("Pausing/Resuming job 2, Do() was just called") if err != nil { - logger.LogError("print_status.createPauseButton()", "Do(PauseRequest)", err) + logger.LogError("PrintStatusPanel.createPauseButton()", "Do(PauseRequest)", err) return } @@ -217,21 +208,21 @@ func (this *printStatusPanel) createControlButton() gtk.IWidget { } func (this *printStatusPanel) update() { - logger.TraceEnter("printStatusPanel.update()") + logger.TraceEnter("PrintStatusPanel.update()") this.updateTemperature() this.updateJob() - logger.TraceLeave("printStatusPanel.update()") + logger.TraceLeave("PrintStatusPanel.update()") } func (this *printStatusPanel) updateTemperature() { - logger.TraceEnter("printStatusPanel.updateTemperature()") + logger.TraceEnter("PrintStatusPanel.updateTemperature()") fullStateResponse, err := (&octoprintApis.FullStateRequest{Exclude: []string{"sd"}}).Do(this.UI.Client) if err != nil { - logger.LogError("print_status.updateTemperature()", "Do(StateRequest)", err) - logger.TraceLeave("printStatusPanel.updateTemperature()") + logger.LogError("PrintStatusPanel.updateTemperature()", "Do(StateRequest)", err) + logger.TraceLeave("PrintStatusPanel.updateTemperature()") return } @@ -257,7 +248,7 @@ func (this *printStatusPanel) updateTemperature() { } } - logger.TraceLeave("printStatusPanel.updateTemperature()") + logger.TraceLeave("PrintStatusPanel.updateTemperature()") } func (this *printStatusPanel) doUpdateState(printerState *dataModels.PrinterState) { @@ -318,12 +309,12 @@ func (this *printStatusPanel) doUpdateState(printerState *dataModels.PrinterStat } func (this *printStatusPanel) updateJob() { - logger.TraceEnter("printStatusPanel.updateJob()") + logger.TraceEnter("PrintStatusPanel.updateJob()") jobResponse, err := (&octoprintApis.JobRequest{}).Do(this.UI.Client) if err != nil { - logger.LogError("print_status.updateJob()", "Do(JobRequest)", err) - logger.TraceLeave("printStatusPanel.updateJob()") + logger.LogError("PrintStatusPanel.updateJob()", "Do(JobRequest)", err) + logger.TraceLeave("PrintStatusPanel.updateJob()") return } @@ -359,7 +350,7 @@ func (this *printStatusPanel) updateJob() { this.timeLabel.Label.SetLabel(timeSpent) this.timeLeftLabel.Label.SetLabel(timeLeft) - logger.TraceLeave("printStatusPanel.updateJob()") + logger.TraceLeave("PrintStatusPanel.updateJob()") } func confirmStopDialogBox( @@ -392,7 +383,7 @@ func confirmStopDialogBox( if userResponse == int(gtk.RESPONSE_YES) { logger.Warn("Stopping job") if err := (&octoprintApis.CancelRequest{}).Do(printStatusPanel.UI.Client); err != nil { - logger.LogError("print_status.confirmStopDialogBox()", "Do(CancelRequest)", err) + logger.LogError("PrintStatusPanel.confirmStopDialogBox()", "Do(CancelRequest)", err) return } } @@ -2,8 +2,8 @@ package ui import ( "fmt" - "os" - "strconv" + // "os" + // "strconv" "strings" "sync" "time" @@ -35,7 +35,7 @@ type UI struct { NotificationsBox *uiWidgets.NotificationsBox - splashPanel *SplashPanel + // splashPanel *SplashPanel backgroundTask *utils.BackgroundTask grid *gtk.Grid window *gtk.Window @@ -80,62 +80,63 @@ func CreateUi() *UI { height: height, } - instance.window.Connect("configure-event", func(win *gtk.Window) { + instance.initialize1() + + logger.TraceLeave("ui.CreateUi()") + + return instance +} + +func (this *UI) initialize1() { + logger.TraceEnter("ui.initialize1()") + + this.window.Connect("configure-event", func(win *gtk.Window) { allocatedWidth:= win.GetAllocatedWidth() allocatedHeight:= win.GetAllocatedHeight() sizeWidth, sizeHeight := win.GetSize() - if (allocatedWidth > width || allocatedHeight > height) || - (sizeWidth > width || sizeHeight > height) { - logger.Errorf("Window resize went past max size. allocatedWidth:%d allocatedHeight:%d sizeWidth:%d sizeHeight:%d", + if (allocatedWidth > this.width || allocatedHeight > this.height) || + (sizeWidth > this.width || sizeHeight > this.height) { + logger.Errorf( + "Window resize went past max size. allocatedWidth:%d allocatedHeight:%d sizeWidth:%d sizeHeight:%d", allocatedWidth, allocatedHeight, sizeWidth, - sizeHeight) - logger.Errorf("Window resize went past max size. Target width and height: %dx%d", - width, - height) + sizeHeight, + ) + logger.Errorf( + "Window resize went past max size. Target width and height: %dx%d", + this.width, + this.height, + ) } }) switch { - case width > 480: - instance.scaleFactor = 2 + case this.width > 480: + this.scaleFactor = 2 - case width > 1000: - instance.scaleFactor = 3 + case this.width > 1000: + this.scaleFactor = 3 default: - instance.scaleFactor = 1 + this.scaleFactor = 1 } - instance.splashPanel = CreateSplashPanel(instance) + // this.splashPanel = NewSplashPanel(this) - // Default timeout of 20 seconds. - duration := time.Second * 20 + this.initialize2() - // Experimental, set the timeout based on config setting, but only if the config is pressent. - updateFrequency := os.Getenv("EXPERIMENTAL_UI_UPDATE_FREQUENCY") - if updateFrequency != "" { - logger.Infof("ui.CreateUi() - EXPERIMENTAL_UI_UPDATE_FREQUENCY is present, frequency is %s", updateFrequency) - val, err := strconv.Atoi(updateFrequency) - if err == nil { - duration = time.Second * time.Duration(val) - } else { - logger.LogError("ui.CreateUi()", "strconv.Atoi()", err) - } - } - - instance.backgroundTask = utils.CreateBackgroundTask(duration, instance.Update) - instance.initialize() - - logger.TraceLeave("ui.CreateUi()") + // this.GoToPanel(NewSplashPanel(this)) + // this.GoToPanel(IdleStatusPanel(this)) + // this.GoToPanel(ConnectToNetworkPanel(this)) + this.GoToPanel(GetConnectionPanelInstance(this)) - return instance + logger.TraceLeave("ui.initialize1()") } -func (this *UI) initialize() { - logger.TraceEnter("ui.initialize()") +func (this *UI) initialize2() { + logger.TraceEnter("ui.initialize2()") defer this.window.ShowAll() this.loadStyle() @@ -144,7 +145,9 @@ func (this *UI) initialize() { this.window.SetDefaultSize(this.width, this.height) this.window.SetResizable(false) + this.createBackgroundTask() this.window.Connect("show", this.backgroundTask.Start) + this.window.Connect("destroy", func() { logger.Debug("window destroy callback was called, now executing MainQuit()") gtk.MainQuit() @@ -156,9 +159,30 @@ func (this *UI) initialize() { this.grid = utils.MustGrid() overlay.Add(this.grid) - logger.TraceLeave("ui.initialize()") + // connectionManager := utils.GetConnectionManagerInstance(this.Client) + // connectionManager.AttemptToConnect() + + logger.TraceLeave("ui.initialize2()") } +func (this *UI) createBackgroundTask() { + logger.TraceEnter("ui.createBackgroundTask()") + + // Default timeout of 10 seconds. + duration := utils.GetExperimentalFrequency(10, "EXPERIMENTAL_UI_UPDATE_FREQUENCY") + this.backgroundTask = utils.CreateBackgroundTask(duration, this.Update) + + logger.TraceLeave("ui.createBackgroundTask()") +} + + + + + + + + + func (this *UI) loadStyle() { logger.TraceEnter("ui.loadStyle()") @@ -176,8 +200,51 @@ func (this *UI) loadStyle() { logger.TraceLeave("ui.loadStyle()") } -var errMercyPeriod = time.Second * 10 +func (this *UI) Update() { + logger.TraceEnter("ui.update()") + + /* + if this.connectionAttempts > 8 { + logger.Info("ui.update() - this.connectionAttempts > 8") + this.splashPanel.putOnHold() + + logger.TraceLeave("ui.update()") + return + } + + logger.Infof("ui.update() - this.UIState is: %q", this.UIState) + + if this.UIState == "splash" { + this.connectionAttempts++ + } else { + this.connectionAttempts = 0 + } + + this.verifyConnection() + + if this.OctoPrintPluginIsAvailable { + this.checkNotification() + } + */ + + connectionManager := utils.GetConnectionManagerInstance(this.Client) + if connectionManager.IsConnectedToOctoPrint == true { + if this.Settings == nil { + this.loadSettings() + } + } + + + + logger.TraceLeave("ui.update()") +} + + + + + +/* func (this *UI) verifyConnection() { logger.TraceEnter("ui.verifyConnection()") @@ -212,7 +279,7 @@ func (this *UI) verifyConnection() { logger.Debugf("ui.verifyConnection() - newUIState is now: %s", newUIState) } - this.splashPanel.Label.SetText(splashMessage) + // this.splashPanel.Label.SetText(splashMessage) defer func() { this.setUiState(newUIState, splashMessage) @@ -220,7 +287,9 @@ func (this *UI) verifyConnection() { logger.TraceLeave("ui.verifyConnection()") } +*/ +/* func (this *UI) getUiStateAndMessageFromConnectionResponse( connectionResponse *dataModels.ConnectionResponse, newUIState string, @@ -273,10 +342,25 @@ func (this *UI) getUiStateAndMessageFromConnectionResponse( } logger.TraceLeave("ui.getUiStateAndMessageFromConnectionResponse()") - return newUIState, splashMessage } +*/ + +// ********************************** + + + + + + + + +// var errMercyPeriod = time.Second * 10 + + + +/* func (this *UI) getUiStateAndMessageFromError( err error, newUIState string, @@ -307,17 +391,18 @@ func (this *UI) getUiStateAndMessageFromError( } logger.TraceLeave("ui.getUiStateAndMessageFromError()") - return newUIState, splashMessage } +*/ +/* func (this *UI) setUiState( newUiState string, splashMessage string, ) { logger.TraceEnter("ui.setUiState()") - this.splashPanel.Label.SetText(splashMessage) + // this.splashPanel.Label.SetText(splashMessage) if newUiState == this.UIState { logger.Infof("ui.setUiState() - newUiState and ui.UIState are the same (%q)", this.UIState) @@ -333,14 +418,14 @@ func (this *UI) setUiState( switch newUiState { case "idle": logger.Info("ui.setUiState() - printer is ready") - this.GoToPanel(GetIdleStatusPanelInstance(this)) + this.GoToPanel(IdleStatusPanel(this)) case "printing": logger.Info("ui.setUiState() - printing a job") - this.GoToPanel(GetPrintStatusPanelInstance(this)) + this.GoToPanel(PrintStatusPanel(this)) - case "splash": - this.GoToPanel(this.splashPanel) + // case "splash": + // this.GoToPanel(this.splashPanel) default: logger.Errorf("ERROR: ui.setUiState() - unknown newUiState case: %q", newUiState) @@ -348,7 +433,9 @@ func (this *UI) setUiState( logger.TraceLeave("ui.setUiState()") } +*/ +/* func (this *UI) checkNotification() { logger.TraceEnter("ui.checkNotification()") @@ -371,6 +458,8 @@ func (this *UI) checkNotification() { logger.TraceLeave("ui.checkNotification()") } +*/ + func (this *UI) loadSettings() { logger.TraceEnter("ui.loadSettings()") @@ -468,34 +557,6 @@ func (this *UI) validateMenuItems(menuItems []dataModels.MenuItem, name string, return true } -func (this *UI) Update() { - logger.TraceEnter("ui.Update()") - - if this.connectionAttempts > 8 { - logger.Info("ui.Update() - this.connectionAttempts > 8") - this.splashPanel.putOnHold() - - logger.TraceLeave("ui.Update()") - return - } - - logger.Infof("ui.Update() - this.UIState is: %q", this.UIState) - - if this.UIState == "splash" { - this.connectionAttempts++ - } else { - this.connectionAttempts = 0 - } - - this.verifyConnection() - - if this.OctoPrintPluginIsAvailable { - this.checkNotification() - } - - logger.TraceLeave("ui.Update()") -} - func (this *UI) GoToPanel(panel interfaces.IPanel) { logger.TraceEnter("ui.GoToPanel()") @@ -573,11 +634,7 @@ func (this *UI) errToUser(err error) string { return "Loading..." } - logger.Errorf("ui.errToUser() - unexpected error: %s", text) - - unexpectedErrorMsg := fmt.Sprintf("Unexpected Error: %s", text) - - logger.TraceLeave("ui.errToUser()") - - return unexpectedErrorMsg + msg := fmt.Sprintf("ui.errToUser() - unexpected error: %s", text) + logger.TraceLeave(msg) + return fmt.Sprintf("Unexpected Error: %s", text) } diff --git a/utils/BackgroundTask.go b/utils/BackgroundTask.go index 54be5c1..57910d2 100755 --- a/utils/BackgroundTask.go +++ b/utils/BackgroundTask.go @@ -1,8 +1,10 @@ package utils import ( - "time" + "os" + "strconv" "sync" + "time" "github.com/gotk3/gotk3/glib" "github.com/Z-Bolt/OctoScreen/logger" @@ -76,3 +78,29 @@ func (this *BackgroundTask) execute() { logger.LogFatalError("BackgroundTask.execute()", "IdleAdd()", err) } } + + +func GetExperimentalFrequency( + defaultTimeout int, + experimentalConfigName string, +) time.Duration { + duration := time.Second * time.Duration(defaultTimeout) + + // Experimental, set the timeout based on config setting, but only if the config is pressent. + updateFrequency := os.Getenv(experimentalConfigName) + if updateFrequency != "" { + logger.Infof( + "BackgroundTask.GetExperimentalFrequency() - '%s' is present, frequency is %s", + experimentalConfigName, + updateFrequency, + ) + val, err := strconv.Atoi(updateFrequency) + if err == nil { + duration = time.Second * time.Duration(val) + } else { + logger.LogError("BackgroundTask.GetExperimentalFrequency()", "strconv.Atoi()", err) + } + } + + return duration +}
\ No newline at end of file diff --git a/utils/ConnectionManager.go b/utils/ConnectionManager.go index 9473875..fc8f199 100755 --- a/utils/ConnectionManager.go +++ b/utils/ConnectionManager.go @@ -9,12 +9,10 @@ import ( "github.com/Z-Bolt/OctoScreen/logger" ) -// const MAX_CONNECTION_ATTEMPTS = 8 -const MAX_CONNECTION_ATTEMPTS = 4 +const MAX_CONNECTION_ATTEMPTS = 10 type connectionManager struct { Client *octoprintApis.Client - // IsRunning bool ConnectAttempts int IsConnectedToOctoPrint bool IsConnectedToPrinter bool @@ -30,7 +28,6 @@ func GetConnectionManagerInstance(client *octoprintApis.Client) (*connectionMana connectionManagerInstance = &connectionManager{ Client: client, - // IsRunning: false, ConnectAttempts: 0, IsConnectedToOctoPrint: false, IsConnectedToPrinter: false, @@ -40,8 +37,7 @@ func GetConnectionManagerInstance(client *octoprintApis.Client) (*connectionMana return connectionManagerInstance } -func (this *connectionManager) InitializeConnectionState() { - // this.IsRunning = true +func (this *connectionManager) ReInitializeConnectionState() { this.ConnectAttempts = 0 this.IsConnectedToOctoPrint = false this.IsConnectedToPrinter = false @@ -50,90 +46,104 @@ func (this *connectionManager) InitializeConnectionState() { func (this *connectionManager) UpdateStatus() { logger.TraceEnter("ConnectionManager.UpdateStatus()") - if this.IsConnected() != true { - if this.ConnectAttempts > MAX_CONNECTION_ATTEMPTS { - this.ConnectAttempts++ - } + logger.Infof("ConnectAttempts: %d", this.ConnectAttempts) - logger.Debug("ConnectionManager.UpdateStatus() - about to call ConnectionRequest.Do()") - t1 := time.Now() - connectionResponse, err := (&octoprintApis.ConnectionRequest{}).Do(this.Client) - t2 := time.Now() - logger.Debug("ConnectionManager.UpdateStatus() - finished calling ConnectionRequest.Do()") - logger.Debugf("time elapsed: %q", t2.Sub(t1)) - - if err != nil { - logger.LogError("ConnectionManager.UpdateStatus()", "ConnectionRequest.Do()", err) - // newUIState, splashMessage = this.getUiStateAndMessageFromError(err, newUIState, splashMessage) - // logger.Debugf("ConnectionManager.UpdateStatus() - newUIState is now: %s", newUIState) - this.IsConnectedToOctoPrint = false - logger.Debug("ConnectionManager.UpdateStatus() - Connection state: IsConnectedToOctoPrint is now false") - logger.TraceLeave("ConnectionManager.UpdateStatus()") - return - } - - logger.Debug("ConnectionManager.UpdateStatus() - ConnectionRequest.Do() succeeded") - - this.IsConnectedToOctoPrint = true - - jsonResponse, err := StructToJson(connectionResponse) - if err != nil { - logger.LogError("ConnectionManager.UpdateStatus()", "StructToJson()", err) - // If there's an error here, it's with the serialization of the object to JSON. - // This is just for debugging, so don't return if there's an issue, and just - // carry on (and hopefully connectionResponse isn't corrupted) - } else { - logger.Debugf("ConnectionManager.UpdateStatus() - connectionResponse is: %s", jsonResponse) - } - - /* - Example JSON response: - { - "Current": { - "state": "Operational", - "port": "/dev/ttyACM0", - "baudrate": 115200, - "printerProfile": "_default" - }, - "Options": { - "ports": [ - "/dev/ttyACM0" - ], - "baudrates": [ - 250000, - 230400, - 115200, - 57600, - 38400, - 19200, - 9600 - ], - "printerProfiles": [ - { - "id": "_default", - "name": "name-of-the-printer" - } - ], - "portPreference": "", - "baudratePreference": 0, - "printerProfilePreference": "_default", - "autoconnect": false - } - } - */ - - printerConnectionState := connectionResponse.Current.State - if printerConnectionState.IsOffline() || printerConnectionState.IsError() { - this.IsConnectedToPrinter = false - } else { - this.IsConnectedToPrinter = true + // If OctoScreen is connected to OctoPrint, + // and OctoPrint is connected to the printer, + // don't bother checking again. + if this.IsConnected() == true { + logger.TraceLeave("ConnectionManager.UpdateStatus()") + return + } + + // Continue on if OctoScreen isn't connected... + + // If the maximum number of attempts have already been made, don't bother trying agin. + if this.ConnectAttempts >= MAX_CONNECTION_ATTEMPTS { + logger.TraceLeave("ConnectionManager.UpdateStatus()") + return + } + + this.ConnectAttempts++ + + logger.Debug("ConnectionManager.UpdateStatus() - about to call ConnectionRequest.Do()") + t1 := time.Now() + connectionResponse, err := (&octoprintApis.ConnectionRequest{}).Do(this.Client) + t2 := time.Now() + logger.Debug("ConnectionManager.UpdateStatus() - finished calling ConnectionRequest.Do()") + logger.Debugf("time elapsed: %q", t2.Sub(t1)) + + if err != nil { + logger.LogError("ConnectionManager.UpdateStatus()", "ConnectionRequest.Do()", err) + // newUIState, splashMessage = this.getUiStateAndMessageFromError(err, newUIState, splashMessage) + // logger.Debugf("ConnectionManager.UpdateStatus() - newUIState is now: %s", newUIState) + this.IsConnectedToOctoPrint = false + logger.Debug("ConnectionManager.UpdateStatus() - Connection state: IsConnectedToOctoPrint is now false") + logger.TraceLeave("ConnectionManager.UpdateStatus()") + return + } + + logger.Debug("ConnectionManager.UpdateStatus() - ConnectionRequest.Do() succeeded") + + this.IsConnectedToOctoPrint = true + + jsonResponse, err := StructToJson(connectionResponse) + if err != nil { + logger.LogError("ConnectionManager.UpdateStatus()", "StructToJson()", err) + // If there's an error here, it's with the serialization of the object to JSON. + // This is just for debugging, so don't return if there's an issue, and just + // carry on (and hopefully connectionResponse isn't corrupted) + } else { + logger.Debugf("ConnectionManager.UpdateStatus() - connectionResponse is: %s", jsonResponse) + } + + /* + Example JSON response: + { + "Current": { + "state": "Operational", + "port": "/dev/ttyACM0", + "baudrate": 115200, + "printerProfile": "_default" + }, + "Options": { + "ports": [ + "/dev/ttyACM0" + ], + "baudrates": [ + 250000, + 230400, + 115200, + 57600, + 38400, + 19200, + 9600 + ], + "printerProfiles": [ + { + "id": "_default", + "name": "name-of-the-printer" + } + ], + "portPreference": "", + "baudratePreference": 0, + "printerProfilePreference": "_default", + "autoconnect": false } } + */ + + printerConnectionState := connectionResponse.Current.State + if printerConnectionState.IsOffline() || printerConnectionState.IsError() { + this.IsConnectedToPrinter = false + } else { + this.IsConnectedToPrinter = true + } logger.TraceLeave("ConnectionManager.UpdateStatus()") } func (this *connectionManager) IsConnected() bool { - // TODO: should this be named IsFullyConnected? + // TODO: should this be named IsFullyConnected()? return this.IsConnectedToOctoPrint == true && this.IsConnectedToPrinter == true; } diff --git a/utils/SystemDHeartbeat.go b/utils/SystemDHeartbeat.go index c2b21f0..9de0487 100755 --- a/utils/SystemDHeartbeat.go +++ b/utils/SystemDHeartbeat.go @@ -1,10 +1,10 @@ package utils import ( - "os" - "strconv" + // "os" + // "strconv" "sync" - "time" + // "time" "github.com/coreos/go-systemd/daemon" @@ -28,31 +28,25 @@ func GetSystemDHeartbeatInstance() (*systemDHeartbeat) { systemDHeartbeatOnce.Do(func() { systemDHeartbeatInstance = &systemDHeartbeat{} - - // Default timeout of 5 seconds - duration := time.Second * 5 - - // Experimental, set the timeout based on config setting, but only if the config is pressent. - updateFrequency := os.Getenv("EXPERIMENTAL_SYSTEMD_HEARTBEAT_UPDATE_FREQUENCY") - if updateFrequency != "" { - logger.Infof("SystemDHeartbeat.GetSystemDHeartbeatInstance() - EXPERIMENTAL_SYSTEMD_HEARTBEAT_UPDATE_FREQUENCY is present, frequency is %s", updateFrequency) - val, err := strconv.Atoi(updateFrequency) - if err == nil { - duration = time.Second * time.Duration(val) - } else { - logger.LogError("SystemDHeartbeat.GetSystemDHeartbeatInstance()", "strconv.Atoi()", err) - } - } - - systemDHeartbeatInstance.backgroundTask = CreateBackgroundTask(duration, func() { - systemDHeartbeatInstance.sendHeartbeat() - }) + systemDHeartbeatInstance.createBackgroundTask() }) } return systemDHeartbeatInstance } +func (this *systemDHeartbeat) createBackgroundTask() { + logger.TraceEnter("SystemDHeartbeat.createBackgroundTask()") + + // Default timeout of 5 seconds + duration := GetExperimentalFrequency(5, "EXPERIMENTAL_SYSTEMD_HEARTBEAT_UPDATE_FREQUENCY") + systemDHeartbeatInstance.backgroundTask = CreateBackgroundTask(duration, func() { + systemDHeartbeatInstance.sendHeartbeat() + }) + + logger.TraceLeave("SystemDHeartbeat.createBackgroundTask()") +} + func (this *systemDHeartbeat) Start() { this.backgroundTask.Start() } @@ -67,4 +61,3 @@ func (this *systemDHeartbeat) sendHeartbeat() { logger.Errorf("SystemDHeartbeat.sendHeartbeat() - SdNotify() returned an error: %q", err) } } - |