基本逻辑完成

This commit is contained in:
2024-11-01 17:40:34 +08:00
commit f9b9beea4b
40 changed files with 1869 additions and 0 deletions

72
internal/common/device.go Normal file
View File

@@ -0,0 +1,72 @@
package common
import (
"context"
"fmt"
"github.com/eclipse/paho.golang/autopaho"
"github.com/eclipse/paho.golang/paho"
"sync"
"sync/atomic"
)
type DeviceMan interface {
sync.Locker
Status() int
PublishStatus()
}
type Device struct {
mu sync.Mutex
C context.Context
cm *autopaho.ConnectionManager
topic string
status atomic.Int32
OnChange func()
}
func (d *Device) Lock() {
defer d.OnChange()
d.mu.Lock()
d.status.Store(1)
}
func (d *Device) Unlock() {
defer d.OnChange()
d.status.Store(0)
d.mu.Unlock()
}
func (d *Device) Status() int {
return int(d.status.Load())
}
// PublishStatus 推送设备状态
func (d *Device) PublishStatus() {
err := d.cm.AwaitConnection(d.C)
if err != nil {
return
}
_, _ = d.cm.Publish(d.C, &paho.Publish{
Topic: d.topic,
Payload: []byte(fmt.Sprint(d.Status())),
QoS: 1,
})
}
func DefaultDevice(ctx context.Context, cm *autopaho.ConnectionManager, topic string) *Device {
return &Device{
C: ctx,
cm: cm,
topic: topic,
}
}
func NewDevice(ctx context.Context, cm *autopaho.ConnectionManager, topic string, onChange func()) *Device {
return &Device{
C: ctx,
cm: cm,
topic: topic,
OnChange: onChange,
}
}

View File

@@ -0,0 +1,58 @@
package common
import (
"sync"
"sync/atomic"
)
type Stopper interface {
Reset()
Stop()
Done() <-chan struct{}
}
var closedchan = make(chan struct{})
func init() {
close(closedchan)
}
type simpleStopper struct {
mu sync.Mutex
done atomic.Value
}
func (g *simpleStopper) Reset() {
g.mu.Lock()
defer g.mu.Unlock()
g.done = atomic.Value{}
}
func (g *simpleStopper) Stop() {
g.mu.Lock()
defer g.mu.Unlock()
d, _ := g.done.Load().(chan struct{})
if d == nil {
g.done.Store(closedchan)
} else {
close(d)
}
}
func (g *simpleStopper) Done() <-chan struct{} {
d := g.done.Load()
if d != nil {
return d.(chan struct{})
}
g.mu.Lock()
defer g.mu.Unlock()
d = g.done.Load()
if d == nil {
d = make(chan struct{})
g.done.Store(d)
}
return d.(chan struct{})
}
// GlobalStopper 全局停止器
var GlobalStopper Stopper = &simpleStopper{}