- 移除 bj_power_dashboard 旧 React 大屏源码(迁移至 2D SVG 方案) - MES/WMS/工位终端前端:清理 help.js 与 PageHelp 帮助文档,统一操作列与布局,接入请求拦截器 - 新增收集式校验错误弹窗(ErrorListDialog 统一拦截 3015,逐条列现象+建议) - 新增托盘程序(tray)与 WebSocket(ws) 实时通知模块(三端共用) - MES/WMS 物料档案新增同步状态字段,补齐双向失败重推与默认角色 seed - 工单/产能/产品工艺/日排产逻辑调整;拧紧枪按工位配置 - 新增迁移 SQL:扭矩按工位、sysconfig 序列修复 - 更新 技术约束/案例/部署手册/项目说明 等文档
189 lines
4.5 KiB
Go
189 lines
4.5 KiB
Go
package ws
|
||
|
||
import (
|
||
"context"
|
||
"encoding/json"
|
||
"net/http"
|
||
"strings"
|
||
"sync"
|
||
"time"
|
||
|
||
"bj_power_mes/internal/logic"
|
||
"bj_power_mes/internal/svc"
|
||
|
||
"github.com/gorilla/websocket"
|
||
"github.com/zeromicro/go-zero/core/logx"
|
||
)
|
||
|
||
// 待办变化轮询间隔 / 读写超时 / ping 间隔
|
||
const (
|
||
todoPollInterval = 5 * time.Second
|
||
todoWriteTimeout = 5 * time.Second
|
||
todoReadTimeout = 90 * time.Second
|
||
todoPingInterval = 30 * time.Second
|
||
)
|
||
|
||
// todoClient 单个 WebSocket 连接;send 由 writePump 独占写,避免并发写冲突。
|
||
type todoClient struct {
|
||
conn *websocket.Conn
|
||
send chan []byte
|
||
}
|
||
|
||
// TodoHub 待办 WebSocket 推送中心:持有连接,定时轮询 TodoStats,与上次结果不同才广播。
|
||
type TodoHub struct {
|
||
svcCtx *svc.ServiceContext
|
||
upgrader websocket.Upgrader
|
||
mu sync.Mutex
|
||
clients map[*todoClient]struct{}
|
||
last string // 上次广播的 payload,用于变化检测
|
||
once sync.Once
|
||
}
|
||
|
||
func NewTodoHub(svcCtx *svc.ServiceContext) *TodoHub {
|
||
h := &TodoHub{
|
||
svcCtx: svcCtx,
|
||
clients: map[*todoClient]struct{}{},
|
||
}
|
||
h.upgrader = websocket.Upgrader{
|
||
CheckOrigin: sameOrigin,
|
||
}
|
||
return h
|
||
}
|
||
|
||
// sameOrigin 允许同源(现场用 IP 访问):比较 Origin 的 host 段与请求 Host;禁正则。
|
||
// 无 Origin(非浏览器客户端)直接放行。
|
||
func sameOrigin(r *http.Request) bool {
|
||
origin := r.Header.Get("Origin")
|
||
if origin == "" {
|
||
return true
|
||
}
|
||
o := origin
|
||
if idx := strings.Index(o, "://"); idx >= 0 {
|
||
o = o[idx+3:]
|
||
}
|
||
if slash := strings.Index(o, "/"); slash >= 0 {
|
||
o = o[:slash]
|
||
}
|
||
return strings.EqualFold(o, r.Host)
|
||
}
|
||
|
||
func (h *TodoHub) add(c *todoClient) {
|
||
h.mu.Lock()
|
||
h.clients[c] = struct{}{}
|
||
h.mu.Unlock()
|
||
}
|
||
|
||
func (h *TodoHub) remove(c *todoClient) {
|
||
h.mu.Lock()
|
||
delete(h.clients, c)
|
||
h.mu.Unlock()
|
||
_ = c.conn.Close()
|
||
}
|
||
|
||
// snapshot 取一次全量待办统计 payload
|
||
func (h *TodoHub) snapshot(ctx context.Context) []byte {
|
||
items, total, err := logic.New(h.svcCtx).TodoStats(ctx)
|
||
if err != nil {
|
||
logx.Errorf("待办统计失败:%v", err)
|
||
items, total = []logic.TodoItem{}, 0
|
||
}
|
||
b, _ := json.Marshal(map[string]any{"items": items, "total": total})
|
||
return b
|
||
}
|
||
|
||
// publishIfChanged 轮询结果变化才广播("待办数变化时推送")
|
||
func (h *TodoHub) publishIfChanged(ctx context.Context) {
|
||
payload := h.snapshot(ctx)
|
||
h.mu.Lock()
|
||
if string(payload) == h.last {
|
||
h.mu.Unlock()
|
||
return
|
||
}
|
||
h.last = string(payload)
|
||
h.mu.Unlock()
|
||
h.broadcast(payload)
|
||
}
|
||
|
||
func (h *TodoHub) broadcast(payload []byte) {
|
||
h.mu.Lock()
|
||
for c := range h.clients {
|
||
select {
|
||
case c.send <- payload:
|
||
default: // 慢客户端丢弃当前帧,不阻塞其它连接
|
||
}
|
||
}
|
||
h.mu.Unlock()
|
||
}
|
||
|
||
// startPolling 首个连接建立时懒启动轮询(无需改服务启动入口)
|
||
func (h *TodoHub) startPolling() {
|
||
h.once.Do(func() {
|
||
go func() {
|
||
ticker := time.NewTicker(todoPollInterval)
|
||
defer ticker.Stop()
|
||
for range ticker.C {
|
||
h.publishIfChanged(context.Background())
|
||
}
|
||
}()
|
||
})
|
||
}
|
||
|
||
// Handle 升级为 WebSocket:先推一次全量,再由独立 writePump 串行写广播帧与 ping,
|
||
// readPump 负责检测关闭/pong。token 校验在 handler 层完成。
|
||
func (h *TodoHub) Handle(w http.ResponseWriter, r *http.Request) {
|
||
conn, err := h.upgrader.Upgrade(w, r, nil)
|
||
if err != nil {
|
||
logx.Errorf("待办 WebSocket 升级失败:%v", err)
|
||
return
|
||
}
|
||
c := &todoClient{conn: conn, send: make(chan []byte, 16)}
|
||
h.add(c)
|
||
h.startPolling()
|
||
|
||
// 连接建立先推一次全量,并把 last 对齐,避免轮询立刻重推同样内容
|
||
payload := h.snapshot(r.Context())
|
||
h.mu.Lock()
|
||
h.last = string(payload)
|
||
h.mu.Unlock()
|
||
c.send <- payload
|
||
|
||
go h.writePump(c)
|
||
h.readPump(c)
|
||
}
|
||
|
||
func (h *TodoHub) readPump(c *todoClient) {
|
||
defer h.remove(c)
|
||
c.conn.SetReadLimit(1024)
|
||
_ = c.conn.SetReadDeadline(time.Now().Add(todoReadTimeout))
|
||
c.conn.SetPongHandler(func(string) error {
|
||
return c.conn.SetReadDeadline(time.Now().Add(todoReadTimeout))
|
||
})
|
||
for {
|
||
if _, _, err := c.conn.ReadMessage(); err != nil {
|
||
return
|
||
}
|
||
}
|
||
}
|
||
|
||
func (h *TodoHub) writePump(c *todoClient) {
|
||
ticker := time.NewTicker(todoPingInterval)
|
||
defer func() {
|
||
ticker.Stop()
|
||
_ = c.conn.Close()
|
||
}()
|
||
for {
|
||
select {
|
||
case msg := <-c.send:
|
||
_ = c.conn.SetWriteDeadline(time.Now().Add(todoWriteTimeout))
|
||
if err := c.conn.WriteMessage(websocket.TextMessage, msg); err != nil {
|
||
return
|
||
}
|
||
case <-ticker.C:
|
||
_ = c.conn.SetWriteDeadline(time.Now().Add(todoWriteTimeout))
|
||
if err := c.conn.WriteMessage(websocket.PingMessage, nil); err != nil {
|
||
return
|
||
}
|
||
}
|
||
}
|
||
}
|