#!/usr/bin/python

# bluetooth communication with lego mindstorms ev3

#based on
# file: rfcomm-client.py
# auth: Albert Huang <albert@csail.mit.edu>
# desc: simple demonstration of a client application that uses RFCOMM sockets
#       intended for use with rfcomm-server
#
# $Id: rfcomm-client.py 424 2006-08-24 03:35:54Z albert $

from bluetooth import *
import sys
import array
from os.path import getsize
import struct
import time
import argparse

if sys.version < '3':
    input = raw_input

# bluetooth address of ev3 brick; displayed by hcitool scan
#addr = "AA:BB:CC:DD:EE:FF"
addr = "00:16:53:43:A3:B5"

parser = argparse.ArgumentParser(description='Send binary file(s) by bluetooth to ev3 brick; with default address '+addr)
#parser.add_argument('filename')
parser.add_argument('filenames', metavar='F', nargs='+', help='file(s) to send')
parser.add_argument('-a', '--address', metavar='MAC', default=addr, help='bluetooth address of ev3 brick')

args = parser.parse_args()

#msgfile = args.filename
msgfiles = args.filenames
addr = args.address


# search service at given address
service_matches = find_service( address = addr )

if len(service_matches) == 0:
    print("couldn't find service at address %d" % addr)
    sys.exit(0)

first_match = service_matches[0]
port = first_match["port"]
name = first_match["name"]
host = first_match["host"]

print("Found %i services. Connecting to \"%s\" (channel %s) on %s" % (len(service_matches), name, port, host))

# Create the client socket
sock=BluetoothSocket( RFCOMM )
sock.connect((host, port))

print("connected")

for msgfile in msgfiles:
	try:
		msgsize=getsize(msgfile)
	except OSError:
		print("error: file '%s' not found." %msgfile)
		continue
	msg = array.array('B')
	try:
		f=open(msgfile,"rb")
	except IOError:
		print("error: could not read file '%s'." %msgfile)
		continue
	try:
		msg.fromfile(f,msgsize)
	except IOError:
		print("error: could not read file '%s'." %msgfile)
		f.close()
		continue
	try:
		f.close()
	except IOError:
		print("error: could not read file '%s'." %msgfile)
		continue
	try:
		n=sock.send(msg.tostring())
		print("%i bytes sent\n" % n)
	except KeyboardInterrupt:
		sock.close()
		print "Interrupted by user"
		break
	except BluetoothError:
		sock.close()
		print "bluetooth disconnected"
		break

sock.close()
