! rev PF 12/03/2012
! Lancer terminal VBRAY
! test prealable en mode Commande doivent etre OK
! voir Bluetooth_click.log
! Selectionner COM2  115200,N,8,1
!connect
!Hardware:
!Module Bluetooth_Click Mikronicka relie a COM2 via interface RS232 DS275
!Alim 3,3V pour le module
!seuls TX et RX sont connecte
!Archos 43 it
!Association avec Bluetooth_Click
!

debug.on
Prog$="_Bluetooth_Click_120312"
print "Version basic : "; Version$()
Device DV$
print "Device Info : "; DV$
pause 3000

type=0

! When BT is opened, the program  will start listening for another
! device to connect. At this time the user can continue to wait
! for a connection are can attempt to connect to another device
! that is waiting for a connection

! Ask user what to do
array.load type$[], "Connection avec BluetoohCklick", "Continue to listen for connection", "Quitter"
msg$ = "Selection du mode"

debug.print 10

bt.open

new_connection:
select type, type$[], msg$

! If the user pressed the back key or selected quit then quit
! otherwise try to connect to  a listener

debug.print 15

if (type = 0) | (type =3)
print "Thanks for playing"
 bt.close
!debug.print 16
 goto fini
elseif type = 1
bt.connect
Debug.print 17
endif

Debug.print 20
!Read status until a connection is made
Do
 bt.status s
 if s = 1
  print "Listening"
  elseif s =2
   print "Connecting"
   elseif s = 3
    print "Connected"
 endif
 pause 1000
until s =3

Debug.print "s=";s
Debug.print 30

! When a connection is made get the name of the connected device
bt.device.name device$
print "connection to ";device$

Debug.print 35
Debug.print "device=";device$

! *** Read/Write Loop ****
RW_Loop:
Debug.print 40
Debug.print "debut RW_loop"

Do

! Read status to insure that we remain connected.
! If disconnected, program reverts to listen mode.
! In that case, ask user what to do.
 bt.status s
 if s<> 3
  print "Connection perdue"
  goto new_connection
 endif

! Read messages until the message queue is empty
! boucle pour ne pas fractionner le message
 A1$=""
 MsgR$=""
 dr=0
 do
 bt.read.ready rr
 if rr
  dr=1
   bt.read.bytes A1$
   MsgR$=MsgR$+A1$
  end if
 until rr=0

 if dr=1
   print device$; ": ";msgR$
   k1=k1+1
Tone 880,1000
 endif

! Send a message
 if (dr=1) then
  msgE$= "Reception #" +format$("####",k1)+" *"+chr$(13)
  else
 msgE$="*"		% alive !!!
 end if
 bt.write msgE$
 print "Archos: "; msgE$

 pause 500
until (msgR$="fin");


bt.close
pause 2000
bt.open
goto new_connection
Debug.print "fin normale"
fini:
Console.save Prog$+".txt"
end

!OnError:
Debug.print "sortie sur Erreur"
Console.save "Err_"+Prog$+".txt"
pause 2000
end
 
 
