serialHandler.py 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111
  1. import serial
  2. from serial import SerialException
  3. import numpy as np
  4. class SerialConnection:
  5. def __init__(self):
  6. self._ser = None
  7. self._brightness = 15
  8. self.port = None
  9. def connect(self, port = None):
  10. if port == None:
  11. port = self.port
  12. if port == None:
  13. for port in ["/dev/ttyUSB{}".format(p) for p in range(4)]:
  14. try:
  15. self._ser = serial.Serial(port, 115200)
  16. print("connected to " + port)
  17. self.port = port
  18. break
  19. except serial.SerialException:
  20. pass
  21. if port == None:
  22. for port in ["COM{}".format(p) for p in range(3,20)]:
  23. try:
  24. self._ser = serial.Serial(port, 115200)
  25. print("connected to " + port)
  26. self.port = port
  27. break
  28. except serial.SerialException:
  29. pass
  30. else:
  31. try:
  32. self._ser = serial.Serial(port, 115200)
  33. print("connected to " + port)
  34. self.port = port
  35. except serial.SerialException:
  36. pass
  37. if self._ser:
  38. self._ser.write(b'~u~t~c ')
  39. else:
  40. print("connection to port {} failed".format(port))
  41. def send(self, matrix):
  42. if not self._ser:
  43. return
  44. buf = [32] * (4**3)
  45. for z in range(4):
  46. for y in range(4):
  47. for x in range(4):
  48. if matrix[x][y][z] >= 1:
  49. b = self._brightness
  50. elif matrix[x][y][z] >= 0:
  51. b = min(int(matrix[x][y][z] * 15), self._brightness)
  52. else:
  53. b = 0
  54. buf[z*16+y*4+x] = b + 32
  55. try:
  56. self._ser.write(b'~a')
  57. self._ser.write(bytearray(buf))
  58. except serial.SerialException:
  59. self._ser = None
  60. def setBrightness(self, brightness):
  61. self._brightness = brightness
  62. def isConnected(self):
  63. return self._ser != None
  64. class Visualization:
  65. def __init__(self):
  66. self.matrix = np.zeros((4,4,4))
  67. def clear(self):
  68. self.matrix = np.zeros((4,4,4))
  69. def noteCircle(self, notes, z=0):
  70. matrix = np.zeros((4,4,4))
  71. map = [
  72. [ 0, 1, 2, 3],
  73. [11,-1,-1, 4],
  74. [10,-1,-1, 5],
  75. [ 9, 8, 7, 6],
  76. ]
  77. for x, line in enumerate(map[::-1]):
  78. for y, i in enumerate(line):
  79. if i < 0:
  80. continue
  81. matrix[x][y][z] = notes[i]
  82. return matrix
  83. def ampPyramid(self, vals):
  84. matrix = np.zeros((4,4,4))
  85. coords = [
  86. (1,1),
  87. (2,2),
  88. (1,2),
  89. (2,1)
  90. ]
  91. for i, (x, y) in enumerate(coords):
  92. for z in range(4):
  93. if vals[i] > z * 0.25:
  94. matrix[x][y][z] = (vals[i] * 4 - z) * 0.5
  95. return matrix