Picadae hardware and control code
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

picadae_api.py 13KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368
  1. ##| Copyright: (C) 2018-2020 Kevin Larke <contact AT larke DOT org>
  2. ##| License: GNU GPL version 3.0 or above. See the accompanying LICENSE file.
  3. import os,sys,argparse,yaml,types,select,serial,logging,time,datetime
  4. from enum import Enum
  5. from multiprocessing import Process, Pipe
  6. # Message header id's for messages passed between the application
  7. # process and the microcontroller and video processes
  8. class TinyOp(Enum):
  9. setPwmOp = 0
  10. noteOnVelOp = 1
  11. noteOnUsecOp = 2
  12. noteOffOp = 3
  13. setReadAddr = 4
  14. writeOp = 5
  15. writeTableOp = 6
  16. holdDelayOp = 7
  17. invalidOp = 8
  18. class TinyRegAddr(Enum):
  19. kRdRegAddrAddr = 0
  20. kRdTableAddrAddr = 1
  21. kRdEEAddrAddr = 2
  22. kRdSrcAddr = 3
  23. kWrRegAddrAddr = 4
  24. kWrTableAddrAddr = 5
  25. kWrEEAddrAddr = 6
  26. kWrDstAddr = 7
  27. kTmrCoarseAddr = 8
  28. kTmrFineAddr = 9
  29. kTmrPrescaleAddr = 10
  30. kPwmDutyAddr = 11
  31. kPwmFreqAddr = 12
  32. kPwmDivAddr = 13
  33. kStateAddr = 14
  34. kErrorCodeAddr = 15
  35. kMaxAllowTmrAddr = 16
  36. kDelayCoarseAddr = 17
  37. kDelayFineAddr = 18
  38. class TinyConst(Enum):
  39. kRdRegSrcId = TinyRegAddr.kRdRegAddrAddr.value # 0
  40. kRdTableSrcId = TinyRegAddr.kRdTableAddrAddr.value # 1
  41. kRdEESrcId = TinyRegAddr.kRdEEAddrAddr.value # 2
  42. kWrRegDstId = TinyRegAddr.kWrRegAddrAddr.value # 4
  43. kWrTableDstId = TinyRegAddr.kWrTableAddrAddr.value # 5
  44. kWrEEDstId = TinyRegAddr.kWrEEAddrAddr.value # 6
  45. kWrAddrFl = 0x08 # first avail bit above kWrEEAddr
  46. class SerialMsgId(Enum):
  47. QUIT_MSG = 0xffff
  48. DATA_MSG = 0xfffe
  49. class Result(object):
  50. def __init__( self, value=None, msg=None ):
  51. self.value = value
  52. self.msg = msg
  53. def set_error( self, msg ):
  54. if self.msg is None:
  55. self.msg = ""
  56. self.msg += " " + msg
  57. def __bool__( self ):
  58. return self.msg is None
  59. def _serial_process_func( serial_dev, baud, pipe ):
  60. reset_N = 0
  61. drop_N = 0
  62. noSync_N = 0
  63. with serial.Serial(serial_dev, baud) as port:
  64. while True:
  65. # get the count of available bytes in the serial port buffer
  66. bytes_waiting_N = port.in_waiting
  67. # if no serial port bytes are available then sleep ....
  68. if bytes_waiting_N == 0:
  69. time.sleep(0.01) # ... for 10 ms
  70. else: # read the serial port ...
  71. v = port.read(bytes_waiting_N)
  72. pipe.send((SerialMsgId.DATA_MSG,v)) # ... and send it to the parent
  73. msg = None
  74. if pipe.poll(): # non-blocking check for parent process messages
  75. try:
  76. msg = pipe.recv()
  77. except EOFError:
  78. break
  79. # if an incoming message was received
  80. if msg != None:
  81. # this is a shutdown msg
  82. if msg[0] == SerialMsgId.QUIT_MSG:
  83. pipe.send(msg) # ... send quit msg back
  84. break
  85. # this is a data xmit msg
  86. elif msg[0] == SerialMsgId.DATA_MSG:
  87. port.write(msg[1])
  88. class SerialProcess(Process):
  89. def __init__(self,serial_dev,serial_baud):
  90. self.parent_end, child_end = Pipe()
  91. super(SerialProcess, self).__init__(target=_serial_process_func, name="Serial", args=(serial_dev,serial_baud,child_end,))
  92. self.doneFl = False
  93. def quit(self):
  94. # send quit msg to the child process
  95. self.parent_end.send((SerialMsgId.QUIT_MSG,0))
  96. def send(self,msg_id,value):
  97. # send a msg to the child process
  98. self.parent_end.send((msg_id,value))
  99. return Result()
  100. def recv(self):
  101. #
  102. x = None
  103. if not self.doneFl and self.parent_end.poll():
  104. x = self.parent_end.recv()
  105. if x[0] == SerialMsgId.QUIT_MSG:
  106. self.doneFl = True
  107. return x
  108. def is_done(self):
  109. return self.doneFl
  110. class Picadae:
  111. def __init__( self, key_mapL, i2c_base_addr=21, serial_dev='/dev/ttyACM0', serial_baud=38400, prescaler_usec=16 ):
  112. """
  113. key_mapL = [{ index, board, ch, type, midi, class }]
  114. serial_dev = /dev/ttyACM0
  115. serial_baud = 38400
  116. i2c_base_addr = 1
  117. """
  118. self.serialProc = SerialProcess( serial_dev, serial_baud )
  119. self.keyMapD = { d['midi']:d for d in key_mapL }
  120. self.i2c_base_addr = i2c_base_addr
  121. self.prescaler_usec = prescaler_usec
  122. self.log_level = 0
  123. self.serialProc.start()
  124. def close( self ):
  125. self.serialProc.quit()
  126. def wait_for_serial_sync(self, timeoutMs=10000):
  127. # wait for the letter 'a' to come back from the serial port
  128. result = self.block_on_serial_read(1,timeoutMs)
  129. if result and len(result.value)>0 and result.value[0] == ord('a'):
  130. pass
  131. else:
  132. result.set_error("Serial sync failed.")
  133. return result
  134. def write_tiny_reg( self, i2c_addr, reg_addr, byteL ):
  135. return self._send( 'w', i2c_addr, reg_addr, [ len(byteL) ] + byteL )
  136. def call_op( self, midi_pitch, op_code, argL ):
  137. return self.write_tiny_reg( self._pitch_to_i2c_addr( midi_pitch ), op_code, argL )
  138. def set_read_addr( self, i2c_addr, mem_id, addr ):
  139. # mem_id: 0=reg_array 1=vel_table 2=eeprom
  140. return self.write_tiny_reg(i2c_addr, TinyOp.setReadAddr.value,[ mem_id, addr ])
  141. def read_request( self, i2c_addr, reg_addr, byteOutN ):
  142. return self._send( 'r', i2c_addr, reg_addr,[ byteOutN ] )
  143. def block_on_serial_read( self, byteOutN, time_out_ms=250 ):
  144. ts = datetime.datetime.now() + datetime.timedelta(milliseconds=time_out_ms)
  145. retL = []
  146. while datetime.datetime.now() < ts and len(retL) < byteOutN:
  147. # If a value is available at the serial port return is otherwise return None.
  148. x = self.serialProc.recv()
  149. if x is not None and x[0] == SerialMsgId.DATA_MSG:
  150. for b in x[1]:
  151. retL.append(int(b))
  152. time.sleep(0.01)
  153. result = Result(value=retL)
  154. if len(retL) < byteOutN:
  155. result.set_error("Serial port time out on read.")
  156. return result
  157. def block_on_picadae_read( self, midi_pitch, mem_id, reg_addr, byteOutN, time_out_ms=250 ):
  158. i2c_addr = self._pitch_to_i2c_addr( midi_pitch )
  159. result = self.set_read_addr( i2c_addr, mem_id, reg_addr )
  160. if result:
  161. result = self.read_request( i2c_addr, TinyOp.setReadAddr.value, byteOutN )
  162. if result:
  163. result = self.block_on_serial_read( byteOutN, time_out_ms )
  164. return result
  165. def block_on_picadae_read_reg( self, midi_pitch, reg_addr, byteOutN=1, time_out_ms=250 ):
  166. return self.block_on_picadae_read( midi_pitch,
  167. TinyRegAddr.kRdRegAddrAddr.value,
  168. reg_addr,
  169. byteOutN,
  170. time_out_ms )
  171. def note_on_vel( self, midi_pitch, midi_vel ):
  172. return self.call_op( midi_pitch, TinyOp.noteOnVelOp.value, [self._validate_vel(midi_vel)] )
  173. def note_on_us( self, midi_pitch, pulse_usec ):
  174. return self.call_op( midi_pitch, TinyOp.noteOnUsecOp.value, list(self._usec_to_coarse_and_fine(pulse_usec)) )
  175. def note_off( self, midi_pitch ):
  176. return self.call_op( midi_pitch, TinyOp.noteOffOp.value,
  177. [0] ) # TODO: sending a dummy byte because we can't handle sending a command with no data bytes.
  178. def set_hold_delay( self, midi_pitch, pulse_usec ):
  179. return self.call_op( midi_pitch, TinyOp.holdDelayOp.value, list(self._usec_to_coarse_and_fine(pulse_usec)) )
  180. def get_hold_delay( self, midi_pitch, time_out_ms=250 ):
  181. res = self.block_on_picadae_read_reg( midi_pitch, TinyRegAddr.kDelayCoarseAddr.value, byteOutN=2, time_out_ms=time_out_ms )
  182. if len(res.value) == 2:
  183. res.value = [ self.prescaler_usec*255*res.value[0] + self.prescaler_usec*res.value[1] ]
  184. return res
  185. def set_velocity_map( self, midi_pitch, midi_vel, pulse_usec ):
  186. coarse,fine = self._usec_to_coarse_and_fine( pulse_usec )
  187. src = TinyConst.kWrAddrFl.value | TinyConst.kWrTableDstId.value
  188. addr = midi_vel*2
  189. return self.call_op( midi_pitch, TinyOp.writeOp.value, [ src, addr, coarse, fine ] )
  190. def get_velocity_map( self, midi_pitch, midi_vel, time_out_ms=250 ):
  191. byteOutN = 2
  192. return self.block_on_picadae_read( midi_pitch, TinyConst.kRdTableSrcId.value, midi_vel*2, byteOutN, time_out_ms )
  193. def set_pwm_duty( self, midi_pitch, duty_cycle_pct ):
  194. if 0 <= duty_cycle_pct and duty_cycle_pct <= 100:
  195. # duty_cycle_pct = 100.0 - duty_cycle_pct
  196. return self.call_op( midi_pitch, TinyOp.setPwmOp.value, [ int( duty_cycle_pct * 255.0 /100.0 )])
  197. else:
  198. return Result(msg="Duty cycle (%f) out of range 0-100." % (duty_cycle_pct))
  199. def get_pwm_duty( self, midi_pitch, time_out_ms=250 ):
  200. return self.block_on_picadae_read_reg( midi_pitch, TinyRegAddr.kPwmDutyAddr.value, time_out_ms=time_out_ms )
  201. def set_pwm_freq( self, midi_pitch, freq ):
  202. res = self.get_pwm_duty( midi_pitch )
  203. if res:
  204. print("duty",int(res.value[0]))
  205. res = self.call_op( midi_pitch, TinyOp.setPwmOp.value, [ int(res.value[0]), int(freq) ])
  206. return res
  207. def get_pwm_freq( self, midi_pitch, time_out_ms=250 ):
  208. return self.block_on_picadae_read_reg( midi_pitch, TinyRegAddr.kPwmFreqAddr.value, time_out_ms=time_out_ms )
  209. def get_pwm_div( self, midi_pitch, time_out_ms=250 ):
  210. return self.block_on_picadae_read_reg( midi_pitch, TinyRegAddr.kPwmDivAddr.value, time_out_ms=time_out_ms )
  211. def set_pwm_div( self, midi_pitch, div, time_out_ms=250 ):
  212. res = self.get_pwm_duty( midi_pitch )
  213. if res:
  214. duty = res.value[0]
  215. res = self.get_pwm_freq( midi_pitch )
  216. if res:
  217. res = self.call_op( midi_pitch, TinyOp.setPwmOp.value, [ int(duty), int(res.value[0]), int(div) ])
  218. return res
  219. def write_table( self, midi_pitch, time_out_ms=250 ):
  220. # TODO: sending a dummy byte because we can't handle sending a command with no data bytes.
  221. return self.call_op( midi_pitch, TinyOp.writeTableOp.value,[0])
  222. def make_note( self, midi_pitch, atk_us, dur_ms ):
  223. # TODO: handle error on note_on_us()
  224. self.note_on_us(midi_pitch, atk_us);
  225. time.sleep( dur_ms / 1000.0 )
  226. return self.note_off(midi_pitch)
  227. def make_seq( self, midi_pitch, base_atk_us, dur_ms, delta_us, note_cnt ):
  228. for i in range(note_cnt):
  229. self.make_note( midi_pitch, base_atk_us + i*delta_us, dur_ms )
  230. time.sleep( dur_ms / 1000.0 )
  231. return Result()
  232. def set_log_level( self, log_level ):
  233. self.log_level = log_level
  234. return Result()
  235. def _pitch_to_i2c_addr( self, pitch ):
  236. return self.keyMapD[ pitch ]['index'] + self.i2c_base_addr
  237. def _validate_vel( self, vel ):
  238. return vel
  239. def _usec_to_coarse_and_fine( self, usec ):
  240. coarse_usec = self.prescaler_usec*255 # usec's in one coarse tick
  241. coarse = int( usec / coarse_usec )
  242. fine = int(round((usec - coarse*coarse_usec) / self.prescaler_usec))
  243. assert( coarse <= 255 )
  244. assert( fine <= 255)
  245. x = coarse*coarse_usec + fine*self.prescaler_usec
  246. print("C:%i F:%i : %i %i (%i)" % (coarse,fine, x, usec, usec-x ))
  247. return coarse,fine
  248. def _send( self, opcode, i2c_addr, reg_addr, byteL ):
  249. self._print( opcode, i2c_addr, reg_addr, byteL )
  250. byteA = bytearray( [ord(opcode), i2c_addr, reg_addr ] + byteL )
  251. return self.serialProc.send(SerialMsgId.DATA_MSG, byteA )
  252. def _print( self, opcode, i2c_addr, reg_addr, byteL ):
  253. if self.log_level:
  254. s = "{} {} {}".format( opcode, i2c_addr, reg_addr )
  255. for x in byteL:
  256. s += " {}".format(x)
  257. print(s)