proc_rpc2.go 3.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188
  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. _, err = McuCtrlBoard_Write([]byte(jsonStr))
  46. if err != nil {
  47. return err
  48. }
  49. return nil
  50. }
  51. // 发送请求, 并等待应答
  52. func SendRPC2Request(req *jsonrpc2.Request, timeout int /*单位: ms*/) (*jsonrpc2.Response, error) {
  53. if req == nil || req.ID == nil {
  54. return nil, fmt.Errorf("invalid request")
  55. }
  56. id := *req.ID
  57. ch := make(chan *jsonrpc2.Response, 1)
  58. pendingRequests.Store(id, ch)
  59. defer pendingRequests.Delete(id)
  60. jsonStr, err := req.String()
  61. if err != nil {
  62. return nil, err
  63. }
  64. _, err = McuCtrlBoard_Write([]byte(jsonStr))
  65. if err != nil {
  66. return nil, err
  67. }
  68. timer := time.NewTimer(time.Duration(timeout) * time.Millisecond)
  69. defer timer.Stop()
  70. select {
  71. case resp := <-ch:
  72. return resp, nil
  73. case <-timer.C:
  74. return nil, fmt.Errorf("request %v timed out after %d ms", id, timeout)
  75. }
  76. }
  77. // 获取主动请求的应答
  78. func handleRPC2Response(jsonStr string) error {
  79. w, err := jsonrpc2.ParseResponse(jsonStr)
  80. if err != nil {
  81. return fmt.Errorf("an error occurred while parsing JSON-RPC response: %v", err)
  82. }
  83. if w.ID == nil {
  84. return nil
  85. }
  86. id := *w.ID
  87. v, ok := pendingRequests.Load(id)
  88. if !ok {
  89. return fmt.Errorf("orphan response id=%d, no pending request", id)
  90. }
  91. ch, ok := v.(chan *jsonrpc2.Response)
  92. if !ok {
  93. return fmt.Errorf("invalid response channel for id=%d", id)
  94. }
  95. select {
  96. case ch <- w:
  97. return nil
  98. default:
  99. return fmt.Errorf("response dropped for id=%d, channel not receiving", id)
  100. }
  101. }
  102. // 处理JSONRPC 2.0报文
  103. func processRPC2(jsonStr string) *C.char {
  104. s := jsonStr
  105. role := detectRPC2Role(s)
  106. var w *jsonrpc2.Response
  107. wret := func() *C.char {
  108. if w == nil { // 无应答
  109. return nil
  110. }
  111. // 下面由C.CString()分配的内存由C侧释放
  112. b, err := w.String()
  113. if err != nil {
  114. return C.CString(fmt.Sprintf("an error occurred while calling the String() method of jsonrpc2.Response: %v", err))
  115. }
  116. return C.CString(b)
  117. }
  118. if role == "response" {
  119. err := handleRPC2Response(s)
  120. if err != nil {
  121. baseapp.Logger.Errorf("[%s] 解析请求返回的应答时发生错误: %v", MODULE_NAME, err)
  122. }
  123. return nil
  124. }
  125. if role != "request" {
  126. return nil
  127. }
  128. r, err := jsonrpc2.ParseRequest(s)
  129. if err != nil {
  130. w = jsonrpc2.BuildError(nil, jsonrpc2.ErrParse, "")
  131. return wret()
  132. }
  133. call := func(f func(*jsonrpc2.Request) (*jsonrpc2.Response, error)) *jsonrpc2.Response {
  134. w, e := f(r)
  135. if e != nil { // 调用本地RPC函数执行时发生错误
  136. return jsonrpc2.BuildError(r, jsonrpc2.ErrInternal, "")
  137. }
  138. return w
  139. }
  140. switch r.Method {
  141. case "echo":
  142. w = call(test_echo)
  143. default:
  144. w = jsonrpc2.BuildError(r, jsonrpc2.ErrMethodNotFound, "")
  145. }
  146. return wret()
  147. }
  148. // 数据回显本地测试方法
  149. func test_echo(r *jsonrpc2.Request) (*jsonrpc2.Response, error) {
  150. if r.Params == nil {
  151. return jsonrpc2.BuildError(r, jsonrpc2.ErrInvalidParams, ""), nil
  152. }
  153. return jsonrpc2.BuildResult(r, r.Params)
  154. }