| 1 |
# Class implementing communication to the USB to the Serial Adapter |
| 2 |
# Require python-usb module installed |
| 3 |
|
| 4 |
import usb, array, time, sys |
| 5 |
|
| 6 |
VENDOR_ID = 0x03eb # Vendor ID of Atmel |
| 7 |
PRODUCT_ID = 0x21ff # Atmega based usb interface |
| 8 |
VDR = 0xC0 # USB Vendor device request |
| 9 |
RS_WRITE = 10 |
| 10 |
RS_READ = 14 |
| 11 |
RS_SETBAUD = 12 |
| 12 |
|
| 13 |
USBMAXTRY = 100 |
| 14 |
USBTIMEOUT = 0 |
| 15 |
PHOENIX_ERR = -1 |
| 16 |
MAXDATA = 802 # 800 + 2 |
| 17 |
buf = array.array('B',MAXDATA * [0]) # unsigned character array, Global |
| 18 |
|
| 19 |
class avrusb: |
| 20 |
def __init__(self): |
| 21 |
busses = usb.busses() |
| 22 |
self.fd = None # Device file handle |
| 23 |
for bus in busses: |
| 24 |
devices = bus.devices |
| 25 |
for dev in devices: # Search for AVRUSB |
| 26 |
if dev.idVendor == VENDOR_ID and dev.idProduct==PRODUCT_ID: |
| 27 |
self.dev = dev |
| 28 |
self.conf = self.dev.configurations[0] |
| 29 |
self.intf = self.conf.interfaces[0][0] |
| 30 |
self.fd = self.dev.open() |
| 31 |
self.fd.setConfiguration(self.conf) |
| 32 |
self.fd.claimInterface(self.intf) |
| 33 |
self.setbaud(38) # 38400 baud |
| 34 |
self.clearbuf() |
| 35 |
|
| 36 |
def setbaud(self, val): |
| 37 |
self.fd.controlMsg(VDR, RS_SETBAUD, 1, value = val, index = 0) |
| 38 |
|
| 39 |
def write(self, val): |
| 40 |
self.fd.controlMsg(VDR, RS_WRITE, 1, value = val) |
| 41 |
# time.sleep(.01) |
| 42 |
|
| 43 |
def read_one(self): # Read one byte, no wait |
| 44 |
res = self.fd.controlMsg(VDR, RS_READ, 1+2) |
| 45 |
if len(res) > 2: |
| 46 |
return res[2] |
| 47 |
|
| 48 |
def clearbuf(self): |
| 49 |
while 1: |
| 50 |
res = self.fd.controlMsg(VDR, RS_READ, 802) |
| 51 |
if len(res) < 3: |
| 52 |
break |
| 53 |
else: |
| 54 |
print ('Cleared ', res[0] + res[1]*256, 'bytes') |
| 55 |
|
| 56 |
def read(self, nb): # loop until getting 'nb' bytes |
| 57 |
index = 0 |
| 58 |
remaining = nb |
| 59 |
timer = 0 |
| 60 |
while remaining: |
| 61 |
if remaining <= 200: |
| 62 |
bsize = remaining |
| 63 |
else: |
| 64 |
bsize = 200 |
| 65 |
part = self.fd.controlMsg(VDR, RS_READ, bsize + 2) |
| 66 |
if len(part) < 3: |
| 67 |
timer = timer + 1 |
| 68 |
if timer > USBMAXTRY: |
| 69 |
return USBTIMEOUT |
| 70 |
continue; |
| 71 |
pl = len(part) - 2 |
| 72 |
for k in range(2,len(part)): |
| 73 |
buf[index] = part[k] |
| 74 |
index = index + 1 |
| 75 |
remaining = remaining - pl |
| 76 |
return index |
| 77 |
|