Picadae hardware and control code
選択できるのは25トピックまでです。 トピックは、先頭が英数字で、英数字とダッシュ('-')を使用した35文字以内のものにしてください。

picadae_api.py 11KB

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