Source

maple-stm32-learn / stream_play / wavserver.py

import sys, os
import time
import logging
import threading
import serial
import scipy.io.wavfile

BAUDRATE = 2000000

class Wavserver(object):
    def __init__(self, wavarr, srate, serialinstance):
        self.wavarr = wavarr
        self.srate = srate
        self.ser = serialinstance
        self.pos = 0
        self.blcksize=1024

    def hello(self):
        self.ser.flushOutput()
        self.ser.flushInput()
        self.ser.write('h')
        resp = self.ser.readline(),
        if not resp:
            print "error--timeout, no response"
        else:
            print resp[0],

    def stop(self):
        self.ser.flushOutput()
        self.ser.write('s')

    def play(self):
        ser = self.ser
        ser.write('p')
        while 1:
            # waiting = ser.inWaiting()
            ## if waiting:
            ch = ser.read(1)

            if ch == 'U':
                datastr=self.wavarr[self.pos:self.pos+self.blcksize].tostring()
                print "len(datastr): %d" % len(datastr)
                ser.write(datastr)
                self.pos += self.blcksize
            else:
                print ch,

    def test_serial_upload(self):
        ser = self.ser
        ser.write('t')
        ch = ser.read(1)

        if ch == 'U':
            datastr=self.wavarr[self.pos:self.pos+self.blcksize].tostring()
            print "len(datastr): %d" % len(datastr)
            ser.write(datastr)
            self.pos += self.blcksize
        else:
            print ch,




        
    def debug(self):
        self.ser.write('d');
        for xx in self.ser.readlines():
            print xx

if __name__ == '__main__':
    import optparse

    parser = optparse.OptionParser(
        usage = "%prog [options] port wavefilename",
        description = "serve a wavfile to the maple+audio_codec board.",
        epilog = """\


Only one connection at once is supported. When the connection is terminated
it waits for the next connect.
""")


    parser.add_option("-v", "--verbose",
        dest = "verbosity",
        action = "count",
        help = "print more diagnostic messages (option can be given multiple times)",
        default = 0
    )

    (options, args) = parser.parse_args()
    if len(args) != 2:
        parser.error('<serial port name> and <wavefile name> are required as arguments')

    port = args[0]
    wavefilename = args[1]
        

    logging.basicConfig(level=logging.INFO)
    logging.getLogger('root').setLevel(logging.INFO)
    logging.getLogger('wavserver').setLevel(logging.INFO)

    try:
        srate, wavarr = scipy.io.wavfile.read(wavefilename)
    except:
        logging.error("Could not open wavefile %s - %s " % wavefilename)
        sys.exit(1)
    logging.info("Opened wavfile: %s" % wavefilename)
    logging.info("srate %s, wavarr.dtype: %s, shape=%s" % (srate, wavarr.dtype, wavarr.shape))
    
    ser = serial.Serial()
    ser.port = port
    ser.timeout=3
    ser.baudrate = BAUDRATE
    try:
        ser.open()
    except serial.SerialException, e:
        logging.error("Could not open serial port %s: %s" % (ser.portstr, e))
        sys.exit(1)

    logging.info("Opened serial port: %s" % (ser.portstr,))


    wserver = Wavserver(wavarr, srate, ser)
    ws=wserver