| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278 |
- // Author: NiuJiuRu
- // Email: niujiuru@qq.com
- // Date: 2025-11-20
- package mcu_ctrl_board
- /*
- #include "mcu_ctrl_board.h"
- */
- import "C"
- import (
- "encoding/json"
- "fmt"
- "sync"
- "time"
- "unsafe"
- "hnyfkj.com.cn/rtu/linux/baseapp"
- "hnyfkj.com.cn/rtu/linux/netmgrd"
- "hnyfkj.com.cn/rtu/linux/utils/jsonrpc2"
- )
- // 打开与MCU控制板的串口通讯
- func mcuCtrlBoard_ComInit() (int, error) {
- ret := int(C.MCBComInit())
- if ret != 0 {
- return ret, fmt.Errorf("an error occurred while calling the C.MCBComInit function(%d)", ret)
- }
- return 0, nil
- }
- // 关闭与MCU控制板的串口通讯
- func mcuCtrlBoard_ComExit() error {
- ret := int(C.MCBComExit())
- if ret != 0 {
- return fmt.Errorf("an error occurred while calling the C.MCBComExit function(%d)", ret)
- }
- return nil
- }
- // 主动的发送指令给MCU控制板
- func mcuCtrlBoard_SendCmd(cmd string) error {
- cstr := C.CString(cmd)
- defer C.free(unsafe.Pointer(cstr))
- ret := int(C.MCBComSendCmd(cstr))
- if ret != 0 {
- return fmt.Errorf("an error occurred while calling the C.MCBComSendCmd function(%d)", ret)
- }
- return nil
- }
- // 判断输入字符串是请求/应答
- func detectJsonRole(jsonStr string) string {
- var obj map[string]json.RawMessage
- if json.Unmarshal([]byte(jsonStr), &obj) != nil {
- return "invalid"
- }
- switch {
- case obj["method"] != nil:
- return "request"
- case obj["result"] != nil || obj["error"] != nil:
- return "response"
- default:
- return "unknown"
- }
- }
- //export RTU_JsonMsgProcCb
- func RTU_JsonMsgProcCb(jsonStr *C.char) *C.char {
- s := C.GoString(jsonStr)
- role := detectJsonRole(s)
- var w *jsonrpc2.Response
- wret := func() *C.char {
- if w == nil {
- return nil
- }
- b, err := w.String()
- if err != nil {
- return C.CString(fmt.Sprintf("an error occurred while calling the String() method of jsonrpc2.Response: %v", err))
- }
- return C.CString(b)
- }
- if role == "response" {
- err := Board.handleResponse(s)
- if err != nil {
- baseapp.Logger.Errorf("[%s] 解析数据板返回的命令应答时发生错误: %v", MODULE_NAME, err)
- }
- return nil
- }
- if role != "request" {
- w = jsonrpc2.BuildError(nil, jsonrpc2.ErrInvalidRequest, "")
- return wret()
- }
- r, err := jsonrpc2.ParseRequest(s)
- call := func(f func(*jsonrpc2.Request) (*jsonrpc2.Response, error)) *jsonrpc2.Response {
- w, e := f(r)
- if e != nil { // 调用本地RPC处理函数时发生错误
- return jsonrpc2.BuildError(r, jsonrpc2.ErrInternal, "")
- }
- return w
- }
- if err != nil {
- w = jsonrpc2.BuildError(nil, jsonrpc2.ErrParse, "")
- } else {
- switch r.Method {
- // 控制板查询数据板状态
- case "get_rtu_status":
- w = call(Board.getRTUStatus)
- // 控制板发送传感器数据
- case "send_sensor_data":
- w = call(Board.sendSensorData)
- // 控制板请求数据板拍照
- case "take_photo":
- w = call(Board.takePhoto)
- // 控制板发送预掉电通知
- case "power_down":
- w = call(Board.powerDown)
- default:
- w = jsonrpc2.BuildError(r, jsonrpc2.ErrMethodNotFound, "")
- }
- }
- return wret()
- }
- // 控制板查询数据板状态
- func (b *MCUCtrlBoard) getRTUStatus(r *jsonrpc2.Request) (*jsonrpc2.Response, error) {
- netst := "offline"
- if netmgrd.IsInetAvailable() {
- netst = "online"
- }
- systm := ""
- if netmgrd.IsSyncedNtpTime() {
- now := time.Now()
- systm = now.Format("2006-01-02 15:04:05")
- }
- wrkst := "idle"
- if GlobalWorkState.Get() != Idle {
- wrkst = "busy"
- }
- wjson := fmt.Sprintf(`{"netst":"%s","systm":"%s","wrkst":"%s"}`, netst, systm, wrkst)
- return jsonrpc2.BuildResult(r, wjson)
- }
- // 控制板发送传感器数据
- func (board *MCUCtrlBoard) sendSensorData(r *jsonrpc2.Request) (*jsonrpc2.Response, error) {
- GlobalWorkState.Add(SensorDataReceiving)
- defer GlobalWorkState.Remove(SensorDataReceiving)
- var dataOne EnvSensorData
- if err := json.Unmarshal([]byte(r.Params), &dataOne); err != nil {
- return jsonrpc2.BuildError(r, jsonrpc2.ErrInvalidParams, ""), nil
- }
- select {
- case board.OneEnvDataCh <- &dataOne:
- default:
- old := <-board.OneEnvDataCh // 弹出旧数据
- baseapp.Logger.Warnf("OneEnvData 通道满, 丢弃一条老数据: %s!", old.String())
- board.OneEnvDataCh <- &dataOne
- }
- return jsonrpc2.BuildResult(r, "success")
- }
- // 控制板请求数据板拍照
- func (board *MCUCtrlBoard) takePhoto(r *jsonrpc2.Request) (*jsonrpc2.Response, error) {
- select {
- case board.ReqTakePhoCh <- true:
- default:
- <-board.ReqTakePhoCh // 弹出旧数据
- board.ReqTakePhoCh <- true
- }
- return jsonrpc2.BuildResult(r, "success")
- }
- // 控制板发送预掉电通知
- func (board *MCUCtrlBoard) powerDown(r *jsonrpc2.Request) (*jsonrpc2.Response, error) {
- netst := "offline"
- if netmgrd.IsInetAvailable() {
- netst = "online"
- }
- systm := ""
- if netmgrd.IsSyncedNtpTime() {
- now := time.Now()
- systm = now.Format("2006-01-02 15:04:05")
- }
- wrkst := "idle"
- if GlobalWorkState.Get() != Idle {
- wrkst = "busy"
- } else {
- close(board.PwrWillOffCh)
- }
- wjson := fmt.Sprintf(`{"netst":"%s","systm":"%s","wrkst":"%s"}`, netst, systm, wrkst)
- return jsonrpc2.BuildResult(r, wjson)
- }
- var pendingRequests sync.Map // 存储所有待处理的请求ID和对应的应答通道
- // 发送请求, 并等待应答
- func (board *MCUCtrlBoard) sendRequest(req *jsonrpc2.Request, timeout int /*单位: ms*/) (*jsonrpc2.Response, error) {
- if req == nil || req.ID == nil {
- return nil, fmt.Errorf("invalid request or request ID")
- }
- id := *req.ID
- ch := make(chan *jsonrpc2.Response, 1)
- pendingRequests.Store(id, ch)
- defer pendingRequests.Delete(id)
- jsonStr, err := req.String()
- if err != nil {
- return nil, err
- }
- err = mcuCtrlBoard_SendCmd(jsonStr)
- if err != nil {
- return nil, err
- }
- timer := time.NewTimer(time.Duration(timeout) * time.Millisecond)
- defer timer.Stop()
- select {
- case resp := <-ch:
- return resp, nil
- case <-timer.C:
- return nil, fmt.Errorf("request %v timed out after %d ms", id, timeout)
- }
- }
- // 处理控制板返回的请求
- func (board *MCUCtrlBoard) handleResponse(jsonStr string) error {
- w, err := jsonrpc2.ParseResponse(jsonStr)
- if err != nil {
- return fmt.Errorf("an error occurred while parsing JSON-RPC response: %v", err)
- }
- if w.ID == nil {
- return nil
- }
- id := *w.ID
- v, ok := pendingRequests.Load(id)
- if !ok {
- return fmt.Errorf("orphan response id=%d, no pending request", id)
- }
- ch, ok := v.(chan *jsonrpc2.Response)
- if !ok {
- return fmt.Errorf("invalid response channel for id=%d", id)
- }
- select {
- case ch <- w:
- return nil
- default:
- return fmt.Errorf("response dropped for id=%d, channel not receiving", id)
- }
- }
|