serialHandler.py 2.1 KB

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