protocol.go 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373
  1. // Package faultRecordProtocol 故障录波 MQTT 业务协议编解码(纯函数,不涉及网络、数据库和文件)。
  2. //
  3. // 协议依据:docs/fault-record/FaultFilter_MQTT协议文档.md、docs/fault-record/protocol-specification.md
  4. package faultRecordProtocol
  5. import (
  6. "bytes"
  7. "encoding/json"
  8. "fmt"
  9. "strings"
  10. )
  11. // 外层 cmdType
  12. const (
  13. CmdTypeRequest uint = 377 // 本工具 → 设备:故障录波操作指令
  14. CmdTypeAck uint = 378 // 设备 → 本工具:指令应答
  15. CmdTypeReply uint = 379 // 设备 → 平台:信息上传(业务回复)
  16. CmdTypeReplyAck uint = 380 // 平台 → 设备:信息上传应答
  17. CmdTypeUploadCall uint = 607 // 平台 → 设备:录波文件上传指令
  18. CmdTypeUploadAck uint = 608 // 设备 → 平台:上传指令应答
  19. CmdTypeUploadDone uint = 609 // 设备 → 平台:文件上传结果
  20. CmdTypeUploadDoneA uint = 610 // 平台 → 设备:上传结果应答
  21. )
  22. // 业务层 cmd
  23. const (
  24. CmdRealtime = 0 // 获取实时数据
  25. CmdSetParam = 1 // 设置参数
  26. CmdGetRecord = 2 // 获取记录数据
  27. CmdQueryParam = 3 // 查询参数
  28. CmdExit = 4 // 退出
  29. CmdTestSuccess = 90
  30. CmdTestFail = 99
  31. )
  32. // 业务层设备类型
  33. const (
  34. DeviceTypePE = "pe"
  35. DeviceTypeAGate = "aGate"
  36. )
  37. // 整体结果
  38. const (
  39. ResultOk = "ok"
  40. ResultError = "error"
  41. ResultBusy = "busy"
  42. )
  43. // NormalizeDeviceType 将页面/HTTP 中的设备类型转换为协议值,不区分大小写
  44. func NormalizeDeviceType(t string) (string, error) {
  45. switch strings.ToLower(t) {
  46. case "pe":
  47. return DeviceTypePE, nil
  48. case "agate":
  49. return DeviceTypeAGate, nil
  50. default:
  51. return "", fmt.Errorf("unknown device type: %s", t)
  52. }
  53. }
  54. /************** 377 请求 **************/
  55. type ParaItem struct {
  56. Id int `json:"id"`
  57. SetVal string `json:"setVal"`
  58. }
  59. type RequestInfo struct {
  60. Sn string `json:"sn"`
  61. CodeList []int `json:"codeList,omitempty"` // cmd=0
  62. ParaList []ParaItem `json:"paraList,omitempty"` // cmd=1
  63. Index []int `json:"index,omitempty"` // cmd=2
  64. IdList []int `json:"idList,omitempty"` // cmd=3
  65. }
  66. type RequestGroup struct {
  67. Type string `json:"type"`
  68. Info []RequestInfo `json:"info"`
  69. }
  70. type RequestData struct {
  71. List []RequestGroup `json:"list"`
  72. }
  73. // Request 377 的 dataArea
  74. type Request struct {
  75. Cmd int `json:"cmd"`
  76. Data any `json:"data"`
  77. }
  78. func newDeviceRequest(cmd int, deviceType, sn string, info RequestInfo) (Request, error) {
  79. t, err := NormalizeDeviceType(deviceType)
  80. if err != nil {
  81. return Request{}, err
  82. }
  83. if sn == "" {
  84. return Request{}, fmt.Errorf("device sn is empty")
  85. }
  86. info.Sn = sn
  87. return Request{
  88. Cmd: cmd,
  89. Data: RequestData{List: []RequestGroup{{Type: t, Info: []RequestInfo{info}}}},
  90. }, nil
  91. }
  92. // NewRealtimeRequest cmd=0,codeList 取值 1~3
  93. func NewRealtimeRequest(deviceType, sn string, codeList []int) (Request, error) {
  94. if len(codeList) == 0 {
  95. return Request{}, fmt.Errorf("codeList is empty")
  96. }
  97. for _, c := range codeList {
  98. if c < 1 || c > 3 {
  99. return Request{}, fmt.Errorf("invalid code %d, cmd=0 only supports 1~3", c)
  100. }
  101. }
  102. return newDeviceRequest(CmdRealtime, deviceType, sn, RequestInfo{CodeList: codeList})
  103. }
  104. // NewSetParamRequest cmd=1,setVal 按功能码校验
  105. func NewSetParamRequest(deviceType, sn string, paraList []ParaItem) (Request, error) {
  106. if len(paraList) == 0 {
  107. return Request{}, fmt.Errorf("paraList is empty")
  108. }
  109. for i, p := range paraList {
  110. if err := ValidateSetVal(p.Id, p.SetVal); err != nil {
  111. return Request{}, fmt.Errorf("paraList[%d]: %w", i, err)
  112. }
  113. paraList[i].SetVal = strings.ToUpper(p.SetVal)
  114. }
  115. return newDeviceRequest(CmdSetParam, deviceType, sn, RequestInfo{ParaList: paraList})
  116. }
  117. // MaxRecordsPerRequest 一次 cmd=2 最多获取的记录数
  118. const MaxRecordsPerRequest = 32
  119. // NewGetRecordRequest cmd=2,可一次获取多条记录,设备打成一个包上传
  120. func NewGetRecordRequest(deviceType, sn string, indexes []int) (Request, error) {
  121. if len(indexes) == 0 {
  122. return Request{}, fmt.Errorf("record index is empty")
  123. }
  124. if len(indexes) > MaxRecordsPerRequest {
  125. return Request{}, fmt.Errorf("too many records: %d (max %d)", len(indexes), MaxRecordsPerRequest)
  126. }
  127. seen := map[int]bool{}
  128. for _, i := range indexes {
  129. if i < 1 || i > 255 {
  130. return Request{}, fmt.Errorf("invalid record index %d", i)
  131. }
  132. if seen[i] {
  133. return Request{}, fmt.Errorf("duplicate record index %d", i)
  134. }
  135. seen[i] = true
  136. }
  137. return newDeviceRequest(CmdGetRecord, deviceType, sn, RequestInfo{Index: indexes})
  138. }
  139. // NewQueryParamRequest cmd=3
  140. func NewQueryParamRequest(deviceType, sn string, idList []int) (Request, error) {
  141. if len(idList) == 0 {
  142. return Request{}, fmt.Errorf("idList is empty")
  143. }
  144. for _, id := range idList {
  145. if _, ok := FunctionCodeNames[id]; !ok {
  146. return Request{}, fmt.Errorf("invalid function code %d", id)
  147. }
  148. }
  149. return newDeviceRequest(CmdQueryParam, deviceType, sn, RequestInfo{IdList: idList})
  150. }
  151. // NewExitRequest cmd=4,结束设备当前处理
  152. func NewExitRequest() Request {
  153. return Request{Cmd: CmdExit, Data: struct{}{}}
  154. }
  155. /************** 外层解析辅助 **************/
  156. // envelopeHead 只取路由需要的外层字段,dataArea 保留原始字节
  157. type envelopeHead struct {
  158. CmdType uint `json:"cmdType"`
  159. EquipNo string `json:"equipNo"`
  160. DataArea json.RawMessage `json:"dataArea"`
  161. }
  162. // SplitEnvelope 从完整报文中取出 cmdType、equipNo 和原始 dataArea
  163. func SplitEnvelope(raw []byte) (cmdType uint, equipNo string, dataArea json.RawMessage, err error) {
  164. var h envelopeHead
  165. if err = json.Unmarshal(raw, &h); err != nil {
  166. return 0, "", nil, err
  167. }
  168. return h.CmdType, h.EquipNo, h.DataArea, nil
  169. }
  170. /************** 378 指令应答 **************/
  171. type Ack struct {
  172. Cmd int `json:"cmd"`
  173. Result int `json:"result"` // 样本成功为 0
  174. }
  175. func ParseAck(dataArea []byte) (Ack, error) {
  176. var a Ack
  177. err := json.Unmarshal(dataArea, &a)
  178. return a, err
  179. }
  180. func (a Ack) Ok() bool { return a.Result == 0 }
  181. /************** 379 业务回复 **************/
  182. type HexItem struct {
  183. Code int `json:"code"`
  184. HexData string `json:"hexData"`
  185. ResultOne string `json:"resultOne"`
  186. }
  187. type IndexItem struct {
  188. Index int `json:"index"` // 数据类型码:4=故障数据,5=波形数据
  189. ResultOne string `json:"resultOne"`
  190. }
  191. type IdItem struct {
  192. Id int `json:"id"`
  193. IdData string `json:"idData"`
  194. ResultOne string `json:"resultOne"`
  195. }
  196. type SetResultItem struct {
  197. Id int `json:"id"`
  198. ResultOne string `json:"resultOne"`
  199. }
  200. type ReplyInfo struct {
  201. Sn string `json:"sn"`
  202. HexList []HexItem `json:"hexList,omitempty"`
  203. IndexInfo []IndexItem `json:"indexInfo,omitempty"`
  204. IdInfo []IdItem `json:"idInfo,omitempty"`
  205. SetResultList []SetResultItem `json:"setResultList,omitempty"`
  206. }
  207. type ReplyGroup struct {
  208. Type string `json:"type"`
  209. Info []ReplyInfo `json:"info"`
  210. }
  211. // Reply 379 的 dataArea(FaultFilter 回复的 data 被展开到 dataArea 顶层)
  212. type Reply struct {
  213. Cmd int `json:"cmd"`
  214. Result string `json:"result"`
  215. Filename string `json:"filename,omitempty"`
  216. List []ReplyGroup `json:"list,omitempty"`
  217. }
  218. func ParseReply(dataArea []byte) (Reply, error) {
  219. var r Reply
  220. err := json.Unmarshal(dataArea, &r)
  221. return r, err
  222. }
  223. // Ok 全部子项成功
  224. func (r Reply) Ok() bool { return r.Result == ResultOk }
  225. // Busy 设备正在处理其他命令
  226. func (r Reply) Busy() bool { return r.Result == ResultBusy }
  227. // IsErrorReply 命令未进入业务处理(busy、格式错误、sn 不存在等),此时没有 list
  228. func (r Reply) IsErrorReply() bool { return r.Result != ResultOk && r.Result != ResultError }
  229. // FindInfo 按设备类型和 SN 查找回复项;aGate 系统内唯一,不比较 SN
  230. func (r Reply) FindInfo(deviceType, sn string) (*ReplyInfo, bool) {
  231. for gi := range r.List {
  232. g := &r.List[gi]
  233. if g.Type != deviceType {
  234. continue
  235. }
  236. for ii := range g.Info {
  237. if deviceType == DeviceTypeAGate || g.Info[ii].Sn == sn {
  238. return &g.Info[ii], true
  239. }
  240. }
  241. }
  242. return nil, false
  243. }
  244. /************** 607~610 文件上传 **************/
  245. type UploadCall struct {
  246. FaultRecordID int64 `json:"faultRecordID"`
  247. FileName string `json:"fileName"`
  248. Url string `json:"url"`
  249. LogTime string `json:"logTime"`
  250. }
  251. func ParseUploadCall(dataArea []byte) (UploadCall, error) {
  252. var u UploadCall
  253. err := json.Unmarshal(dataArea, &u)
  254. return u, err
  255. }
  256. // UploadAck 608 上传指令应答
  257. type UploadAck struct {
  258. Result int `json:"result"`
  259. Id int64 `json:"id"` // 平台召唤记录 ID(即 607.faultRecordID)
  260. Filename string `json:"filename"`
  261. }
  262. // ParseUploadAck 解析 608。
  263. // 旧版本设备把 id 字段名误写为 result(同一对象出现两个 result,第二个为 id),后续版本会修复;
  264. // 解析前先把第二个 result 键改名为 id,新旧版本都能按同一结构解析。
  265. func ParseUploadAck(dataArea []byte) (UploadAck, error) {
  266. var a UploadAck
  267. fixed, err := renameDuplicateKey(dataArea, "result", "id")
  268. if err != nil {
  269. return a, fmt.Errorf("608 dataArea: %w", err)
  270. }
  271. err = json.Unmarshal(fixed, &a)
  272. return a, err
  273. }
  274. // renameDuplicateKey 将对象顶层第二次出现的 key 改名为 newKey;没有重复时原样返回
  275. func renameDuplicateKey(obj []byte, key, newKey string) ([]byte, error) {
  276. dec := json.NewDecoder(bytes.NewReader(obj))
  277. if t, err := dec.Token(); err != nil || t != json.Delim('{') {
  278. return nil, fmt.Errorf("not a JSON object")
  279. }
  280. quoted := []byte(`"` + key + `"`)
  281. seen := false
  282. for dec.More() {
  283. kt, err := dec.Token()
  284. if err != nil {
  285. return nil, err
  286. }
  287. end := int(dec.InputOffset())
  288. if k, _ := kt.(string); k == key {
  289. start := end - len(quoted)
  290. if seen && start >= 0 && bytes.Equal(obj[start:end], quoted) {
  291. out := make([]byte, 0, len(obj))
  292. out = append(out, obj[:start]...)
  293. out = append(out, `"`+newKey+`"`...)
  294. return append(out, obj[end:]...), nil
  295. }
  296. seen = true
  297. }
  298. var skip json.RawMessage
  299. if err := dec.Decode(&skip); err != nil {
  300. return nil, err
  301. }
  302. }
  303. return obj, nil
  304. }
  305. // UploadDone 609
  306. type UploadDone struct {
  307. Result int `json:"result"` // 样本成功为 0
  308. FileName string `json:"fileName"`
  309. }
  310. func ParseUploadDone(dataArea []byte) (UploadDone, error) {
  311. var u UploadDone
  312. err := json.Unmarshal(dataArea, &u)
  313. return u, err
  314. }
  315. func (u UploadDone) Ok() bool { return u.Result == 0 }
  316. // UploadFileName 由 379.filename 推得上传文件名
  317. func UploadFileName(batch string) string {
  318. return BatchFromUploadFileName(batch) + ".tar.bz2"
  319. }
  320. // BatchFromUploadFileName 由 609.fileName 去掉扩展名得到批次名
  321. func BatchFromUploadFileName(fileName string) string {
  322. return strings.TrimSuffix(fileName, ".tar.bz2")
  323. }