// This method is run when the mainboard is powered up or reset. void ProgramStarted() { _bluetooth = new Bluetooth(4); _bluetooth.DebugPrintEnabled = true; _client = _bluetooth.ClientMode; _bluetooth.SetDeviceName("Gadgeteer"); _bluetooth.SetPinCode("1234"); _bluetooth.DataReceived += bluetooth_DataReceived; button.ButtonPressed += (sender, state) => _client.EnterPairingMode(); var monitor = new GT.Timer(500); monitor.Tick += timer => { if (_bluetooth.IsConnected) { //_client.Send("xxx"); } }; monitor.Start(); // Use Debug.Print to show messages in Visual Studio's "Output" window during debugging. Debug.Print("Program Started"); var sensePuss = new GT.Timer(1000); sensePuss.Tick += timer => { relays.Relay3 = moistureSensor.GetMoistureReading() > 500; Debug.Print(moistureSensor.GetMoistureReading().ToString()); }; sensePuss.Start(); }
private AndroidJavaObject _activityObject;//AndroidJavaObject Object public static Bluetooth Instance()//Constractor { if (Instance_obj == null) { Instance_obj = new Bluetooth(); Instance_obj.PluginStart(); } return Instance_obj; }
public void InitBluetooth() { #if UNITY_EDITOR #elif UNITY_ANDROID Bluetooth = Bluetooth.Instance; #endif }
public MainWindow() { InitializeComponent(); bluetoothObj = new Bluetooth(Properties.Settings.Default.applicationGuid, this); bluetoothObj.Init(); workerNetwork.DoWork += new DoWorkEventHandler(WorkerNetwork_DoWork); }
/* public void SendCommand(string command) { if (_bluetoothStream != null) { var buffer = System.Text.Encoding.Default.GetBytes(command); _bluetoothStream.Write(buffer, 0, buffer.Length); } } */ private void bluetooth_DataReceived(Bluetooth sender, string data) { switch (data.ToUpper()) { case "A": break; default: break; } }
private async Task <bool> OpenBluetooth(string name, string address, bool isTest) { //oBluetooth = null; //oBluetooth = new Bluetooth(true, isTest); // Create connection object if (!oUserSettings.GetIsTestMode()) { if (!Bluetooth.CheckAdapterPresent()) // Check if bluetooth is available on this device: display message and return on failure { ProcessConnectionError(ERROR_TYPE.ADAPTER_ERROR); return(false); } if (!Bluetooth.CheckAdapterEnabled()) // Check if bluetooth is enabled on this device: display message and return on failure { ProcessConnectionError(ERROR_TYPE.ADAPTER_DISABLED); return(false); } if (!oBluetooth.LoadPairedDevices()) // Attempt to load paired devices: display message and return on failure { ProcessConnectionError(ERROR_TYPE.PAIR_ERROR); return(false); } if (!oBluetooth.CheckPairedDevices()) // Check if there are paired devices available: display message and return on failure { ProcessConnectionError(ERROR_TYPE.PAIR_NONE); return(false); } if (!await oBluetooth.OpenPairedDevice(name, address, true)) // Attempt to open paired device: if failed get list of paired devices { ProcessConnectionError(ERROR_TYPE.PAIR_FAILED); return(false); } } // Load commands and run processing loop oBlueToothCmds = null; oBlueToothCmds = new BlueToothCmds(); // ToDo: replace with db values //oBlueToothCmds.CreateTestCommands(oUserSetting.GetUserUnits(), true); oBlueToothCmds.RetrieveCommands(oUserSettings.GetUserUnits(), true); InitCommands(oBlueToothCmds); InitListViewItems(oBlueToothCmds); RunProcesses(); return(true); }
/// <summary> /// Obsługa zdarzenia kliknięcia w przycisk wyłącznika. Obsługa polega na wyświetleniu użytkownikowi prośby o potwierdzenie /// wysłania komendy. W przypadku, gdy odpowiedź użytkownika jest pozytywna do robota zostaje wysłany rozkaz deaktywacji /// oraz wywoływane są następujące metody: kończąca połączenie Bluetooth i (poprzez globalną zmienną referencji /// do strony głównej) obsługująca zdarzenie wysłania komendy deaktywacji. /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private async void ButtonGoInitialPos_Click(object sender, RoutedEventArgs e) { var result = await PopUp.ShowChoice(StringConsts.DeactivateRobotDialogText, StringConsts.DeactivateRobotDialogTitle, StringConsts.Yes, StringConsts.No); if (!result) { return; } await Bluetooth.SendByte((byte)RobotCommand.GoToInitialPos); Bluetooth.Disconnect(); App.MainPage.HandleRobotDeactivation(); }
void bluetooth_BluetoothStateChanged(Bluetooth sender, Bluetooth.BluetoothState btState) { // If the state is now "connected", we can do stuff over the link. if (btState == Bluetooth.BluetoothState.Connected) { Debug.Print("Connected"); } // if the state is now "disconnected", you might need to stop other processes but for this example we'll just confirm that in the debug output window if (btState == Bluetooth.BluetoothState.Disconnected) { Debug.Print("Disconnected"); } }
void Start() { blue = GameObject.Find("carRoot").GetComponent <Bluetooth>(); leftHand = GameObject.Find("leftHand"); rightHand = GameObject.Find("rightHand"); initPos = (rightHand.transform.position + leftHand.transform.position) / 2; rightOffset = new float[] { 82, 70, 0 }; leftOffset = new float[] { 70, 355, 0 }; rightTranslate = new float[] { 0, 0 }; leftTranslate = new float[] { 0, 0 }; buttons = new float[] { 0, 0, 0, 0, 0, 0 }; indicator = GameObject.Find("bar").GetComponent <Image>(); }
public IActionResult Put([FromBody] Bluetooth bluetooth) { if (bluetooth != null) { using (var scope = new TransactionScope()) { _bluetoothRepository.UpdateBluetooth(bluetooth); scope.Complete(); return(new OkResult()); } } return(new NoContentResult()); }
private async void AddSwitchTileButton_Click(object sender, RoutedEventArgs e) { try { var enabled = await Bluetooth.SendBluetooth(TetheringState.GetState) == TetheringState.Enabled; await Tile.AddSwitchTile((FrameworkElement)sender, enabled); } catch (Exception) { await Tile.AddSwitchTile((FrameworkElement)sender, false); } }
/// <summary> /// The worker will try to connect to the specified device and create a listener for /// the Bluetooth port messages. /// This must be canned async in a separate thread! /// </summary> public async void Work(BluetoothDevice btDevice) { try { Boolean success = await Bluetooth.connectToDeviceWithoutPairing(btDevice); if (success) { await BluetoothStreamListener(btDevice); } } catch (Exception e) { Console.WriteLine(e.ToString()); } }
private void Awake() { gameManager = FindObjectOfType <GameManager>(); bluetooth = FindObjectOfType <Bluetooth>(); //renderer to read the color spRenderer = GetComponent <Image>(); texture = spRenderer.sprite.texture; dataRGB = texture.GetPixels(); brightnessSlider.maxValue = 255; brightnessSlider.minValue = 0; brightnessSlider.value = 255; }
public void Save(JObject obj) { string type = obj.Properties().ElementAt(0).Name; JObject data = (JObject)obj[type]; Bluetooth bt = data.ToObject <Bluetooth>(); Bluetooth bluetooth = bluetoothRepository.GetBluetoothById(bt.Id); if (bluetooth == null) { bluetoothRepository.InsertBluetooth(bt); } }
void Awake() { // This is a SingleTON of stuff if (instance != null && instance != this) { Destroy(gameObject); return; } instance = this; DontDestroyOnLoad(gameObject); SceneManager.activeSceneChanged += ActiveSceneChanged; bt = Bluetooth.GetInstance(); }
public void Visible_CheckedChanged(bool _checked) { if (_checked) { //Making the device discoverable view.Navigate(Constants.DISCOVERY_REQUEST, new Intent(BluetoothAdapter.ActionRequestDiscoverable)); Bluetooth.StartAcceptThread(thisPhone); } else { Bluetooth.StopAcceptThread(); } }
// //public Bluetooth() { } // // constructor initializes serial comm and reads (as own thread) until broken public void InitSerialPort(Bluetooth btooth, string port, int baudrate) { // //PortName = "COM7"; // PortNameMac = "dev/cu.HC-05-DevB"; //PortName = "dev/cu.HC-05-DevB" // Set in Windows Settings->Bluetooth->More Bluetooth Settings->COM Ports (OUTGOING) // create a new serial port listener with given baud rate on given windows port SerialPort serialPort = new SerialPort { //BaudRate = 9600, BaudRate = baudrate, PortName = port //PortName = "/dev/cu.DSDTECHHC-05-DevB" // Set in Windows Settings->Bluetooth->More Bluetooth Settings->COM Ports (OUTGOING) //PortName = "dev/cu.HC-05-DevB" // Set in Windows Settings->Bluetooth->More Bluetooth Settings->COM Ports (OUTGOING) }; serialPort.Open(); // print counter to terminal to troubleshoot //int counter = 0; // POST to server //var postVitals = new BlueTelemetryModel //{ //heartrate = counter, //oxygen = 60.0, //temperature = 70.0 //}; //_ = PostJsonHttpClient(postVitals); // while a serial port connection exists while (serialPort.IsOpen) { // if serial port contains data, extract while (serialPort.BytesToRead > 0) { Console.Write(Convert.ToChar(serialPort.ReadChar())); } // send to arduino through bluetooth comm //serialPort.WriteLine("PC counter: " + (counter++)); // update ctr //counter++; // check serial port connection and buffer for data every second Thread.Sleep(1000); // if serial port closes, break loop } }
public void PopulatePairedDeviceList() { Bluetooth bt = new Bluetooth(); if (bt.AdapterEnabled) { List <string> pairedDevices = bt.PairedDeviceNames; Assert.IsNotNull(pairedDevices); } else { Assert.IsTrue(true, "Adapter not turned on"); } }
public void CreateBluetothWhenTurnedOff() { //To have this test pass, bluetooth must be turned off. Bluetooth bt = new Bluetooth(); List <string> strings = bt.PairedDeviceNames; if (!bt.AdapterEnabled) { Assert.IsTrue(strings.Count <= 0); } else { Assert.IsTrue(true, "Adapter is turned on"); } }
/// <summary> /// Event when the search find new device /// </summary> /// <param name="Device"></param> void FoundDeviceEvent(string Device) { // split up data string[] data = Device.Split(new string[] { ",\n" }, StringSplitOptions.None); if (data[0] == "null") { return; // Bug in bluetooth plugin } Bluetooth.Instance().MacAddresses.Add(Device); // Add to list in bluetooth // Create new GUI for device GameObject newPanel = Instantiate(foundDevicePanel, ServerViewContent.transform, false); newPanel.GetComponent <FoundDevicePanel>().SetNameAndMac(data[0], data[1], Device); }
/// <summary> /// Obsługuje zdarzenie kliknięcia w przycisk 'Wyjdź'. Obsługa polega na sprawdzeniu czy istnieje połączenie z urządzeniem Bluetooth. /// Zależnie od wyniku sprawdzenia wyświetlane jest odpowiednie pytanie. W przypadku, gdy wynik sprawdzenia jest pozytywny i użytkownik /// potwierdził zamknięcie aplikacji wywoływana jest metoda rozłączająca połączenie Bluetooth. /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private async void ButtonExit_Click(object sender, RoutedEventArgs e) { bool btConnected = Bluetooth.IsConnected; bool result = await PopUp.ShowChoice(btConnected?StringConsts.ExitDialogTextWithBt : StringConsts.ExitDialogText, StringConsts.ExitDialogTitle, StringConsts.Yes, StringConsts.No); if (!result) { return; } if (btConnected) { Bluetooth.Disconnect(); } Application.Current.Exit(); }
void Awake() { GameObject[] objs = GameObject.FindGameObjectsWithTag("Bluetooth"); if (objs.Length > 1) { GameObject.Find("Canvas/SettingsMenu").SetActive(false); DestroyImmediate(this.gameObject); } else { bluetooth = new Bluetooth(); bluetooth.ServerObject = "BluetoothService"; DontDestroyOnLoad(this.gameObject); } }
/// <summary>Populate the list view of bluetooth devices</summary> private void PopulateDevices() { var devices = Bluetooth.Devices(ShowDevices).ToList(); var curr = m_lb_devices.DataSource as List <Bluetooth.Device>; // Update the list of devices if (curr == null || !curr.SequenceEqual(devices, Cmp <Bluetooth.Device> .From((l, r) => l.Name.CompareTo(r.Name)))) { m_lb_devices.DataSource = devices; // Select the same device again var name = Device?.Name; Device = devices.FirstOrDefault(x => x.Name == name); } }
/// <summary> /// Enumerate Bluetooth devices /// </summary> /// <returns>Array of <see cref="BluetoothDeviceInfo"/> objects.</returns> public static BluetoothDeviceInfo[] EnumBluetoothDevices() { var lOut = new List <BluetoothDeviceInfo>(); var bth = Bluetooth._internalEnumBluetoothDevices(); var p = _internalEnumerateDevices <BluetoothDeviceInfo>(DevProp.GUID_DEVCLASS_BLUETOOTH, ClassDevFlags.Present); if (p != null && p.Length > 0) { foreach (var x in p) { foreach (var y in bth) { int i = x.InstanceId.LastIndexOf("_"); if (i > -1) { string s = x.InstanceId.Substring(i + 1); ulong res; bool b = ulong.TryParse(s, System.Globalization.NumberStyles.AllowHexSpecifier, System.Globalization.CultureInfo.CurrentCulture, out res); if (b) { if (res == (ulong)y.Address) { x.IsRadio = false; x.BluetoothAddress = y.Address; x.BluetoothDeviceClass = y.ulClassofDevice; lOut.Add(x); break; } } } } } } return(lOut.ToArray()); //Array.Sort(p, new Comparison<DeviceInfo>((x, y) => { if (x.FriendlyName is object && y.FriendlyName is object) { return string.Compare(x.FriendlyName, y.FriendlyName); } else { return string.Compare(x.Description, y.Description); } })); //return p; }
public override void ClickedAt(Vector2 clickPos) { if (IsPointerOverUIObject()) return; // We are on client side if (gameLogic == null) { int[] pos = Grid.GetCellInGridPos(clickPos); // It's going to check whether it is server's or client's turn (on the server side) Bluetooth.Instance().Send(BluetoothMessageStrings.TRY_PLACE_AT + "#" + pos[0].ToString() + "#" + pos[1].ToString()); } else { // We are server side if (((BluetoothTTTGameLogic) gameLogic).IsItServersTurn()) ((BluetoothTTTGameLogic) gameLogic).WantToPlaceAt(clickPos); } }
private bool CheckBluetooth() { if (!Bluetooth.CheckAdapterPresent()) // Check if bluetooth is available on this device: display message and return on failure { DisplayMessage(Bluetooth.GetStatusMessage()); return(false); } if (!Bluetooth.CheckAdapterEnabled()) // Check if bluetooth is enabled on this device: display message and return on failure { // ToDo: open OS settings page? DisplayMessage(Bluetooth.GetStatusMessage()); return(false); } return(true); }
private async void Page_Loaded(object sender, RoutedEventArgs e) { try { var result = await Radio.RequestAccessAsync(); var newstate = await Bluetooth.SendBluetooth(TetheringState.GetState); connected = newstate == TetheringState.Enabled; } catch (Exception) { } UpdateButton(); }
private async void OpenConnection() { btnConnect.IsEnabled = false; isConnect = true; if (!await OpenBluetooth(oUserSettings.GetDeviceName(), oUserSettings.GetDeviceAddress(), oUserSettings.GetIsTestMode())) { btnConnect.IsEnabled = true; } else { Bluetooth.SetBluetoothState(Bluetooth.BLUETOOTH_STATE.CONNECTED); UpdateControls(); } isConnect = false; }
public static async void rescanDevices() { scanning = true; var cl1 = await Bluetooth.GetPairedDevicesAsync(); pairedDevices = new BluetoothDevice[cl1.Count]; pairdDevicesNames = new string[cl1.Count]; var i = 0; foreach (var dev in cl1) { pairedDevices[i] = dev; pairdDevicesNames[i] = dev.Name; i++; } scanning = false; }
/// <summary> /// Enumerate Bluetooth Radios /// </summary> /// <returns>Array of <see cref="BluetoothDeviceInfo"/> objects.</returns> public static BluetoothDeviceInfo[] EnumBluetoothRadios() { var bth = Bluetooth._internalEnumBluetoothRadios(); var p = _internalEnumerateDevices <BluetoothDeviceInfo>(Bluetooth.GUID_BTHPORT_DEVICE_INTERFACE, ClassDevFlags.DeviceInterface | ClassDevFlags.Present); if (p is object && p.Count() > 0) { foreach (var x in p) { foreach (var y in bth) { int i = x.InstanceId.LastIndexOf(@"\"); if (i > -1) { string s = x.InstanceId.Substring(i + 1); ulong res; bool b = ulong.TryParse(s, System.Globalization.NumberStyles.AllowHexSpecifier, System.Globalization.CultureInfo.CurrentCulture, out res); if (b) { if (res == (ulong)(y.address)) { x.IsRadio = true; x.BluetoothAddress = y.address; x.BluetoothDeviceClass = y.ulClassofDevice; break; } } } } } } if (p is null) { return(null); } Array.Sort(p, new Comparison <DeviceInfo>((x, y) => { if (x.FriendlyName is object && y.FriendlyName is object) { return(string.Compare(x.FriendlyName, y.FriendlyName)); } else { return(string.Compare(x.Description, y.Description)); } })); return(p); }
public static Bluetooth GetInstance() { if (instance == null) { instance = new Bluetooth(); try { instance.PluginStart(); instance.Discoverable(); connectedToAndroid = true; } catch (Exception e) { Debug.LogWarning("WARNING: Android environment not found! If it's supposed to (i.e. not testing/debugging), something terrible happened!"); Debug.LogWarning(e); connectedToAndroid = false; } } return(instance); }
public PulsationAnalyzePage() { InitializeComponent(); Bluetooth = DependencyService.Get <Bluetooth>(); #if DEBUG _impulseInvoker = new MockImpulseInvoker(); #endif _vm = new DeviceDataViewModel(); _ddp = DeviceDataProvider.GetProvider; _timer = new StoppableTimer(TimeSpan.FromMilliseconds(Constants.UPDATE_INTERVAL), TimerTick); FirstChanelSeries.ItemsSource = _vm.FirstChanelSeriesData; SecondChanelSeries.ItemsSource = _vm.SecondChanelSeriesData; _jsonKeeper = new JsonDataKeeper <DeviceDataViewModel>(); }
public override void InitDialog(DataBundle datas = null) { var listener = Bluetooth.GetBluetoothListener(); listener.OnFoundDeviceDelegate = delegate(BluetoothDevice device) { lock (devicesLock) { newDevices.Enqueue(device); } }; listener.OnGetSocketConnectDelegate = delegate { closeFlag = true; }; ScanBondedDevices(); Bluetooth.StartDiscovery(); }
/// <summary> /// Returns a list of properties of all connected devices, separated by special character: "|" /// </summary> /// <returns> /// Return format: Name | Address | DeviceType | DeviceConnected /// </returns> public List <string> GetConnectedDevices() { List <string> connectedDevices = new List <string>(); foreach (VPort port in allPortsList) { //get name and address from port string name = port.GetInfo().GetFriendlyName(); string addr = getDeviceAddressFromPort(port); BluetoothDevice bd = Bluetooth.getDeviceByAddress(addr, false); //get device type and connected from Bluetooth Wrapper string deviceType = bd.DeviceType; bool deviceConnected = bd.Connected; connectedDevices.Add(name + "|" + addr + "|" + deviceType + "|" + deviceConnected); } return(connectedDevices); }
/// <summary> /// Start searching for potential clients /// </summary> public void StartSearching() { // Only do it for servers if (!isServer) { return; } // Remove every shown device first foreach (Transform t in ServerViewContent.transform) { Destroy(t.gameObject); } Debug.Log("Is server discoverable " + Bluetooth.Instance().Discoverable()); Bluetooth.Instance().SearchDevice(); GameObject.Find("LoadImage").GetComponent <LoadImage>().StartLoading(); }
public BluetoothConnector(SXML.Receiver receiver, Bluetooth.BluetoothController[] bluetoothControllers, HousenCS.MITes.MITesDecoder[] mitesDecoders) { this.receiver = receiver; this.bluetoothControllers = bluetoothControllers; this.mitesDecoders = mitesDecoders; // TODO At some point close this properly if (!Directory.Exists("\\Wockets")) Directory.CreateDirectory("\\Wockets"); try { this.log = new StreamWriter("\\Wockets\\log-" + receiver.ID + ".txt", true); } catch (IOException e) { // If an exception is thrown, then make sure we don't crash. NIH demo only. // TODO remove and fix more elegantly this.log = new StreamWriter("\\Wockets\\log-" + receiver.ID + "-" + Environment.TickCount + ".txt", true); } }
/// <summary> /// Raises the <see cref="DataReceived"/> event. /// </summary> /// <param name="sender">The object that raised the event.</param> /// <param name="data">Data string received by the Bluetooth module</param> protected virtual void OnDataReceived(Bluetooth sender, string data) { if (onDataReceived == null) onDataReceived = new DataReceivedHandler(OnDataReceived); if (Program.CheckAndInvoke(DataReceived, onDataReceived, sender, data)) { DataReceived(sender, data); } }
private void OnBluetoothStateChanged(Bluetooth sender, Bluetooth.BluetoothState btState) { Debug.Print("SolarPulse - Bluetooth state changed - State: \"" + btState + "\"."); switch (btState) { case Bluetooth.BluetoothState.Connected: this.ShowMaintenanceScreen(); break; default: if (previousBluetoothState == Bluetooth.BluetoothState.Connected) { this.ShowMainScreen(); } break; } this.previousBluetoothState = btState; }
/// <summary> /// Raises the <see cref="PinRequested"/> event. /// </summary> /// <param name="sender">The object that raised the event.</param> /// <param name="macAddress">MAC Address of the inquired device</param> /// <param name="name">Name of the inquired device</param> protected virtual void OnDeviceInquired(Bluetooth sender, string macAddress, string name) { if (onDeviceInquired == null) onDeviceInquired = new DeviceInquiredHandler(OnDeviceInquired); if (Program.CheckAndInvoke(DeviceInquired, onDeviceInquired, sender, macAddress, name)) { DeviceInquired(sender, macAddress, name); } }
/// <summary> /// Raises the <see cref="PinRequested"/> event. /// </summary> /// <param name="sender">The object that raised the event.</param> protected virtual void OnPinRequested(Bluetooth sender) { if (onPinRequested == null) onPinRequested = new PinRequestedHandler(OnPinRequested); if (Program.CheckAndInvoke(PinRequested, onPinRequested, sender)) { PinRequested(sender); } }
internal Client(Bluetooth bluetooth) { Debug.Print("Client Mode"); this.bluetooth = bluetooth; bluetooth.serialPort.Write("\r\n+STWMOD=0\r\n"); }
internal Host(Bluetooth bluetooth) { Debug.Print("Host mode"); this.bluetooth = bluetooth; bluetooth.serialPort.Write("\r\n+STWMOD=1\r\n"); }
public void Connect () { var device = MonoBrick.Bluetooth<MonoBrick.EV3.Command, MonoBrick.EV3.Reply>.GetBondDevice("youDeviceName"); var connection = new Bluetooth<MonoBrick.EV3.Command, MonoBrick.EV3.Reply>(device); var brick = new MonoBrick.EV3.Brick<MonoBrick.EV3.Sensor,MonoBrick.EV3.Sensor,MonoBrick.EV3.Sensor,MonoBrick.EV3.Sensor>(connection); brick.Connection.Open(); }
private void OnBluetoothDataReceived(Bluetooth sender, string data) { Debug.Print("SolarPulse - Bluetooth data received - Data: \"" + data + "\"."); }
private void c_OnConnected(Bluetooth.Connection connection, DateTime Timestamp) { SendScenes(); }
/// <summary> /// Raises the <see cref="BluetoothStateChanged"/> event. /// </summary> /// <param name="sender">The object that raised the event.</param> /// <param name="btState">Current state of the Bluetooth module</param> protected virtual void OnBluetoothStateChanged(Bluetooth sender, BluetoothState btState) { if (onBluetoothStateChanged == null) onBluetoothStateChanged = new BluetoothStateChangedHandler(OnBluetoothStateChanged); if (Program.CheckAndInvoke(BluetoothStateChanged, onBluetoothStateChanged, sender, btState)) { BluetoothStateChanged(sender, btState); } }