protocol.go 11 KB

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