loadCells.py 2.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106
  1. if __name__ == "__main__":
  2. from GSV4BT import GSV4BT
  3. else:
  4. from .GSV4BT import GSV4BT
  5. import time
  6. import bluetooth
  7. import threading
  8. import ctypes
  9. import numpy as np
  10. class LoadCells():
  11. def __init__(self):
  12. self.cells = (
  13. GSV4BT("00:0B:CE:04:F6:66"),
  14. GSV4BT("00:0B:CE:04:F6:67"),
  15. GSV4BT("00:0B:CE:04:F6:68"),
  16. )
  17. self.tareValues = np.ndarray(shape=(len(self.cells),3), dtype=float)
  18. self.tareValues.fill(0)
  19. def connect(self):
  20. success = True
  21. for cell in self.cells:
  22. if not self.running:
  23. return
  24. elif cell.isConnected():
  25. if cell.requiresSetup:
  26. cell.setNormalMode()
  27. cell.stopTransmission()
  28. cell.setFrequency(20) # Hz
  29. cell.setGain(0, '2mV')
  30. cell.setGain(1, '2mV')
  31. cell.setGain(2, '2mV')
  32. mode = cell.getMode()
  33. if mode and mode[0] == 0x01:
  34. cell.requiresSetup = False
  35. elif cell.connect():
  36. cell.requiresSetup = True
  37. else:
  38. success = False
  39. cell.requiresSetup = True
  40. return success
  41. def reconnectThread(self):
  42. while self.running:
  43. time.sleep(1)
  44. self.connect()
  45. def start(self):
  46. self.running = True
  47. self.thread = threading.Thread(target=self.reconnectThread)
  48. self.thread.daemon = True
  49. self.thread.start()
  50. def tare(self):
  51. for i in range(len(self.cells)):
  52. cell = self.cells[i]
  53. if (not cell.isConnected()) or cell.requiresSetup:
  54. self.tareValues[i].fill(0)
  55. else:
  56. cell.getValue()
  57. self.tareValues[i] = cell.getForces()
  58. self.tareValues[np.isnan(self.tareValues)] = 0
  59. def stop(self):
  60. for cell in self.cells:
  61. cell.disconnect()
  62. self.running = False
  63. def getForces(self):
  64. res = np.ndarray(shape=(len(self.cells),3), dtype=float)
  65. for i in range(len(self.cells)):
  66. cell = self.cells[i]
  67. if (not cell.isConnected()) or cell.requiresSetup:
  68. res[i].fill(float('NaN'))
  69. else:
  70. cell.getValue()
  71. res[i] = cell.getForces()
  72. return res - self.tareValues
  73. def scan(self):
  74. nearby_devices = bluetooth.discover_devices(lookup_names=True)
  75. print("Found {} devices.".format(len(nearby_devices)))
  76. for addr, name in nearby_devices:
  77. print(" {} - {}".format(addr, name))
  78. if __name__ == "__main__":
  79. cells = LoadCells()
  80. cells.scan()
  81. try:
  82. cells.start()
  83. while True:
  84. for vals in cells.getForces():
  85. if not np.isnan(vals[0]):
  86. print('cell: ' + ' '.join(["ch {}: {:8.3f} mV/V".format(i, vals[i]) for i in range(len(vals))]))
  87. time.sleep(.3)
  88. except KeyboardInterrupt as e:
  89. cells.stop()