Sub Process_Globals
Dim BT As BluetoothAdmin
Dim Serial1 As Serial
Dim timerBT As Timer
Dim timerLettura As Timer
Dim AStreams As AsyncStreams
Dim tr As TextReader
Dim MyDeviceName As String
Dim MacAddress As String
Private sb As StringBuilder
Public charset As String = "UTF8"
End Sub
Sub Service_Create
If File.Exists(File.DirRootExternal, "Bluetooth.txt") Then
tr.Initialize2(File.OpenInput(File.DirRootExternal, "Bluetooth.txt"), "Windows-1252")
MacAddress = tr.ReadLine
MyDeviceName = tr.ReadLine
tr.Close
End If
ToastMessageShow("Connessione " & MyDeviceName & " MacAddress "& MacAddress, True)
ToastMessageShow("Trying to connect to " & MyDeviceName, True)
timerBT.Initialize("timerBT",5000)
timerBT.Enabled = False
Try
sb.Initialize
BT.Initialize("BT")
Serial1.Initialize("Serial1")
Catch
ToastMessageShow("No BlueTooth Device visible...", False)
End Try
End Sub
Sub Service_Start (StartingIntent As Intent)
'Start Bluetooth
Try
If BT.IsEnabled = False Then
BT.Enable
Else
BTConnectToDevice
End If
Catch
ToastMessageShow("No BlueTooth Device Connect ...", False)
End Try
End Sub
Sub BT_StateChanged(NewState As Int,OldState As Int)
If NewState = BT.STATE_ON Then
BTConnectToDevice
Log("BT Connect")
Else
Serial1.Disconnect
timerBT.Enabled = False
Log("BT Disconnect")
End If
End Sub
Sub BTConnectToDevice
Try
'Serial1.Connect(MacAddress)
Serial1.Connect3(MacAddress,1)
Catch
ToastMessageShow("Device not available",False)
End Try
End Sub
Sub Serial1_Connected (Success As Boolean)
If Success = True Then
ToastMessageShow("Bluetooth connected to " & Serial1.Address, False)
AStreams.Initialize(Serial1.InputStream,Serial1.OutputStream,"AStream")
timerBT.Enabled = True
Else
ToastMessageShow("Connection to " & Serial1.Address & " broken!", False)
timerBT.Enabled = False
'Service_Destroy
End If
End Sub
Sub AStream_NewData (Buffer() As Byte)
Dim newDataStart As Int = sb.Length
sb.Append(BytesToString(Buffer, 0, Buffer.Length, charset))
Dim s As String = sb.ToString
Dim start As Int = 0
For i = newDataStart To s.Length - 1
Dim c As Char = s.CharAt(i)
If i = 0 And c = Chr(10) Then '\n...And
start = 1 'might be a broken end of line character
Continue
End If
If c = Chr(10) Then '\n
'CallSub2(Training,"ValoreGSR",s.SubString2(start, i))
'GSR=s.SubString2(start, i)
start = i + 1
Else If c = Chr(13) Then '\r
' CallSub2(Training,"GSROk",s.SubString2(start, i))
If start =0 And i=7 Then
IptMain.GSR=s.SubString2(start, i)
Log("Conduttanza " & IptMain.GSR)
End If
If i < s.Length - 1 And s.CharAt(i + 1) = Chr(10) Then '\r\n
i = i + 1
End If
start = i + 1
End If
Next
If start > 0 Then sb.Remove(0, start)
End Sub
Sub timerBT_Tick
'Communicte with the device here
'if the device answers, fine
'if there is no response, communication might be lost
'Stop the timer and you should call BTConnectToDevice again
End Sub
Sub Service_Destroy
StopService(Me)
End Sub