from .GSV4BT import GSV4BT
import time
import bluetooth
import threading

class LoadCells():
  def __init__(self):
    self.cells = (
      GSV4BT("00:0B:CE:04:F6:66"),
      GSV4BT("00:0B:CE:04:F6:67"),
      GSV4BT("00:0B:CE:04:F6:68"),
    )
  
  def connect(self):
    success = True
    for cell in self.cells:
      if cell.isConnected():
        pass
      elif cell.connect():
        cell.requiresSetup = True
      else:
        success = False
    return success

  def reconnectThread(self):
    while True:
      self.connect()
      time.sleep(1)

  def start(self):
    self.thread = threading.Thread(target=self.reconnectThread)
    self.thread.start()

  def getForces(self, id):
    cell = self.cells[id]
    if not cell.isConnected():
      return None
    if cell.requiresSetup:
      cell.setNormalMode()
      cell.stopTransmission()
      cell.setFrequency(20) # Hz
      cell.setGain(0, '2mV')
      cell.setGain(1, '2mV')
      cell.setGain(2, '2mV')
      mode = cell.getMode()
      if mode and mode[0] == 0x01:
        cell.requiresSetup = False

    cell.getValue()
    return cell.getForces()

  def scan(self):
    nearby_devices = bluetooth.discover_devices(lookup_names=True)
    print("Found {} devices.".format(len(nearby_devices)))

    for addr, name in nearby_devices:
      print("  {} - {}".format(addr, name))

if __name__ == "__main__":
  cells = LoadCells()

  cells.scan()
  cells.start()
  while True:

    vals = cells.getForces(0)
    if vals:
      print('cell 0: ' + ' '.join(["ch {}: {:8.3f} mV/V".format(i, vals[i]) for i in range(len(vals))]))
    time.sleep(.3)