Skip to content

Commit

Permalink
rework nats connection strategy
Browse files Browse the repository at this point in the history
  • Loading branch information
nosuchtim committed Jan 5, 2024
1 parent 8257264 commit 0859670
Show file tree
Hide file tree
Showing 9 changed files with 247 additions and 112 deletions.
2 changes: 1 addition & 1 deletion VERSION
Original file line number Diff line number Diff line change
@@ -1 +1 @@
7.92
7.93
13 changes: 8 additions & 5 deletions cmd/palette_natsmon/palette_natsmon.go
Original file line number Diff line number Diff line change
@@ -1,5 +1,10 @@
package main

/*
* This program monitors NATS traffic from Palettes
* and writes it to a file whose name contains the date.
*/

import (
"fmt"
"log"
Expand Down Expand Up @@ -34,9 +39,6 @@ func main() {
opts := []nats.Option{nats.Name("Palette hostwin Subscriber")}
opts = setupConnOptions(opts)

// Keep reconnecting forever
opts = append(opts, nats.MaxReconnects(-1))

// Connect to NATS
nc, err := nats.Connect(fullurl, opts...)
if err != nil {
Expand Down Expand Up @@ -88,8 +90,9 @@ func addToLog(file *os.File, subject string, data string) {
}

func setupConnOptions(opts []nats.Option) []nats.Option {
totalWait := 10 * time.Minute
reconnectDelay := time.Second

totalWait := 48 * time.Hour // 2 days
reconnectDelay := 10 * time.Second

opts = append(opts, nats.ReconnectWait(reconnectDelay))
opts = append(opts, nats.MaxReconnects(int(totalWait/reconnectDelay)))
Expand Down
177 changes: 149 additions & 28 deletions cmd/palette_remote/palette_remote.go
Original file line number Diff line number Diff line change
@@ -1,13 +1,18 @@
package main

import (
"fmt"
"image/color"
"slices"
"strings"
"time"

"fyne.io/fyne/v2"
"fyne.io/fyne/v2/app"
"fyne.io/fyne/v2/canvas"
"fyne.io/fyne/v2/container"
"fyne.io/fyne/v2/driver/desktop"
"fyne.io/fyne/v2/layout"
"fyne.io/fyne/v2/widget"

"github.com/vizicist/palette/kit"
Expand All @@ -18,6 +23,7 @@ var CategoryButton = map[string]*widget.Button{}
var CurrentCategory = "global"
var StatusLabel *widget.Label
var SelectGrid *fyne.Container
var SelectList *fyne.Container
var SelectButton = map[string]*widget.Button{}
var SelectButtonName string
var ActionButtons = map[string]*ActionButton{}
Expand Down Expand Up @@ -97,6 +103,15 @@ func NewActionButton(nm string, f func()) *ActionButton {
return a
}

func GenerateEmptyPage() *fyne.Container {
label := widget.NewLabel("This Page Is Blank?")
return container.NewVBox(
TopButtons,
container.NewCenter(label),
BottomButtons,
)
}

func GenerateSelectPageForCategory(category string) *fyne.Container {

scrollableGrid := container.NewVScroll(SelectGrid)
Expand All @@ -112,58 +127,89 @@ func GenerateSelectPageForCategory(category string) *fyne.Container {
right := canvas.NewRectangle(red)
middle := container.NewBorder(top, bottom, left, right, scrollableGrid)

mousewidget := NewMouseWidget()
mousecontainer := container.New(layout.NewStackLayout(), mousewidget)
// mousewidget := canvas.NewRectangle(red)
// mousewidget.Resize(fyne.NewSize(200,200))
// mousewidget.SetMinSize(fyne.NewSize(200,200))

// Use a container to arrange the label and button vertically
return container.NewVBox(
TopButtons,
middle,
mousecontainer,
BottomButtons,
container.NewCenter(StatusLabel),
)
}

func GenerateEditPageForCategory(category string) *fyne.Container {
items := container.NewVBox()
items.Add(widget.NewLabel("ITEM1"))
items.Add(widget.NewLabel("ITEM2"))
items.Add(widget.NewLabel("ITEM3"))
paramlist, err := kit.LoadParamsMapOfCategory(category,"_Current")
if err != nil {
items.Add(widget.NewLabel("NO PARAMETERS OF THAT CATEGORY?"))
kit.LogError(err)
return nil
}
limit := 10
for nm := range paramlist {
limit--
if limit <= 0 {
break

scrollableList := container.NewVScroll(SelectList)
scrollableList.SetMinSize(fyne.Size{
Width: AppSize.Width,
Height: AppSize.Height,
})

SelectList.RemoveAll()

/*
// items := container.NewVBox()
paramlist, err := kit.LoadParamsMapOfCategory(category, "_Current")
if err != nil {
SelectList.Add(widget.NewLabel("NO PARAMETERS OF THAT CATEGORY?"))
kit.LogError(err)
return nil
}
*/
paramlist := []string{}
for nm, def := range kit.ParamDefs {
if strings.HasPrefix(nm, category+"._") {
continue
}
kit.LogInfo("nm="+nm)
items.Add(widget.NewLabel(nm))
if def.Category == category {
paramlist = append(paramlist, nm)
}
}
slices.Sort(paramlist)
for _, nm := range paramlist {
kit.LogInfo("nm=" + nm)
SelectList.Add(widget.NewLabel(nm))
}
items.Refresh()
SelectList.Refresh()

return container.NewVBox(
TopButtons,
items,
scrollableList,
BottomButtons,
container.NewCenter(StatusLabel),
)
}

func SetCurrentContent(nm string) {
var EditPage = map[string]*fyne.Container{}

func GenerateEditPages() {
for _, category := range []string{"global",
"misc", "sound", "visual", "effect"} {
EditPage[category] = GenerateEditPageForCategory(category)
}
}

func SetCurrentContent(contentType string) {

var content *fyne.Container
switch nm {
switch contentType {
case "edit":
content = GenerateEditPageForCategory(CurrentCategory)
content = EditPage[CurrentCategory]
case "select":
content = GenerateSelectPageForCategory("select")

content = GenerateSelectPageForCategory(CurrentCategory)
}
if content == nil {
kit.LogWarn("No content with that name", "name", nm)
kit.LogWarn("No content of that type", "contentType", contentType)
CurrentContentType = "empty"
RemoteWindow.SetContent(GenerateEmptyPage())
} else {
CurrentContentType = nm
CurrentContentType = contentType
RemoteWindow.SetContent(content) // Set the window content to be the container
}
}
Expand Down Expand Up @@ -202,13 +248,18 @@ func main() {
Width: 200,
Height: 40,
}
listsize := fyne.Size{
Width: 200,
Height: 30,
}

RemoteWindow.Resize(fyne.NewSize(AppSize.Width, AppSize.Height)) // Resize the window

// Create a label (widget) with initial text
StatusLabel = widget.NewLabel("Palette Remote 2024")

SelectGrid = container.NewGridWrap(gridsize)
SelectList = container.NewGridWrap(listsize)

// Create the buttons along the top
TopButtons = container.NewHBox()
Expand All @@ -231,11 +282,81 @@ func main() {
kit.LogInfo("Should be doing Help")
}))

// The "edit" Content page is dynamically generated
// the first time it's viewed
GenerateEditPages()

SetCurrentContent("select")
SelectCategory("quad")

RemoteWindow.ShowAndRun() // Show and run the application
}

// MouseWidget is a widget that implements the desktop.Mouseable interface
type MouseWidget struct {
rect *canvas.Rectangle
}

func (w *MouseWidget) Refresh() {
w.rect.Refresh()
}

func (w *MouseWidget) Hide() {
w.rect.Hide()
}

func (w *MouseWidget) Show() {
w.rect.Show()
}
func (w *MouseWidget) Visible() bool {
return w.rect.Visible()
}

func (w *MouseWidget) Resize(size fyne.Size) {
w.rect.Resize(size)
}
func (w *MouseWidget) MinSize() fyne.Size {
return w.rect.MinSize()
}
func (w *MouseWidget) Size() fyne.Size {
return w.rect.Size()
}
func (w *MouseWidget) Position() fyne.Position {
return w.rect.Position()
}
func (w *MouseWidget) Move(pos fyne.Position) {
w.rect.Move(pos)
}

// MouseDown is called when a mouse button is pressed
func (w *MouseWidget) MouseDown(ev *desktop.MouseEvent) {
fmt.Printf("Mouse down at %v with button %v and modifier %v\n", ev.Position, ev.Button, ev.Modifier)
}

// MouseUp is called when a mouse button is released
func (w *MouseWidget) MouseUp(ev *desktop.MouseEvent) {
fmt.Printf("Mouse up at %v with button %v and modifier %v\n", ev.Position, ev.Button, ev.Modifier)
}

// MouseMoved is called when the mouse pointer is moved
func (w *MouseWidget) MouseMoved(ev *desktop.MouseEvent) {
fmt.Printf("Mouse moved at %v with button %v and modifier %v\n", ev.Position, ev.Button, ev.Modifier)
}

// NewMouseWidget creates a new mouse widget
func NewMouseWidget() *MouseWidget {
red := color.RGBA{R: 255, G: 0, B: 0, A: 255}
w := canvas.NewRectangle(red)
// w := &MouseWidget{}
w.SetMinSize(fyne.NewSize(200, 200))
w.FillColor = color.RGBA{R: 255, G: 0, B: 0, A: 255}
return &MouseWidget{rect: w}
}

/*
func main() {
a := app.New()
w := a.NewWindow("Mouse Events")
w.SetContent(NewMouseWidget())
w.ShowAndRun()
}
*/
1 change: 1 addition & 0 deletions data/config/paramdefs.json
Original file line number Diff line number Diff line change
Expand Up @@ -196,6 +196,7 @@
"global.mmtt_xexpand": {"valuetype": "float", "min": "0.5", "max": "2.0", "init": "1.25", "comment": "#" },
"global.mmtt_yexpand": {"valuetype": "float", "min": "0.5", "max": "2.0", "init": "1.25", "comment": "#" },
"global.mmtt_zexpand": {"valuetype": "float", "min": "0.5", "max": "10.0", "init": "4.0", "comment": "#" },
"global.nats": {"valuetype":"bool", "min":"false", "max":"true", "init":"false", "comment":"# Enable NATS" },
"global.notifygui": {"valuetype":"bool", "min":"false", "max":"true", "init":"true", "comment":"#" },
"global.obspath": {"valuetype":"string", "min":"", "max":"", "init":"C:/Program Files/obs-studio/bin/64bit/obs64.exe", "comment":"# OBS executable path" },
"global.obsstream": {"valuetype":"bool", "min":"false", "max":"true", "init":"false", "comment":"# turn on OBS streaming" },
Expand Down
22 changes: 5 additions & 17 deletions kit/engine.go
Original file line number Diff line number Diff line change
Expand Up @@ -76,8 +76,6 @@ func InitEngine() {

TheEngine = e

EngineSubscribeNats()

for name := range ParamDefs {
if strings.HasPrefix(name, "global.") {
ActivateGlobalParam(name)
Expand Down Expand Up @@ -108,10 +106,11 @@ func EngineNatsApi(host string, cmd string) (result string, err error) {
if !TheNats.enabled {
return "", fmt.Errorf("NatsAPI: NATS not enabled")
}
err = TheNats.Connect()
if err != nil {
LogIfError(err)
return "", err
if !TheNats.isConnected {
return "", fmt.Errorf("EngineNatsAPI: NATS is not connected")
}
if TheNats.natsConn == nil {
return "", fmt.Errorf("NatsAPI: natsConn is nil?")
}
timeout := 3 * time.Second
subject := fmt.Sprintf("to_palette.%s.api", host)
Expand All @@ -120,17 +119,6 @@ func EngineNatsApi(host string, cmd string) (result string, err error) {
return retdata, err
}

func EngineSubscribeNats() {
err := TheNats.Connect()
LogIfError(err)
if err == nil {
subscribeTo := fmt.Sprintf("to_palette.%s.>", Hostname())
LogInfo("Subscribing to NATS", "subscribeTo", subscribeTo)
err = TheNats.Subscribe(subscribeTo, natsRequestHandler)
LogIfError(err)
}
}

func EngineCloseNats() {
TheNats.Disconnect()
}
Expand Down
25 changes: 24 additions & 1 deletion kit/engineapi.go
Original file line number Diff line number Diff line change
Expand Up @@ -90,7 +90,8 @@ func ExecuteGlobalApi(api string, apiargs map[string]string) (result string, err

case "status":
uptime := fmt.Sprintf("%f", Uptime())
attractmode := fmt.Sprintf("%v", TheAttractManager.AttractModeIsOn())
attractmode := strconv.FormatBool(TheAttractManager.AttractModeIsOn())
natsConnected := strconv.FormatBool(TheNats.isConnected)
if TheQuad == nil {
result = JsonObject(
"uptime", uptime,
Expand All @@ -100,6 +101,7 @@ func ExecuteGlobalApi(api string, apiargs map[string]string) (result string, err
result = JsonObject(
"uptime", uptime,
"attractmode", attractmode,
"natsconnected", natsConnected,
"A", Patchs["A"].Status(),
"B", Patchs["B"].Status(),
"C", Patchs["C"].Status(),
Expand Down Expand Up @@ -328,6 +330,27 @@ func ApplyGlobalParam(name string, value string) (err error) {

switch name {

case "global.nats":
newvalue := IsTrueValue(value)
if !newvalue && TheNats.isConnected {
TheNats.Close()
}
TheNats.enabled = IsTrueValue(value)
if TheNats.enabled {
err = TheNats.Init()
LogIfError(err)
}

/*
if TheNats.enabled && TheNats.natsConn == nil {
err = TheNats.Connect()
if err != nil {
LogIfError(err)
return err
}
}
*/

case "global.attract":
TheAttractManager.SetAttractMode(IsTrueValue(value))

Expand Down
Loading

0 comments on commit 0859670

Please sign in to comment.