#!/usr/bin/env python

import threading
import time
from ctypes import *
#
bca = cdll.LoadLibrary("BCA_Lib.dll")
#
CMPFUNC = CFUNCTYPE(None, c_void_p, c_ubyte, c_ubyte, c_void_p, c_uint, c_void_p)
#BCA_LIB_API void BCA_RegisterPairingFunc(void* antDevice, 
#										 void (*func)(void* context, int* devicelist, unsigned char count, void* cookie), 
#										 void* cookie);

PIRFUNC = CFUNCTYPE(None, c_void_p, POINTER(c_int), c_ubyte, c_void_p)
#
def recv_func(contx, channel, event, data, length, cookie):
	dat = cast(data, POINTER(c_ubyte))
	print "receive channel:", channel, \
													"data:", \
													hex(dat[0]).upper(),\
													hex(dat[1]).upper(),\
													hex(dat[2]).upper(),\
													hex(dat[3]).upper(),\
													hex(dat[4]).upper(),\
													hex(dat[5]).upper(),\
													hex(dat[6]).upper(),\
													hex(dat[7]).upper()
	return
#
def pair_func(contx, devicelist, count, cookie):
	print "pair_func:count", count
	if count > 0:
		device_no = c_int(0)
		device_type = c_int(0)
		trans_type = c_int(0)

		p_device_no = pointer(device_no)
		p_device_type = pointer(device_type)
		p_trans_type = pointer(trans_type)

		res = bca.BCA_GetPairingDeviceInfo(contx, 0, p_device_no, p_device_type, p_trans_type)
		print "pair_func:device_no", device_no
		res = bca.BCA_OpenChannel(contx,\
															0,\
															16,\
															0,\
															device_no,\
															device_type,\
															trans_type,\
															66,\
															c_double(4.0))
	return

class thread(threading.Thread):
		def __init__(self):
				threading.Thread.__init__(self)

		def run(self):
				while loop:
					time.sleep(1)
#
func = CMPFUNC(recv_func)
#
p_func = PIRFUNC(pair_func)
#
loop = 1
#
if __name__ == "__main__":
#
	print "OpenDevice"
	context = bca.BCA_OpenDevice(0)
#
	res = bca.BCA_Init(context);

	print "RegisterReceiveFunc"
	bca.BCA_RegisterReceiveFunc(context, func, context)
#
	print "RegisterPairingFunc"
	bca.BCA_RegisterPairingFunc(context, p_func, context)
#
	print "StartPairing"
	res = bca.BCA_StartPairing(context, 66, c_double(4.0),10)
#
	app = thread()
	app.start()
	app.join()
#
