proc_rpc2.go 3.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183
  1. package mcu_ctrl_board
  2. /*
  3. #include "mcu_ctrl_board.h"
  4. */
  5. import "C"
  6. import (
  7. "encoding/json"
  8. "fmt"
  9. "sync"
  10. "time"
  11. "hnyfkj.com.cn/rtu/linux/baseapp"
  12. "hnyfkj.com.cn/rtu/linux/utils/jsonrpc2"
  13. )
  14. var (
  15. // 存储所有待处理的JSON RPC 2.0请求ID和对应的应答通道
  16. pendingRequests sync.Map
  17. )
  18. // 判断报文的角色是什么
  19. func detectRPC2Role(jsonStr string) string {
  20. var obj map[string]json.RawMessage
  21. if json.Unmarshal([]byte(jsonStr), &obj) != nil {
  22. return "invalid"
  23. }
  24. if string(obj["jsonrpc"]) != `"2.0"` {
  25. return "invalid"
  26. }
  27. switch {
  28. case obj["method"] != nil:
  29. return "request"
  30. case obj["result"] != nil || obj["error"] != nil:
  31. return "response"
  32. default:
  33. return "unknown"
  34. }
  35. }
  36. // 发送通知, 不用等应答
  37. func SendRPC2Notify(req *jsonrpc2.Request) error {
  38. if req == nil || req.ID != nil {
  39. return fmt.Errorf("invalid notify")
  40. }
  41. jsonStr, err := req.String()
  42. if err != nil {
  43. return err
  44. }
  45. return Board.WriteDataToUart([]byte(jsonStr))
  46. }
  47. // 发送请求, 并等待应答
  48. func SendRPC2Request(req *jsonrpc2.Request, timeout int /*单位: ms*/) (*jsonrpc2.Response, error) {
  49. if req == nil || req.ID == nil {
  50. return nil, fmt.Errorf("invalid request")
  51. }
  52. id := *req.ID
  53. ch := make(chan *jsonrpc2.Response, 1)
  54. pendingRequests.Store(id, ch)
  55. defer pendingRequests.Delete(id)
  56. jsonStr, err := req.String()
  57. if err != nil {
  58. return nil, err
  59. }
  60. err = Board.WriteDataToUart([]byte(jsonStr))
  61. if err != nil {
  62. return nil, err
  63. }
  64. timer := time.NewTimer(time.Duration(timeout) * time.Millisecond)
  65. defer timer.Stop()
  66. select {
  67. case resp := <-ch:
  68. return resp, nil
  69. case <-timer.C:
  70. return nil, fmt.Errorf("request %v timed out after %d ms", id, timeout)
  71. }
  72. }
  73. // 获取主动请求的应答
  74. func handleRPC2Response(jsonStr string) error {
  75. w, err := jsonrpc2.ParseResponse(jsonStr)
  76. if err != nil {
  77. return fmt.Errorf("an error occurred while parsing JSON-RPC response: %v", err)
  78. }
  79. if w.ID == nil {
  80. return nil
  81. }
  82. id := *w.ID
  83. v, ok := pendingRequests.Load(id)
  84. if !ok {
  85. return fmt.Errorf("orphan response id=%d, no pending request", id)
  86. }
  87. ch, ok := v.(chan *jsonrpc2.Response)
  88. if !ok {
  89. return fmt.Errorf("invalid response channel for id=%d", id)
  90. }
  91. select {
  92. case ch <- w:
  93. return nil
  94. default:
  95. return fmt.Errorf("response dropped for id=%d, channel not receiving", id)
  96. }
  97. }
  98. // 处理JSONRPC 2.0报文
  99. func processRPC2(jsonStr string) *C.char {
  100. s := jsonStr
  101. role := detectRPC2Role(s)
  102. var w *jsonrpc2.Response
  103. wret := func() *C.char {
  104. if w == nil { // 无应答
  105. return nil
  106. }
  107. // 下面由C.CString()分配的内存由C侧释放
  108. b, err := w.String()
  109. if err != nil {
  110. return C.CString(fmt.Sprintf("an error occurred while calling the String() method of jsonrpc2.Response: %v", err))
  111. }
  112. return C.CString(b)
  113. }
  114. if role == "response" {
  115. err := handleRPC2Response(s)
  116. if err != nil {
  117. baseapp.Logger.Errorf("[%s] 解析请求返回的应答时发生错误: %v", MODULE_NAME, err)
  118. }
  119. return nil
  120. }
  121. if role != "request" {
  122. return nil
  123. }
  124. r, err := jsonrpc2.ParseRequest(s)
  125. if err != nil {
  126. w = jsonrpc2.BuildError(nil, jsonrpc2.ErrParse, "")
  127. return wret()
  128. }
  129. call := func(f func(*jsonrpc2.Request) (*jsonrpc2.Response, error)) *jsonrpc2.Response {
  130. w, e := f(r)
  131. if e != nil { // 调用本地RPC函数执行时发生错误
  132. return jsonrpc2.BuildError(r, jsonrpc2.ErrInternal, "")
  133. }
  134. return w
  135. }
  136. switch r.Method {
  137. case "echo":
  138. w = call(test_echo)
  139. default:
  140. w = jsonrpc2.BuildError(r, jsonrpc2.ErrMethodNotFound, "")
  141. }
  142. return wret()
  143. }
  144. // 数据回显本地测试方法
  145. func test_echo(r *jsonrpc2.Request) (*jsonrpc2.Response, error) {
  146. if r.Params == nil {
  147. return jsonrpc2.BuildError(r, jsonrpc2.ErrInvalidParams, ""), nil
  148. }
  149. return jsonrpc2.BuildResult(r, r.Params)
  150. }