loadCells.py 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104
  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.start()
  49. def tare(self):
  50. for i in range(len(self.cells)):
  51. cell = self.cells[i]
  52. if (not cell.isConnected()) or cell.requiresSetup:
  53. self.tareValues[i].fill(0)
  54. else:
  55. cell.getValue()
  56. self.tareValues[i] = cell.getForces()
  57. self.tareValues[np.isnan(self.tareValues)] = 0
  58. def stop(self):
  59. if self.running:
  60. self.running = False
  61. def getForces(self):
  62. res = np.ndarray(shape=(len(self.cells),3), dtype=float)
  63. for i in range(len(self.cells)):
  64. cell = self.cells[i]
  65. if (not cell.isConnected()) or cell.requiresSetup:
  66. res[i].fill(float('NaN'))
  67. else:
  68. cell.getValue()
  69. res[i] = cell.getForces()
  70. return res - self.tareValues
  71. def scan(self):
  72. nearby_devices = bluetooth.discover_devices(lookup_names=True)
  73. print("Found {} devices.".format(len(nearby_devices)))
  74. for addr, name in nearby_devices:
  75. print(" {} - {}".format(addr, name))
  76. if __name__ == "__main__":
  77. cells = LoadCells()
  78. cells.scan()
  79. try:
  80. cells.start()
  81. while True:
  82. vals = cells.getForces(0)
  83. if vals[0] != None:
  84. print('cell 0: ' + ' '.join(["ch {}: {:8.3f} mV/V".format(i, vals[i]) for i in range(len(vals))]))
  85. time.sleep(.3)
  86. except KeyboardInterrupt as e:
  87. cells.stop()