79 lines
1.8 KiB
Go
79 lines
1.8 KiB
Go
package robot
|
|||
|
|
|
||
|
|
import (
|
||
|
|
"sync"
|
||
|
|
"time"
|
||
|
|
|
||
|
|
"bj_power_mes/internal/alarm"
|
||
|
|
"bj_power_mes/internal/sse"
|
||
|
|
|
||
|
|
"bj_power_mes/ent"
|
||
|
|
|
||
|
|
goplc "bjhardman.cn/bjhardman/goplc"
|
||
|
|
)
|
||
|
|
|
||
|
|
type Controller struct {
|
||
|
|
plcClient goplc.Client
|
||
|
|
entClient *ent.Client
|
||
|
|
sseHandler *sse.Handler
|
||
|
|
alarmSvc *alarm.Service
|
||
|
|
maxRetries int
|
||
|
|
checkSignalDuration time.Duration
|
||
|
|
mtx sync.Mutex
|
||
|
|
activity string // 当前持有锁的Action名称
|
||
|
|
waitingQueue []string // 等待队列
|
||
|
|
queueLock sync.Mutex // 保护等待队列的锁
|
||
|
|
}
|
||
|
|
|
||
|
|
func NewRobotController(plcClient goplc.Client, entClient *ent.Client, sseHandler *sse.Handler, alarmSvc *alarm.Service) *Controller {
|
||
|
|
return &Controller{
|
||
|
|
plcClient: plcClient,
|
||
|
|
entClient: entClient,
|
||
|
|
sseHandler: sseHandler,
|
||
|
|
alarmSvc: alarmSvc,
|
||
|
|
maxRetries: 3,
|
||
|
|
checkSignalDuration: 1 * time.Second,
|
||
|
|
}
|
||
|
|
}
|
||
|
|
|
||
|
|
func (c *Controller) Lock(activity string) {
|
||
|
|
c.queueLock.Lock()
|
||
|
|
c.waitingQueue = append(c.waitingQueue, activity)
|
||
|
|
c.queueLock.Unlock()
|
||
|
|
|
||
|
|
c.mtx.Lock()
|
||
|
|
|
||
|
|
c.queueLock.Lock()
|
||
|
|
defer c.queueLock.Unlock()
|
||
|
|
// 从等待队列移除
|
||
|
|
for i, name := range c.waitingQueue {
|
||
|
|
if name == activity {
|
||
|
|
c.waitingQueue = append(c.waitingQueue[:i], c.waitingQueue[i+1:]...)
|
||
|
|
break
|
||
|
|
}
|
||
|
|
}
|
||
|
|
c.activity = activity
|
||
|
|
}
|
||
|
|
|
||
|
|
func (c *Controller) UnLock() {
|
||
|
|
c.queueLock.Lock()
|
||
|
|
defer c.queueLock.Unlock()
|
||
|
|
c.activity = ""
|
||
|
|
c.mtx.Unlock()
|
||
|
|
}
|
||
|
|
|
||
|
|
// Status 获取当前锁状态
|
||
|
|
func (c *Controller) Status() (current string, queue []string) {
|
||
|
|
c.queueLock.Lock()
|
||
|
|
defer c.queueLock.Unlock()
|
||
|
|
return c.activity, append([]string(nil), c.waitingQueue...) // 返回副本
|
||
|
|
}
|
||
|
|
|
||
|
|
func (c *Controller) SetAction(activity string) {
|
||
|
|
c.activity = activity
|
||
|
|
}
|
||
|
|
|
||
|
|
func (c *Controller) ClearAction() {
|
||
|
|
c.activity = ""
|
||
|
|
}
|