meter.go 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990
  1. package iotMeter
  2. import (
  3. "IotAdmin/core/tools/utils"
  4. iotInterface "IotAdmin/iot/interface"
  5. iotMap "IotAdmin/iot/map"
  6. iotProtocol "IotAdmin/iot/protocol"
  7. iotProtocolHandler "IotAdmin/iot/protocol/handler"
  8. iotRtuService "IotAdmin/iot/service/rtuService"
  9. iotStruct "IotAdmin/iot/struct"
  10. "errors"
  11. "fmt"
  12. )
  13. func SetMeterAddress(sn, protocol string, addr, newAddr int) error {
  14. client, handler, rtu, err := getClientHandle(sn, protocol, addr)
  15. if err != nil {
  16. return err
  17. }
  18. client.MLock.Lock()
  19. defer client.MLock.Unlock()
  20. if newAddr == addr {
  21. return errors.New("新地址不能与旧地址相同")
  22. }
  23. if newAddr < 1 || newAddr > 255 {
  24. return errors.New("新地址范围1-255")
  25. }
  26. if err = handler.SetAddress(rtu, newAddr); err != nil {
  27. return fmt.Errorf("表计地址设置失败: %s", err.Error())
  28. }
  29. return nil
  30. }
  31. func SetMeterConfig(sn, protocol string, addr int, data *string) error {
  32. client, handler, rtu, err := getClientHandle(sn, protocol, addr)
  33. if err != nil {
  34. return err
  35. }
  36. client.MLock.Lock()
  37. defer client.MLock.Unlock()
  38. if err = handler.SetConfig(rtu, data); err != nil {
  39. return fmt.Errorf("表计配置设置失败: %s", err.Error())
  40. }
  41. return nil
  42. }
  43. func GetMeterConfig(sn, protocol string, addr int) (data interface{}, err error) {
  44. client, handler, rtu, err := getClientHandle(sn, protocol, addr)
  45. if err != nil {
  46. return
  47. }
  48. client.MLock.Lock()
  49. defer client.MLock.Unlock()
  50. if data, err = handler.GetConfig(rtu); err != nil {
  51. err = fmt.Errorf("表计配置获取失败: %s", err.Error())
  52. }
  53. return
  54. }
  55. func getClientHandle(sn, protocol string, addr int) (client *iotStruct.DtuClient, handle iotInterface.MeterHandler, rtu iotRtuService.RtuNetPgr, err error) {
  56. if !iotProtocol.VerifyMeterProtocol(protocol) {
  57. err = errors.New("表计协议不支持")
  58. return
  59. }
  60. if addr < 1 || addr > 255 {
  61. err = errors.New("地址范围1-255")
  62. return
  63. }
  64. _, ok := iotMap.MapDtuDevice.Get(sn)
  65. if !ok {
  66. err = errors.New("表计不存在")
  67. return
  68. }
  69. client, ok = iotMap.MapDtuClient.Get(sn)
  70. if !ok {
  71. err = errors.New("表计正在通信或已离线,请稍后再试!")
  72. return
  73. }
  74. rtu = iotRtuService.NewRtuNetPgr(utils.IntoByte(addr))
  75. rtu.SetClientState(client)
  76. rtu.SetSerialNumber(sn)
  77. handle, err = iotProtocolHandler.GetMeterHandler(protocol)
  78. return
  79. }
  80. func IsOnline(sn string) bool {
  81. _, ok := iotMap.MapDtuClient.Get(sn)
  82. return ok
  83. }