manager.cs 5.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194
  1. using System.Collections;
  2. using System.Collections.Generic;
  3. using UnityEngine;
  4. using UnityEngine.UI;
  5. using ArduinoBluetoothAPI;
  6. using System;
  7. using System.Text;
  8. public class manager : MonoBehaviour {
  9. // Use this for initialization
  10. BluetoothHelper bluetoothHelper;
  11. string deviceName;
  12. public Text text;
  13. public GameObject sphere;
  14. string received_message;
  15. void Start () {
  16. deviceName = "HC-05"; //bluetooth should be turned ON;
  17. try
  18. {
  19. bluetoothHelper = BluetoothHelper.GetInstance(deviceName);
  20. bluetoothHelper.OnConnected += OnConnected;
  21. bluetoothHelper.OnConnectionFailed += OnConnectionFailed;
  22. bluetoothHelper.OnDataReceived += OnMessageReceived; //read the data
  23. //bluetoothHelper.setFixedLengthBasedStream(3); //receiving every 3 characters together
  24. bluetoothHelper.setTerminatorBasedStream("\n"); //delimits received messages based on \n char
  25. //if we received "Hi\nHow are you?"
  26. //then they are 2 messages : "Hi" and "How are you?"
  27. // bluetoothHelper.setLengthBasedStream();
  28. /*
  29. will received messages based on the length provided, this is useful in transfering binary data
  30. if we received this message (byte array) :
  31. {0x55, 0x55, 0, 3, 'a', 'b', 'c', 0x55, 0x55, 0, 9, 'i', ' ', 'a', 'm', ' ', 't', 'o', 'n', 'y'}
  32. then its parsed as 2 messages : "abc" and "i am tony"
  33. the first 2 bytes are the length data writted on 2 bytes
  34. byte[0] is the MSB
  35. byte[1] is the LSB
  36. on the unity side, you dont have to add the message length implementation.
  37. if you call bluetoothHelper.SendData("HELLO");
  38. this API will send automatically :
  39. 0x55 0x55 0x00 0x05 0x68 0x65 0x6C 0x6C 0x6F
  40. |________| |________| |________________________|
  41. preamble Length Data
  42. when sending data from the arduino to the bluetooth, there's no preamble added.
  43. this preamble is used to that you receive valid data if you connect to your arduino and its already send data.
  44. so you will not receive
  45. on the arduino side you can decode the message by this code snippet:
  46. char * data;
  47. char _length[2];
  48. int length;
  49. if(Serial.avalaible() >2 )
  50. {
  51. _length[0] = Serial.read();
  52. _length[1] = Serial.read();
  53. length = (_length[0] << 8) & 0xFF00 | _length[1] & 0xFF00;
  54. data = new char[length];
  55. int i=0;
  56. while(i<length)
  57. {
  58. if(Serial.available() == 0)
  59. continue;
  60. data[i++] = Serial.read();
  61. }
  62. ...process received data...
  63. delete [] data; <--dont forget to clear the dynamic allocation!!!
  64. }
  65. */
  66. LinkedList<BluetoothDevice> ds = bluetoothHelper.getPairedDevicesList();
  67. foreach(BluetoothDevice d in ds)
  68. {
  69. Debug.Log($"{d.DeviceName} {d.DeviceAddress}");
  70. }
  71. //Debug.Log(ds);
  72. // if(bluetoothHelper.isDevicePaired())
  73. // sphere.GetComponent<Renderer>().material.color = Color.blue;
  74. // else
  75. // sphere.GetComponent<Renderer>().material.color = Color.grey;
  76. }
  77. catch (Exception ex)
  78. {
  79. sphere.GetComponent<Renderer>().material.color = Color.yellow;
  80. Debug.Log (ex.Message);
  81. text.text = ex.Message;
  82. //BlueToothNotEnabledException == bluetooth Not turned ON
  83. //BlueToothNotSupportedException == device doesn't support bluetooth
  84. //BlueToothNotReadyException == the device name you chose is not paired with your android or you are not connected to the bluetooth device;
  85. // bluetoothHelper.Connect () returned false;
  86. }
  87. }
  88. IEnumerator blinkSphere()
  89. {
  90. sphere.GetComponent<Renderer>().material.color = Color.cyan;
  91. yield return new WaitForSeconds(0.5f);
  92. sphere.GetComponent<Renderer>().material.color = Color.green;
  93. }
  94. // Update is called once per frame
  95. void Update () {
  96. /*
  97. //Synchronous method to receive messages
  98. if(bluetoothHelper != null)
  99. if (bluetoothHelper.Available)
  100. received_message = bluetoothHelper.Read ();
  101. */
  102. }
  103. //Asynchronous method to receive messages
  104. void OnMessageReceived(BluetoothHelper helper)
  105. {
  106. //StartCoroutine(blinkSphere());
  107. received_message = helper.Read();
  108. Debug.Log(received_message);
  109. text.text = received_message;
  110. // Debug.Log(received_message);
  111. }
  112. void OnConnected(BluetoothHelper helper)
  113. {
  114. sphere.GetComponent<Renderer>().material.color = Color.green;
  115. try{
  116. helper.StartListening ();
  117. }catch(Exception ex){
  118. Debug.Log(ex.Message);
  119. }
  120. }
  121. void OnConnectionFailed(BluetoothHelper helper)
  122. {
  123. sphere.GetComponent<Renderer>().material.color = Color.red;
  124. Debug.Log("Connection Failed");
  125. }
  126. //Call this function to emulate message receiving from bluetooth while debugging on your PC.
  127. void OnGUI()
  128. {
  129. if(bluetoothHelper!=null)
  130. bluetoothHelper.DrawGUI();
  131. else
  132. return;
  133. if(!bluetoothHelper.isConnected())
  134. if(GUI.Button(new Rect(Screen.width/2-Screen.width/10, Screen.height/10, Screen.width/5, Screen.height/10), "Connect"))
  135. {
  136. if(bluetoothHelper.isDevicePaired())
  137. bluetoothHelper.Connect (); // tries to connect
  138. else
  139. sphere.GetComponent<Renderer>().material.color = Color.magenta;
  140. }
  141. if(bluetoothHelper.isConnected())
  142. if(GUI.Button(new Rect(Screen.width/2-Screen.width/10, Screen.height - 2*Screen.height/10, Screen.width/5, Screen.height/10), "Disconnect"))
  143. {
  144. bluetoothHelper.Disconnect ();
  145. sphere.GetComponent<Renderer>().material.color = Color.blue;
  146. }
  147. if(bluetoothHelper.isConnected())
  148. if(GUI.Button(new Rect(Screen.width/2-Screen.width/10, Screen.height/10, Screen.width/5, Screen.height/10), "Send text"))
  149. {
  150. bluetoothHelper.SendData(new Byte[] {0, 0, 85, 0, 85});
  151. // bluetoothHelper.SendData("This is a very long long long long text");
  152. }
  153. }
  154. void OnDestroy()
  155. {
  156. if(bluetoothHelper!=null)
  157. bluetoothHelper.Disconnect ();
  158. }
  159. }