#!/usr/bin/python3.1
# Scans for BusPirate, just tries a few hardcoded options

# Version 1.0   6.12.2012  Works
# Version 1.1  11.12.2012  Fixed detection to work with firmware 6.1

# Copyright (C) 2012, Arno Wagner <arno@wagner.name>
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# version 2, or a later version at your choice, as published by the 
# Free Software Foundation.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301
# USA.

import serial

candidates = ['/dev/ttyUSB0','/dev/ttyUSB1','/dev/ttyUSB2','/dev/ttyUSB3',
        '/dev/ttyUSB4','/dev/ttyUSB5','/dev/ttyUSB6','/dev/ttyUSB7',
        '/dev/ttyUSB8','/dev/ttyUSB9','/dev/ttyUSB10','/dev/ttyUSB11',
        '/dev/ttyUSB12','/dev/ttyUSB13','/dev/ttyUSB14','/dev/ttyUSB15']

def test_if(name):
  try:
    s = serial.Serial(port=name, baudrate=115200, timeout=0.1)
  except Exception as e:
    return None
  else:
    return s
    
def test_bp(s):
  if s == None:
    return None 
  else:  
    s.write(b'#\n')
    i = s.read(10000)
    sl = i.splitlines() 

    if len(sl) < 4 or \
       ( sl[2][0:10] != b'Bus Pirate' and \
         sl[3][0:10] != b'Bus Pirate' ):
       return None;
    return True

def find_bp():
  # tests list of candidates. Returns serial instance if exactly one found. 
  # If several found, aborts with exception.
  # If none found, returns None           
  cnt = 0
  s_bp = None
  n_bp = None
  n_str = ''
  for n in candidates:
    s = test_if(n)
    is_bp = test_bp(s)
    if is_bp: 
      cnt += 1
      s_bp = s
      n_bp = n
      n_str += n + '\n'
  if cnt > 1:
    raise IOError('More than one Bus Pirate found! Interfaces: \n'+n_str)
  return (s_bp, n_bp)  
    

#for n in candidates:
#  s = test_if(n)
#  is_bp = test_bp(s)
#  print('=====')
#  print(n,': ', end='')
#  print(is_bp)
#  if(is_bp): print(s) 
#print('=====')   
  
a = find_bp()
#print(a)
(s,n) = a
print('device:    ', n)
print('seri_inst: ', s) 
 
  
