import sys
import time
import serial

def xbeereadline(xbeehand):
    # oldtimeout = xbeehand.timeout
    # xbeehand.timeout = 0.1
    instr = ''
    x = xbeehand.read()
    while x and x != '\n' and x != '\r':
        if x and x != '\r':
            instr += x
        x = xbeehand.read()
    if x == '\n' or x == '\r':
        instr += '\n'
    # xbeehand.timeout = oldtimeout
    return instr

def xbeeatcmd(xbeehand):
    print "Sending +++"
    xbeehand.write('+++')
    time.sleep(1)
    o = xbeehand.read()
    k = xbeehand.read()
    cr = xbeehand.read()
    if (o == 'O' and k == 'K' and cr == '\r'):
        print "OK received"
        xbeehand.write('ATSH\r')
        print xbeereadline(xbeehand)
    else:
        print o,k,cr,


XBEEDEVNAME = '/dev/ttyUSB0'

def xbeedriver():
    try:
        xbeehand = serial.Serial(port=XBEEDEVNAME, baudrate=9600)
        print xbeehand.name
        print "opened ", XBEEDEVNAME
        xbeeatcmd(xbeehand)
        line = xbeereadline(xbeehand)
        print line,
        print "DONE"
    except IOError as inst:
        print 'IOError: ', inst

if __name__ == "__main__":
    xbeedriver()
