vedirect.py 2.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788
  1. # import vedirect from https://github.com/karioja/vedirect
  2. # description of channels:https://beta.ivc.no/wiki/index.php/Victron_VE_Direct_DIY_Cable
  3. import serial
  4. class vedirect:
  5. def __init__(self, serialport, timeout):
  6. self.serialport = serialport
  7. self.ser = serial.Serial(serialport, 19200, timeout=timeout)
  8. self.header1 = '\r'
  9. self.header2 = '\n'
  10. self.hexmarker = ':'
  11. self.delimiter = '\t'
  12. self.key = ''
  13. self.value = ''
  14. self.bytes_sum = 0;
  15. self.state = self.WAIT_HEADER
  16. self.dict = {}
  17. (HEX, WAIT_HEADER, IN_KEY, IN_VALUE, IN_CHECKSUM) = range(5)
  18. def input(self, byte):
  19. if byte == self.hexmarker and self.state != self.IN_CHECKSUM:
  20. self.state = self.HEX
  21. if self.state == self.WAIT_HEADER:
  22. self.bytes_sum += ord(byte)
  23. if byte == self.header1:
  24. self.state = self.WAIT_HEADER
  25. elif byte == self.header2:
  26. self.state = self.IN_KEY
  27. return None
  28. elif self.state == self.IN_KEY:
  29. self.bytes_sum += ord(byte)
  30. if byte == self.delimiter:
  31. if (self.key == 'Checksum'):
  32. self.state = self.IN_CHECKSUM
  33. else:
  34. self.state = self.IN_VALUE
  35. else:
  36. self.key += byte
  37. return None
  38. elif self.state == self.IN_VALUE:
  39. self.bytes_sum += ord(byte)
  40. if byte == self.header1:
  41. self.state = self.WAIT_HEADER
  42. self.dict[self.key] = self.value;
  43. self.key = '';
  44. self.value = '';
  45. else:
  46. self.value += byte
  47. return None
  48. elif self.state == self.IN_CHECKSUM:
  49. self.bytes_sum += ord(byte)
  50. self.key = ''
  51. self.value = ''
  52. self.state = self.WAIT_HEADER
  53. if (self.bytes_sum % 256 == 0):
  54. self.bytes_sum = 0
  55. return self.dict
  56. else:
  57. print('Malformed packet')
  58. self.bytes_sum = 0
  59. elif self.state == self.HEX:
  60. self.bytes_sum = 0
  61. if byte == self.header2:
  62. self.state = self.WAIT_HEADER
  63. else:
  64. raise AssertionError()
  65. def read_data(self):
  66. while True:
  67. byte = self.ser.read(1)
  68. packet = self.input(byte)
  69. def read_data_single(self):
  70. while True:
  71. byte = self.ser.read(1)
  72. packet = self.input(byte)
  73. if (packet != None):
  74. return packet
  75. def read_data_callback(self, callbackFunction):
  76. while True:
  77. byte = self.ser.read(1)
  78. if byte:
  79. packet = self.input(byte)
  80. if (packet != None):
  81. callbackFunction(packet)
  82. else:
  83. break
  84. def print_data_callback(data):
  85. print(data)
  86. # end import vedirect