123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111 |
- import serial
- from serial import SerialException
- import numpy as np
- class SerialConnection:
- def __init__(self):
- self._ser = None
- self._brightness = 15
- self.port = None
-
- def connect(self, port = None):
- if port == None:
- port = self.port
- if port == None:
- for port in ["/dev/ttyUSB{}".format(p) for p in range(4)]:
- try:
- self._ser = serial.Serial(port, 115200)
- print("connected to " + port)
- self.port = port
- break
- except serial.SerialException:
- pass
-
- if port == None:
- for port in ["COM{}".format(p) for p in range(3,20)]:
- try:
- self._ser = serial.Serial(port, 115200)
- print("connected to " + port)
- self.port = port
- break
- except serial.SerialException:
- pass
- else:
- try:
- self._ser = serial.Serial(port, 115200)
- print("connected to " + port)
- self.port = port
- except serial.SerialException:
- pass
- if self._ser:
- self._ser.write(b'~u~t~c ')
- else:
- print("connection to port {} failed".format(port))
-
- def send(self, matrix):
- if not self._ser:
- return
- buf = [32] * (4**3)
-
- for z in range(4):
- for y in range(4):
- for x in range(4):
- if matrix[x][y][z] >= 1:
- b = self._brightness
- elif matrix[x][y][z] >= 0:
- b = min(int(matrix[x][y][z] * 15), self._brightness)
- else:
- b = 0
-
- buf[z*16+y*4+x] = b + 32
-
- try:
- self._ser.write(b'~a')
- self._ser.write(bytearray(buf))
- except serial.SerialException:
- self._ser = None
-
- def setBrightness(self, brightness):
- self._brightness = brightness
-
- def isConnected(self):
- return self._ser != None
-
- class Visualization:
- def __init__(self):
- self.matrix = np.zeros((4,4,4))
-
- def clear(self):
- self.matrix = np.zeros((4,4,4))
-
- def noteCircle(self, notes, z=0):
- matrix = np.zeros((4,4,4))
- map = [
- [ 0, 1, 2, 3],
- [11,-1,-1, 4],
- [10,-1,-1, 5],
- [ 9, 8, 7, 6],
- ]
- for x, line in enumerate(map[::-1]):
- for y, i in enumerate(line):
- if i < 0:
- continue
- matrix[x][y][z] = notes[i]
- return matrix
-
- def ampPyramid(self, vals):
- matrix = np.zeros((4,4,4))
- coords = [
- (1,1),
- (2,2),
- (1,2),
- (2,1)
- ]
- for i, (x, y) in enumerate(coords):
- for z in range(4):
- if vals[i] > z * 0.25:
- matrix[x][y][z] = (vals[i] * 4 - z) * 0.5
- return matrix
-
|