Advertisement
Guest User

Python Sonar

a guest
Jul 11th, 2014
963
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.83 KB | None | 0 0
  1. #!/usr/bin/env python2.7
  2.  
  3. # In order to run this you will need python-numpy and alsa-utils to be installed
  4. # I'm sorry for this being quick and dirty
  5.  
  6. from sys import stdin, argv
  7. from struct import unpack, pack, Struct
  8. import subprocess as sp
  9. import numpy as npy
  10. import time
  11.  
  12. rate = 16000
  13. nsamples = 100
  14. nchars = 75
  15. block = 2000
  16. ssize = 2
  17. sformat = "S16_LE"
  18. sendian = "<"
  19. schar = "h"
  20. ssingle = sendian + schar
  21. maxval = (2**14-1)*2+1
  22. minval = -maxval
  23.  
  24. blockformat = sendian + schar * block
  25.  
  26. packer = Struct(blockformat)
  27. up = packer.unpack
  28. pa = packer.pack
  29.  
  30. spack = Struct(sendian+schar)
  31.  
  32. zeroblock = spack.pack(0)*(block*ssize)
  33. tickblock = (
  34.     spack.pack(0) +
  35.     spack.pack(minval) +
  36.     spack.pack(0) +
  37.     spack.pack(maxval) +
  38.     spack.pack(0)*((block-2)*2))
  39. params = [
  40.     "-f", sformat,
  41.     "-r", str(rate),
  42.     "-t", "raw",
  43.     ]
  44. pin = sp.Popen(
  45.     ["arecord", "-c", "1"] + params,
  46.     stdout=sp.PIPE
  47.     )
  48. pout = sp.Popen(
  49.     ["aplay", "-c", "2"] + params,
  50.     stdin=sp.PIPE
  51.     )
  52. calib = None
  53. while True:
  54.     pout.stdin.write(tickblock)
  55.     inp = pin.stdout.read(block*ssize)
  56.     if (len(inp) < block*ssize):
  57.         print "Block discarded, too short"
  58.         break
  59.     inpa = npy.array(packer.unpack(inp))
  60.     inpa = inpa[:-1]-inpa[1:]
  61.     peakt = npy.argmax(inpa)
  62.     if peakt > 100:
  63.         pin.stdout.read(ssize*((peakt-100)/100+1))
  64.     elif peakt < 100:
  65.         pout.stdin.write(zeroblock[:ssize*2])
  66.     part = inpa[peakt:peakt+nsamples]
  67.     if len(part) < nsamples:
  68.         continue
  69.     if calib == None:
  70.         calib = part
  71.         continue
  72.     swap = part
  73.     part = abs(part-calib)
  74.     tmp = [" "]*nchars
  75.     detected = False
  76.     for i in xrange(len(part)):
  77.         threshold = 10+((nsamples-i)*130/nsamples)
  78.         if part[i] > threshold:
  79.             if i > 2:
  80.                 detected = True
  81.             tmp[(i*nchars)/nsamples] = "#"
  82.         elif detected:
  83.             tmp[(i*nchars)/nsamples] = "-"
  84.     if detected:
  85.         print "".join(tmp)
  86.         calib = swap
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement