GSV4BT.py 7.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259
  1. #!/usr/bin/env python
  2. # -*- coding: utf-8 -*-
  3. import sys
  4. import bluetooth
  5. import time
  6. class GSV4BT():
  7. # https://www.manualslib.com/manual/1380505/Me-Gsv-4.html?page=30#manual
  8. scalings = {
  9. # (ID, value for 0xFFFF, unit)
  10. '2mV': (0x01, 2.1 , 'mV/V'), # Measuring range ±2 mV/V (set_gain 0xB2 <p1> <p2>) with p1=ch, p2=0x01
  11. '10mV': (0x02, 10.5, 'mV/V'), # Measuring range ±10 mV/V (set_gain 0xB2 <p1> <p2>) with p1=ch, p2=0x02
  12. '5V': (0x03, 5.25, 'V' ), # Measuring range 0-5 V (set_gain 0xB2 <p1> <p2>) with p1=ch, p2=0x03
  13. '10V': (0x07, 10.5, 'V' ), # Measuring range 0-10 V (set_gain 0xB2 <p1> <p2>) with p1=ch, p2=0x07
  14. 'PT1000': (0x04, 1050, '°C' ), # Measuring range PT1000 (set_gain 0xB2 <p1> <p2>) with p1=ch, p2=0x04
  15. 'K': (0x06, 1050, '°C' ) # Measuring range K-thermocouple cable (set_gain 0xB2 <p1> <p2>) with p1=ch, p2=0x06
  16. }
  17. channelModes = [
  18. None,
  19. None,
  20. None,
  21. None
  22. ]
  23. values = [0] * 4
  24. frequencies = [
  25. # (ID, fNom in Hz, fEff in Hz)
  26. (0xA0, 0.63, 0.625),
  27. (0xA1, 1.25, 1.250),
  28. (0xA2, 2.5 , 2.500),
  29. (0xA3, 3.75, 3.750),
  30. (0xA4, 6.25, 6.250),
  31. (0xA5, 7.5 , 7.500),
  32. (0xA6, 12.5, 12.40),
  33. (0xA7, 15 , 14.7 ),
  34. (0xA8, 25 , 24.4 ),
  35. (0xA9, 125 , 125 ),
  36. (0xAA, 250 , 250 ),
  37. (0xAB, 500 , 500 ),
  38. (0xAC, 937.5, 900 ),
  39. ]
  40. def __init__(self, addr):
  41. self.addr = addr
  42. self.uuid = None
  43. self.sock = None
  44. self.requiresSetup = True
  45. def printError(self, msg, var = ""):
  46. print("ERROR: GSV4BT {}:".format(self.addr), msg, var)
  47. def printWarning(self, msg, var = ""):
  48. print("WARNING: GSV4BT {}:".format(self.addr), msg, var)
  49. def connect(self):
  50. if self.sock:
  51. return True
  52. service_matches = bluetooth.find_service(address=self.addr, uuid=bluetooth.SERIAL_PORT_CLASS)
  53. if len(service_matches) == 0:
  54. self.printError("BT device not found.")
  55. return False
  56. first_match = service_matches[0]
  57. self.port = first_match["port"]
  58. self.name = first_match["name"]
  59. self.host = first_match["host"]
  60. self.printWarning("Connecting to \"{}\" on {} port {}".format(self.name, self.host, self.port))
  61. self.sock = bluetooth.BluetoothSocket(bluetooth.RFCOMM)
  62. try:
  63. ret = self.sock.connect((self.addr, self.port))
  64. except bluetooth.btcommon.BluetoothError as e:
  65. self.printError(e)
  66. return False
  67. self.sock.settimeout(0.3)
  68. return True
  69. def isConnected(self):
  70. return self.sock and True
  71. def sendRaw(self, data):
  72. if self.sock:
  73. try:
  74. self.sock.send(data)
  75. except bluetooth.btcommon.BluetoothError as e:
  76. self.printError("send", e)
  77. def sendCommand(self, code, *params):
  78. data = bytes([code] + list(params))
  79. return self.sendRaw(data)
  80. def setNormalMode(self):
  81. return self.sendRaw(bytes([0x26, 0x01, 0x62, 0x65, 0x72, 0x6C, 0x69, 0x6E]))
  82. def getMode(self):
  83. self.sendCommand(0x27)
  84. return self.waitResponse(0x27)
  85. def getFirmwareVersion(self):
  86. self.sendCommand(0x2B)
  87. return self.waitResponse(0x2B)
  88. def getTxStatus(self):
  89. self.sendCommand(0x29)
  90. return self.waitResponse(0x29)
  91. # https://www.manualslib.com/manual/1380505/Me-Gsv-4.html?page=34#manual
  92. def setGain(self, channel, scalingName = '2mV'):
  93. self.channelModes[channel] = scalingName
  94. self.sendCommand(0xB2, channel, self.scalings[scalingName][0])
  95. return self.waitResponse(0xB2)
  96. def setFrequency(self, freq = 10):
  97. for id, fNom, fEff in self.frequencies:
  98. value = id
  99. if freq < fEff:
  100. break
  101. self.sendCommand(0x12, value)
  102. return self.waitResponse(0x12)
  103. def startTransmission(self):
  104. self.sendCommand(0x24)
  105. return self.waitResponse(0x24)
  106. def stopTransmission(self):
  107. self.sendCommand(0x23)
  108. return self.waitResponse(0x23)
  109. def getValue(self):
  110. self.sendCommand(0x3B)
  111. lastFrameCarry = None
  112. def recvRaw(self):
  113. if not self.sock:
  114. return
  115. data = None
  116. try:
  117. data = self.sock.recv(1024)
  118. except bluetooth.btcommon.BluetoothError as e:
  119. self.printError("receive", e)
  120. if data == None:
  121. return
  122. if self.lastFrameCarry:
  123. data = self.lastFrameCarry + data
  124. self.lastFrameCarry = None
  125. i = 0
  126. while i < len(data):
  127. prefix = data[i]
  128. start = i
  129. i += 1
  130. end = data.find(b'\r\n', start)
  131. if end == -1:
  132. self.lastFrameCarry = data[start:]
  133. break
  134. else:
  135. i = end + 2
  136. if prefix == 0xA5:
  137. # measured values
  138. if end+2 - start != 11:
  139. self.printError("invalid values frame: length {}".format(end+2-start), data[start:end+2])
  140. continue
  141. self.parseValues(data[start+1:end])
  142. elif prefix == 0x3B:
  143. # response
  144. if end+2 - start < 10:
  145. self.printError("invalid response frame: length {}".format(end+2-start), data[start:end+2])
  146. continue
  147. code = int(data[start+1])
  148. n = int(data[start+2])
  149. length = int.from_bytes(data[start+3:start+5], 'big', signed=False)
  150. no = data[start+5:start+8].decode('ascii')
  151. if end+2 - start != length + 10:
  152. self.printError("incorrect response length field: {}".format(length), data[start:end+2])
  153. continue
  154. self.parseResponse(code, n, no, data[start+8:end])
  155. _valuesCb = None
  156. def setValuesCb(self, cb):
  157. self._valuesCb = cb
  158. def parseValues(self, data):
  159. for i in range(4):
  160. self.values[i] = int.from_bytes(data[i*2:i*2+2], 'big', signed=False)
  161. # map range to units
  162. if self.channelModes[i] == None:
  163. continue
  164. _, scale, unit = self.scalings[self.channelModes[i]]
  165. self.values[i] = (self.values[i] - 32768) / 32768 * scale
  166. if self._valuesCb:
  167. self._valuesCb(self.values)
  168. _respCode = None
  169. _respData = None
  170. def _responseCbWait(self, code, data):
  171. self._respCode = code
  172. self._respData = data
  173. _responseCb = None
  174. def setResponseCb(self, cb):
  175. self._responseCb = cb
  176. def waitResponse(self, sentCode):
  177. userRespCb = self._responseCb
  178. self._respCode = None
  179. self._respData = None
  180. self.setResponseCb(self._responseCbWait)
  181. self.recvRaw()
  182. if self._respCode == None:
  183. return None
  184. if self._respCode != sentCode:
  185. self.printError("invalid response code:", hex(self._respCode))
  186. return None
  187. self.setResponseCb(userRespCb)
  188. return self._respData
  189. def parseResponse(self, code, n, no, data):
  190. if n > 1:
  191. self.printWarning("more than 1 response:", n-1)
  192. if self._responseCb:
  193. self._responseCb(code, data)
  194. def getForces(self):
  195. self.recvRaw()
  196. return self.values[0:3]
  197. def close(self):
  198. self.sock.close()
  199. if __name__ == "__main__":
  200. cell = GSV4BT("00:0B:CE:04:F6:66")
  201. def cb(values):
  202. print(values)
  203. while True:
  204. if cell.isConnected():
  205. cell.recvRaw()
  206. else:
  207. cell.connect()
  208. cell.setNormalMode()
  209. cell.setFrequency(20) # Hz
  210. cell.setGain(0, '2mV')
  211. cell.setGain(1, '2mV')
  212. cell.setGain(2, '2mV')
  213. cell.setGain(3, '5V')
  214. cell.setValuesCb(cb)
  215. print(cell.getMode())
  216. time.sleep(0.3)