nmea0183_converter.py 2.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798
  1. """
  2. @Date :2021/5/21/00219:10:57
  3. @Desc :
  4. """
  5. from sanic.log import logger
  6. import binascii
  7. from converter import Converter
  8. class NEMA0183Converter(Converter):
  9. def convert(self, config, data):
  10. data = data.decode()
  11. if self.checksum(data):
  12. res = self.check_type(config, data)
  13. return res
  14. return "error"
  15. def make_checksum(self, data):
  16. '''
  17. Calculates a checksum from a NMEA sentence.
  18. Keyword arguments:
  19. data -- the NMEA sentence to create
  20. '''
  21. csum = 0
  22. i = 0
  23. # Remove ! or $ and *xx in the sentence
  24. data = data[1:data.rfind('*')]
  25. while (i < len(data)):
  26. input = binascii.b2a_hex(data[i].encode("utf8"))
  27. input = int(input, 16)
  28. # xor
  29. csum = csum ^ input
  30. i += 1
  31. return csum
  32. def checksum(self, data):
  33. '''
  34. Reads the checksum of an NMEA sentence.
  35. Keyword arguments:
  36. data -- the NMEA sentence to check
  37. '''
  38. try:
  39. # Create an integer of the two characters after the *, to the right
  40. supplied_csum = int(data[data.rfind('*') + 1:data.rfind('*') + 3], 16)
  41. except:
  42. return ''
  43. # Create the checksum
  44. csum = self.make_checksum(data)
  45. # Compare and return
  46. if csum == supplied_csum:
  47. return True
  48. else:
  49. return False
  50. def check_type(self, config, data):
  51. logger.info(f"原始数据(波高传感器):len:{len(data)}, data: {data}")
  52. dict = {}
  53. data = data.split('*')
  54. # Splits up the NMEA data by comma
  55. data = data[0].split(',')
  56. if data[0] == '$PMIRWM':
  57. for index in config:
  58. name = 'c' + str(index['serial_number'])
  59. i = int(index['address'])
  60. dict[name] = data[i]
  61. logger.info(f"解析后数据(波高传感器):len:{len(dict)}, dict: {dict}")
  62. return dict
  63. # return data[0]
  64. def nmea2utc(self, data):
  65. '''
  66. Converts NMEA utc format to more standardized format.
  67. '''
  68. time = data[1][0:2] + ':' + data[1][2:4] + ':' + data[1][4:6]
  69. date = '20' + data[9][4:6] + '-' + data[9][2:4] + '-' + data[9][0:2]
  70. return date + 'T' + time + 'Z'
  71. '''
  72. data = "$PMIRR,20210325,033351.719,0.000,0.000,V,0.00*0F"
  73. data2 = data.split('*')
  74. data2 = data2[0].split(',')
  75. logger.debug(data2[0][3:6])
  76. c = NEMA0183Converter(None)
  77. d = c.checksum(data)
  78. logger.debug(d)
  79. logger.debug(c.nmea2utc(data2[1]))
  80. '''