/// <summary> /// NOT FINISHED /// </summary> /// <param name="timeout"></param> /// <returns></returns> public static BluetoothDeviceInfo[] DiscoverDevices(TimeSpan timeout) { BluetoothDeviceInfo[] devices; using (var @event = new ManualResetEvent(false)) { devices = null; var comp = new BluetoothComponent(); EventHandler <DiscoverDevicesEventArgs> progress = (unused, args) => { devices = args.Devices; }; EventHandler <DiscoverDevicesEventArgs> completed = (unused, args) => { devices = args.Devices; @event.Set(); }; comp.DiscoverDevicesProgress += progress; comp.DiscoverDevicesComplete += completed; try { comp.DiscoverDevicesAsync(10, true, true, true, false, null); if ([email protected](timeout)) { return(new BluetoothDeviceInfo[0]); } } finally { comp.DiscoverDevicesProgress -= progress; comp.DiscoverDevicesComplete -= completed; } } return(devices); }
private void StartDiscovery() { BluetoothClient bc = new BluetoothClient(); BluetoothDeviceInfo[] devicesR; if (fShowAuthenticated || fShowRemembered) { devicesR = bc.DiscoverDevices(255, fShowAuthenticated, fShowRemembered, false, fDiscoverableOnly); } else { devicesR = new BluetoothDeviceInfo[0]; } UpdateProgressChanged(null, new DiscoverDevicesEventArgs(devicesR, null)); // if (fShowUnknown || fDiscoverableOnly) { var bco = new BluetoothComponent(bc); bco.DiscoverDevicesAsync(255, false, false, true, fDiscoverableOnly, bco); bco.DiscoverDevicesProgress += bco_DiscoverDevicesProgress; bco.DiscoverDevicesComplete += bco_DiscoverDevicesComplete; } else { UpdateCompleted(null, new DiscoverDevicesEventArgs(new BluetoothDeviceInfo[0], null)); } }
/// <summary> /// Initializes the Bluetooth connection process /// </summary> private static void InitBTConnection() { localClient = new BluetoothClient(); localComponent = new BluetoothComponent(localClient); // Setup event handlers localComponent.DiscoverDevicesProgress += new EventHandler <DiscoverDevicesEventArgs>(DiscoverDevices); localComponent.DiscoverDevicesComplete += new EventHandler <DiscoverDevicesEventArgs>(DiscoverDevicesComplete); // Get previously paired devices BluetoothDeviceInfo[] pairedDevices = localClient.DiscoverDevices(255, false, true, false, false); // Check if specified Shimmer is already paired List <BluetoothDeviceInfo> pairedDevicesList = pairedDevices.OfType <BluetoothDeviceInfo>().ToList(); BluetoothDeviceInfo pairedDevice = pairedDevicesList.Find(item => item.DeviceName.Equals("Shimmer3-" + SHIMMER_ID)); // If the device is not paired begin the discovery process if (pairedDevice == null) { localComponent.DiscoverDevicesAsync(255, true, true, true, true, null); //Console.WriteLine("Shimmer3-" + SHIMMER_ID + " not paired -> Begin discovery"); } // If the device is already paired begin the connection process else { // set pin of device to connect with localClient.SetPin(SHIMMER_PIN); // async connection method localClient.BeginConnect(pairedDevice.DeviceAddress, BluetoothService.SerialPort, new AsyncCallback(Connected_Callback), pairedDevice); //Console.WriteLine("Shimmer3-" + SHIMMER_ID + " already paired -> Begin connect"); } }
static void Main(string[] args) { try { displayBluetoothRadio(); _bluetoothEvents = BluetoothWin32Events.GetInstance(); _bluetoothEvents.InRange += onInRange; _bluetoothEvents.OutOfRange += onOutOfRange; using (BluetoothClient client = new BluetoothClient()) { BluetoothComponent component = new BluetoothComponent(client); component.DiscoverDevicesProgress += onDiscoverDevicesProgress; component.DiscoverDevicesComplete += onDiscoverDevicesComplete; component.DiscoverDevicesAsync(255, true, false, false, false, null); //BluetoothDeviceInfo[] peers = client.DiscoverDevices(); //device = peers.ToList().Where(p => p.DeviceName == DEVICE_NAME).FirstOrDefault(); } } catch (Exception ex) { Console.WriteLine(ex.Message); } finally { Console.ReadKey(); } }
private static void ScanForDevices() { Console.WriteLine("Begin connection."); bluetoothClient = new BluetoothClient(); BluetoothComponent bluetoothComponent = new BluetoothComponent(bluetoothClient); bluetoothComponent.DiscoverDevicesProgress += new EventHandler <DiscoverDevicesEventArgs>(connectionProgress); bluetoothComponent.DiscoverDevicesComplete += new EventHandler <DiscoverDevicesEventArgs>(discoveryComplete); bluetoothComponent.DiscoverDevicesAsync(255, true, true, true, true, null); Console.WriteLine("Device discover began."); void connectionProgress(object sender, DiscoverDevicesEventArgs e) { for (int i = 0; i < e.Devices.Length; i++) { Console.WriteLine("Found device: " + e.Devices[i].DeviceName + " with address " + e.Devices[i].DeviceAddress); deviceList.Add(e.Devices[i]); } } void discoveryComplete(object sender, DiscoverDevicesEventArgs e) { Console.WriteLine("Device discovery completed."); RequestConnection(); } }
public ConnectionManager(bool BluetoothOn, SpeechSynthesizer Reader, SpeechInteraction speechInteraction) { this.BluetoothOn = BluetoothOn; this.Reader = Reader; this.speechInteraction = speechInteraction; if (BluetoothOn) { if (BluetoothRadio.PrimaryRadio.Mode == RadioMode.Discoverable) { thisDevice = new BluetoothClient(); BluetoothComponent bluetoothComponent = new BluetoothComponent(thisDevice); bluetoothComponent.DiscoverDevicesProgress += bluetoothComponent_DiscoverDevicesProgress; bluetoothComponent.DiscoverDevicesComplete += bluetoothComponent_DiscoverDevicesComplete; bluetoothComponent.DiscoverDevicesAsync(8, true, true, true, false, thisDevice); Console.WriteLine("Connectable"); } else { Reader.Speak("Please turn on your Bluetooth adapter"); } } else { asyncClient = new AsynchronousClient(speechInteraction); InitAsyncTCPClient(); } }
public void connectToGLove() { blueComponent = new BluetoothComponent(client); Console.WriteLine("Discover All Devices"); blueComponent.DiscoverDevicesAsync(255, true, true, true, true, null); blueComponent.DiscoverDevicesProgress += new EventHandler <DiscoverDevicesEventArgs>(component_DiscoverDevicesProgress); blueComponent.DiscoverDevicesComplete += new EventHandler <DiscoverDevicesEventArgs>(component_DiscoverDevicesComplete); while (!discoverEnded) { ; } Console.WriteLine("Identifing GLove"); foreach (BluetoothDeviceInfo dev in deviceList) { if (dev.DeviceAddress == GLoveAddr) { GLove = dev; } } client.BeginConnect(GLove.DeviceAddress, BluetoothService.SerialPort, new AsyncCallback(Connect), GLove); stream = client.GetStream(); Console.WriteLine("Stream created"); }
public void DiscoDevicesAsync() { BluetoothComponent btComponent = new BluetoothComponent(); btComponent.DiscoverDevicesProgress += HandleDiscoDevicesProgress; btComponent.DiscoverDevicesComplete += HandleDiscoDevicesComplete; btComponent.DiscoverDevicesAsync(255, true, true, true, false, 99); }
public async Task GetBluetoothClients() { BluetoothClient client = new BluetoothClient(); if (InTheHand.Net.Bluetooth.BluetoothRadio.PrimaryRadio == null) { MessageBox.Show("Failed to discover Bluetooth devices", "Can't find Devices", MessageBoxButton.OK); return; } //client.BeginDiscoverDevices(10, false, false, true, true, null, null); if (localComponent != null) { localComponent.Dispose(); App.Current.Dispatcher.Invoke((Action) delegate { observableCollection.Clear(); latestsearch.Clear(); }); } localComponent = new BluetoothComponent(client); localComponent.DiscoverDevicesProgress += LocalComponent_DiscoverDevicesProgress; localComponent.DiscoverDevicesComplete += LocalComponent_DiscoverDevicesComplete; localComponent.DiscoverDevicesAsync(255, false, false, true, false, null); return; //return null; }
// Scan For Devices private static void ScanForDevices() { deviceList = new List <BluetoothDeviceInfo>(); localComponent = new BluetoothComponent(localclient); localComponent.DiscoverDevicesAsync(255, true, true, true, true, null); localComponent.DiscoverDevicesProgress += new EventHandler <DiscoverDevicesEventArgs>(ComponentDiscoverDevicesProgress); localComponent.DiscoverDevicesComplete += new EventHandler <DiscoverDevicesEventArgs>(ComponentDiscoverDevicesComplete); }
public void SearchDevices() { IsSearching = true; DiscoveredDeviceList.Clear(); localComponent.DiscoverDevicesProgress += new EventHandler <DiscoverDevicesEventArgs>(component_DiscoverDevicesProgress); localComponent.DiscoverDevicesComplete += new EventHandler <DiscoverDevicesEventArgs>(component_DiscoverDevicesComplete); localComponent.DiscoverDevicesAsync(255, true, true, true, true, null); }
// -------------------------------------------------------------------------- // METHODS // -------------------------------------------------------------------------- // Lance la recherche de périphériques bluetooth de façon asynchrone public void SearchDevicesAsync(EventHandler <DiscoverDevicesEventArgs> e1, EventHandler e2) { localComponent.DiscoverDevicesAsync(20, true, true, true, true, null); localComponent.DiscoverDevicesProgress += DiscoveryProgress; localComponent.DiscoverDevicesComplete += DiscoveryCompleted; deviceFound = e1; searchCompleted = e2; }
public void ScanBTDevice() { if (this.State == 0) { OnStartScanDevice?.Invoke(); this.timeBoxJoyList.RemoveAll(i => i.State == deviceState.DISCONNECT); this.State = 1; startScan = DateTime.Now; blueComponent.DiscoverDevicesAsync(30, true, true, true, true, null); } }
public void Search() { // component is used to manage device discovery BluetoothComponent localComponent = new BluetoothComponent(localClient); // async methods, can be done synchronously too localComponent.DiscoverDevicesProgress += new EventHandler <DiscoverDevicesEventArgs>(component_DiscoverDevicesProgress); localComponent.DiscoverDevicesComplete += new EventHandler <DiscoverDevicesEventArgs>(component_DiscoverDevicesComplete); localComponent.DiscoverDevicesAsync(255, true, true, true, true, null); }
static void Main(string[] args) { if (args.Length > 0) { _targetMachineName = args[0]; } // http://blogs.microsoft.co.il/shair/2009/06/21/working-with-bluetooth-devices-using-c-part-1/ //{ // BluetoothClient bc = new BluetoothClient(); // foreach (BluetoothDeviceInfo bdi in bc.DiscoverDevicesInRange()) // { // Console.WriteLine($"{bdi.DeviceName}"); // } // Console.WriteLine(); // foreach (BluetoothDeviceInfo bdi in bc.DiscoverDevices()) // { // Console.WriteLine($"{bdi.DeviceName}"); // } //} // https://stackoverflow.com/questions/42701793/how-to-programatically-pair-a-bluetooth-device { BluetoothClient bluetoothClient; BluetoothComponent bluetoothComponent; bluetoothClient = new BluetoothClient(); bluetoothComponent = new BluetoothComponent(bluetoothClient); bluetoothComponent.DiscoverDevicesProgress += bluetoothComponent_DiscoverDevicesProgress; bluetoothComponent.DiscoverDevicesComplete += bluetoothComponent_DiscoverDevicesComplete; bluetoothComponent.DiscoverDevicesAsync(255, false, true, true, false, null); } Console.WriteLine("Press any key to exit..."); Console.ReadLine(); // https://stackoverflow.com/questions/22346166/error-10049-while-connecting-bluetooth-device-with-32feet?rq=1 // if (false) { //{ // byte[] thisMacBytes = GetThisBTMacAddress().GetAddressBytes(); // BluetoothAddress ba = new BluetoothAddress(thisMacBytes); //} // BluetoothAddress targetMacAddress = BluetoothAddress.Parse("BEA5C3EF3F7D"); } }
public void Ebap_TwoWithSecondNameEvent() { TestInquiryBtIf btIf; BluetoothClient cli; // Create_BluetoothClient(out btIf, out cli); Assert.IsFalse(btIf.testDoCallbacksFromWithinStartInquiry, "tdcfwsi"); ThreadStart dlgt = delegate { bool signalled = btIf.startInquiryCalled.WaitOne(10000, false); Assert.IsTrue(signalled, "!signalled!!!!!"); btIf.InquiryEventsTwoWithSecondNameEvent(); }; IAsyncResult arDlgt = Delegate2.BeginInvoke(dlgt, null, null); // WidcommBluetoothClient.ReadKnownDeviceFromTheRegistry = false; var bc = new BluetoothComponent(cli); var devicesSteps = new List <BluetoothDeviceInfo[]>(); BluetoothDeviceInfo[] devicesResult = null; var complete = new ManualResetEvent(false); bc.DiscoverDevicesProgress += delegate(object sender, DiscoverDevicesEventArgs e) { devicesSteps.Add(e.Devices); }; bc.DiscoverDevicesComplete += delegate(object sender, DiscoverDevicesEventArgs e) { try { devicesResult = e.Devices; } finally { complete.Set(); } }; bc.DiscoverDevicesAsync(255, true, true, true, false, 999); bool signalled2 = complete.WaitOne(15000); Assert.IsTrue(signalled2, "signalled2"); Delegate2.EndInvoke(dlgt, arDlgt); // any exceptions? VerifyDevicesOne(devicesResult); Assert.AreEqual(3, devicesSteps.Count); Assert.AreEqual(1, devicesSteps[0].Length, "[0].Len"); Assert.AreEqual(AddressA, devicesSteps[0][0].DeviceAddress, "[0][0].Addr"); Assert.AreEqual(AddressA.ToString("C"), devicesSteps[0][0].DeviceName, "[0][0].Name"); // no name Assert.AreEqual(1, devicesSteps[1].Length, "[1].Len"); Assert.AreEqual(AddressB, devicesSteps[1][0].DeviceAddress, "[1][0].Addr"); Assert.AreEqual(NameB, devicesSteps[1][0].DeviceName, "[1][0].Name"); Assert.AreEqual(1, devicesSteps[2].Length, "[2].Len"); Assert.AreEqual(AddressA, devicesSteps[2][0].DeviceAddress, "[2][0].Addr"); Assert.AreEqual(NameA, devicesSteps[2][0].DeviceName, "[2][0].Name"); Assert.AreEqual(1, btIf.stopInquiryCalled, "stopInquiryCalled"); }
/// <summary> /// Begins searching for NCHs. /// </summary> public void start() { index = 0; Array.Clear(nchs, 0, nchs.Count()); isSearching = true; btcomp.DiscoverDevicesAsync(255, false, false, true, true, null); btcomp.DiscoverDevicesProgress += new EventHandler <DiscoverDevicesEventArgs>(Progress); btcomp.DiscoverDevicesComplete += new EventHandler <DiscoverDevicesEventArgs>(End); for (int i = 0; i < observers.Count; i++) { ((IDiscovererObserver)observers[i]).onDiscoveryStart(); } }
private void scan() { BluetoothAddress mac = BluetoothAddress.Parse(bt_mac); // mac is mac address of local bluetooth device localEndpoint = new BluetoothEndPoint(mac, BluetoothService.SerialPort); // client is used to manage connections localClient = new BluetoothClient(localEndpoint); // component is used to manage device discovery localComponent = new BluetoothComponent(localClient); // async methods, can be done synchronously too localComponent.DiscoverDevicesAsync(255, true, true, true, true, null); localComponent.DiscoverDevicesProgress += new EventHandler <DiscoverDevicesEventArgs>(component_DiscoverDevicesProgress); localComponent.DiscoverDevicesComplete += new EventHandler <DiscoverDevicesEventArgs>(component_DiscoverDevicesComplete); }
/// <summary> /// Retuns all discoverable bluetooth devices /// </summary> /// <returns></returns> public async Task <List <BluetoothDeviceInfo> > DiscoverAll() { DeviceDiscoveryTask = new TaskCompletionSource <bool>(); DeviceList.Clear(); using (BluetoothComponent bc = new BluetoothComponent()) { // bc.DiscoverDevicesProgress += Bc_DiscoverDevicesProgress; bc.DiscoverDevicesComplete += Bc_DiscoverDevicesComplete; bc.DiscoverDevicesAsync(255, true, true, true, false, "Blue1"); } await DeviceDiscoveryTask.Task; return(DeviceList); }
private void getDevices() { devices.Clear(); PickDevice.Items.Clear(); // mac is mac address of local bluetooth device localEndpoint = new BluetoothEndPoint(chosenRadio.LocalAddress, BluetoothService.SerialPort); // client is used to manage connections localClient = new BluetoothClient(localEndpoint); // component is used to manage device discovery localComponent = new BluetoothComponent(localClient); // async methods, can be done synchronously too localComponent.DiscoverDevicesAsync(255, true, true, true, true, null); localComponent.DiscoverDevicesProgress += new EventHandler <DiscoverDevicesEventArgs>(component_DiscoverDevicesProgress); localComponent.DiscoverDevicesComplete += new EventHandler <DiscoverDevicesEventArgs>(component_DiscoverDevicesComplete); }
private void Scan() { ScanStatus.Text = "Scanning for devices..."; //Create a new instance of the BluetoothClient class BluetoothClient thisDevice = new BluetoothClient(); //Create a new instance of BluetoothComponent by passing this device BluetoothComponent component = new BluetoothComponent(thisDevice); //Add an event listener for when a device is discovered component.DiscoverDevicesProgress += BluetoothComponent_DiscoverDevicesProgress; //Add an event listener for when the discovery process is finished component.DiscoverDevicesComplete += BluetoothComponent_DiscoverDevicesComplete; //Start discovery of devices component.DiscoverDevicesAsync(8, true, true, true, false, thisDevice); }
public JoyManager( Action <List <BTDeviceInfo> > OnJoyStateChange = null, Action <Byte[]> OnJoyMessageReceive = null, Action <string> OnMessage = null, Action OnStartScanDevice = null, Action OnEndScanDevice = null) { timeBoxJoyList = new List <BTDeviceInfo>(); this.OnJoyStateChange = OnJoyStateChange; this.OnJoyMessageReceive = OnJoyMessageReceive; this.OnMessage = OnMessage; this.OnStartScanDevice = OnStartScanDevice; this.OnEndScanDevice = OnEndScanDevice; //读取所有配置文件 mapConfigs = new List <DefaultMapConfig>(); if (!Directory.Exists("maps")) { Directory.CreateDirectory("maps"); } mapConfigs.Add(new KeyBoardConfig()); mapConfigs.Add(new XInputConfig()); mapConfigs.Add(new MixModeConfig()); mapConfigs.Add(new ScriptModeConfig()); foreach (var file in Directory.GetFiles("maps")) { var _config = DefaultMapConfig.GetConfig(file); //FileInfo finfo = new FileInfo(file); _config.Name = System.IO.Path.GetFileNameWithoutExtension(file); if (!mapConfigs.Any(p => p.Name == _config.Name)) { mapConfigs.Add(_config); } } //读取已记忆的MAC设备 rememberMac = new List <string>(); if (File.Exists("remember.txt")) { FileHelper fh = new FileHelper(); foreach (var addr in fh.readFileLine("remember.txt")) { try { if (string.IsNullOrWhiteSpace(addr)) { continue; } if (!addr.Contains(":")) { continue; } string macAddr = addr.Split(':')[0]; string configName = addr.Split(':')[1]; if (rememberMac.Contains(macAddr)) { continue; } rememberMac.Add(macAddr); BluetoothAddress address = BluetoothAddress.Parse(macAddr); BluetoothDeviceInfo info = new BluetoothDeviceInfo(address); var btDevice = new BTDeviceInfo(info); btDevice.State = deviceState.LOST; btDevice.mapConfig = mapConfigs.Where(i => i.Name == configName).FirstOrDefault(); this.timeBoxJoyList.Add(btDevice); } catch { } } this.OnJoyStateChange?.Invoke(this.timeBoxJoyList); } //初始化蓝牙设备 blueClient = new BluetoothClient(); blueComponent = new BluetoothComponent(blueClient); string name = "timebox"; blueComponent.DiscoverDevicesProgress += (sender, e) => { foreach (var device in e.Devices) { if (device.DeviceName == name && !this.timeBoxJoyList.Any(p => p.bluetoothDeviceInfo.DeviceAddress.ToString() == device.DeviceAddress.ToString())) { this.timeBoxJoyList.Add(new BTDeviceInfo(device)); } } this.OnJoyStateChange?.Invoke(this.timeBoxJoyList); }; blueComponent.DiscoverDevicesComplete += (sender, e) => { if ((DateTime.Now - startScan) < ScanBlueTimeOut) { blueComponent.DiscoverDevicesAsync(30, true, true, true, true, null); } else { this.State = 0; this.OnEndScanDevice?.Invoke(); } }; //启动自动扫描手柄状态线程 Thread tr = new Thread(new ThreadStart(() => { ScanJoyConnection(); })); tr.Start(); }
/// <summary> /// /// </summary> /// <param name="publishService"></param> /// <param name="TXTrecords"></param> /// <param name="id"></param> public Console(NetService publishService, Hashtable TXTrecords, String id) { InitializeComponent(); #if USE_BLUETOOTH // If Bluetooth is supported, then scan for nearby players if (BluetoothRadio.IsSupported) { try { bt = new BluetoothComponent(); bt.DiscoverDevicesComplete += new EventHandler<DiscoverDevicesEventArgs>(discoverComplete); bt.DiscoverDevicesAsync(100, true, true, true, true, null); } catch { if (bt != null) bt.Dispose(); // Something is wrong with bluetooth module } } #endif this.publishService = publishService; this.TXTrecords = TXTrecords; this.id = id; playersItem = new System.Windows.Forms.MenuItem(); playersItem.Text = "P&roject Me"; playersItem.MenuItems.Add("-"); archiversItem = new System.Windows.Forms.MenuItem(); archiversItem.Text = "A&rchive Me"; archiversItem.MenuItems.Add("-"); #if USE_WIFI_LOCALIZATION MSE = new QueryMSE(); myMac = getWIFIMACAddress(); /* if (myMac == null) myMac = displaycast; */ if (myMac != null) { locationItem = new System.Windows.Forms.MenuItem(); locationItem.Text = "Disclose location?"; // locationItem.Index = 4; // playersItem.Index++; // archiversItem.Index++; locationItem.Click += new System.EventHandler(locationChecked); using (RegistryKey dcs = Registry.CurrentUser.CreateSubKey("Software").CreateSubKey("FXPAL").CreateSubKey("DisplayCast").CreateSubKey("Streamer")) { locationItem.Checked = Convert.ToBoolean(dcs.GetValue("discloseLocation")); } discloseLocation = locationItem.Checked; locThread = new Thread(new ThreadStart(monitorMyLocation)); locThread.Start(); } #endif Screen[] screens = Screen.AllScreens; if (screens.Length > 1) { desktopItem = new System.Windows.Forms.MenuItem(); desktopItem.Text = "D&esktop to stream"; desktopItem.MenuItems.Add("-"); foreach (Screen screen in screens) { MenuItem item = new MenuItem(); System.Drawing.Rectangle bounds = screen.Bounds; item.Text = "DESKTOP: " + bounds.X + "x" + bounds.Y + " " + bounds.Width + "x" + bounds.Height; item.Click += new System.EventHandler(selectDesktop); item.Select += new System.EventHandler(selectDesktop); item.Tag = screen; desktopItem.MenuItems.Add(item); } } changeNameItem = new System.Windows.Forms.MenuItem(); changeNameItem.Text = "C&hange Name"; changeNameItem.Click += new System.EventHandler(changeName); aboutItem = new System.Windows.Forms.MenuItem(); aboutItem.Text = "A&bout..."; aboutItem.Click += new System.EventHandler(about); exitItem = new System.Windows.Forms.MenuItem(); exitItem.Text = "E&xit"; exitItem.Click += new System.EventHandler(exitItem_Click); contextMenu = new System.Windows.Forms.ContextMenu(); contextMenu.MenuItems.Add(playersItem); contextMenu.MenuItems.Add(archiversItem); contextMenu.MenuItems.Add("-"); if (locationItem != null) contextMenu.MenuItems.Add(locationItem); if (desktopItem != null) contextMenu.MenuItems.Add(desktopItem); contextMenu.MenuItems.Add(changeNameItem); contextMenu.MenuItems.Add("-"); contextMenu.MenuItems.Add(aboutItem); contextMenu.MenuItems.Add("-"); contextMenu.MenuItems.Add(exitItem); iComponents = new System.ComponentModel.Container(); notifyIcon = new NotifyIcon(iComponents); notifyIcon.Icon = new Icon("Streamer.ico"); // notifyIcon.Icon = Streamer.Properties.Resources.Streamer; // notifyIcon.Icon = new Icon(System.Reflection.Assembly.GetExecutingAssembly().GetManifestResourceStream("FXPAL.DisplayCast.Streamer.Streamer.ico")); notifyIcon.ContextMenu = contextMenu; notifyIcon.Text = "FXPAL Displaycast Streamer"; notifyIcon.Visible = true; notifyIcon.DoubleClick += new System.EventHandler(this.notifyIcon_DoubleClick); player = new NetServiceBrowser(); //player.InvokeableObject = this; player.AllowMultithreadedCallbacks = true; player.DidFindService += new NetServiceBrowser.ServiceFound(nsBrowser_DidFindService); player.DidRemoveService += new NetServiceBrowser.ServiceRemoved(nsBrowser_DidRemoveService); player.SearchForService(Shared.DisplayCastGlobals.PLAYER, Shared.DisplayCastGlobals.BONJOURDOMAIN); archiver = new NetServiceBrowser(); // archiver.InvokeableObject = this; archiver.AllowMultithreadedCallbacks = true; archiver.DidFindService += new NetServiceBrowser.ServiceFound(nsBrowser_DidFindService); archiver.DidRemoveService += new NetServiceBrowser.ServiceRemoved(nsBrowser_DidRemoveService); archiver.SearchForService(Shared.DisplayCastGlobals.ARCHIVER, Shared.DisplayCastGlobals.BONJOURDOMAIN); }
private void scan() { BluetoothAddress mac = BluetoothAddress.Parse(bt_mac); // mac is mac address of local bluetooth device localEndpoint = new BluetoothEndPoint(mac, BluetoothService.SerialPort); // client is used to manage connections localClient = new BluetoothClient(localEndpoint); // component is used to manage device discovery localComponent = new BluetoothComponent(localClient); // async methods, can be done synchronously too localComponent.DiscoverDevicesAsync(255, true, true, true, true, null); localComponent.DiscoverDevicesProgress += new EventHandler<DiscoverDevicesEventArgs>(component_DiscoverDevicesProgress); localComponent.DiscoverDevicesComplete += new EventHandler<DiscoverDevicesEventArgs>(component_DiscoverDevicesComplete); }
/// <summary> /// Callback on a completed discover operation /// </summary> /// <param name="sender"></param> /// <param name="e"></param> static private void discoverComplete(object sender, DiscoverDevicesEventArgs e) { BluetoothDeviceInfo[] devices; try { devices = e.Devices; } catch (Exception ex) { // I was getting a reflection invocation exception. WTF!! BluetoothComponent bt = (BluetoothComponent)sender; // bt.DiscoverDevicesComplete += new EventHandler<DiscoverDevicesEventArgs>(discoverComplete); bt.DiscoverDevicesAsync(100, true, true, true, true, null); return; } foreach (MenuItem menu in playersItem.MenuItems) { if (menu == null) { continue; // WTF? } if (menu.Text.EndsWith("(nearby)")) { menu.Text = menu.Text.Replace("(nearby)", ""); } } try { foreach (BluetoothDeviceInfo device in devices) { string addr = device.DeviceAddress.ToString("C").Replace(":", "-").ToLower(); foreach (MenuItem menu in playersItem.MenuItems) { if (menu == null) { continue; // WTF? } NetService service = (NetService)menu.Tag; if (service == null) { continue; // WTF } if (service.TXTRecordData != null) { IDictionary dict = NetService.DictionaryFromTXTRecordData(service.TXTRecordData); if (dict != null) { foreach (DictionaryEntry kvp in dict) { String key = (String)kvp.Key; key = key.ToUpper(); if (key.Equals("BLUETOOTH")) { byte[] value = (byte[])kvp.Value; try { if (Encoding.UTF8.GetString(value).ToLower().Equals(addr)) { menu.Text = menu.Text + "(nearby)"; } } catch { } break; } } } } } } BluetoothComponent bt = (BluetoothComponent)sender; // bt.DiscoverDevicesComplete += new EventHandler<DiscoverDevicesEventArgs>(discoverComplete); bt.DiscoverDevicesAsync(100, true, true, true, true, null); } catch { } }
/// <summary> /// /// </summary> /// <param name="publishService"></param> /// <param name="TXTrecords"></param> /// <param name="id"></param> public Console(NetService publishService, Hashtable TXTrecords, String id) { InitializeComponent(); #if USE_BLUETOOTH // If Bluetooth is supported, then scan for nearby players if (BluetoothRadio.IsSupported) { try { bt = new BluetoothComponent(); bt.DiscoverDevicesComplete += new EventHandler <DiscoverDevicesEventArgs>(discoverComplete); bt.DiscoverDevicesAsync(100, true, true, true, true, null); } catch { if (bt != null) { bt.Dispose(); } // Something is wrong with bluetooth module } } #endif this.publishService = publishService; this.TXTrecords = TXTrecords; this.id = id; playersItem = new System.Windows.Forms.MenuItem(); playersItem.Text = "P&roject Me"; playersItem.MenuItems.Add("-"); archiversItem = new System.Windows.Forms.MenuItem(); archiversItem.Text = "A&rchive Me"; archiversItem.MenuItems.Add("-"); #if USE_WIFI_LOCALIZATION MSE = new QueryMSE(); myMac = getWIFIMACAddress(); /* if (myMac == null) * myMac = displaycast; */ if (myMac != null) { locationItem = new System.Windows.Forms.MenuItem(); locationItem.Text = "Disclose location?"; // locationItem.Index = 4; // playersItem.Index++; // archiversItem.Index++; locationItem.Click += new System.EventHandler(locationChecked); using (RegistryKey dcs = Registry.CurrentUser.CreateSubKey("Software").CreateSubKey("FXPAL").CreateSubKey("DisplayCast").CreateSubKey("Streamer")) { locationItem.Checked = Convert.ToBoolean(dcs.GetValue("discloseLocation")); } discloseLocation = locationItem.Checked; locThread = new Thread(new ThreadStart(monitorMyLocation)); locThread.Start(); } #endif Screen[] screens = Screen.AllScreens; if (screens.Length > 1) { desktopItem = new System.Windows.Forms.MenuItem(); desktopItem.Text = "D&esktop to stream"; desktopItem.MenuItems.Add("-"); foreach (Screen screen in screens) { MenuItem item = new MenuItem(); System.Drawing.Rectangle bounds = screen.Bounds; item.Text = "DESKTOP: " + bounds.X + "x" + bounds.Y + " " + bounds.Width + "x" + bounds.Height; item.Click += new System.EventHandler(selectDesktop); item.Select += new System.EventHandler(selectDesktop); item.Tag = screen; desktopItem.MenuItems.Add(item); } } changeNameItem = new System.Windows.Forms.MenuItem(); changeNameItem.Text = "C&hange Name"; changeNameItem.Click += new System.EventHandler(changeName); aboutItem = new System.Windows.Forms.MenuItem(); aboutItem.Text = "A&bout..."; aboutItem.Click += new System.EventHandler(about); exitItem = new System.Windows.Forms.MenuItem(); exitItem.Text = "E&xit"; exitItem.Click += new System.EventHandler(exitItem_Click); contextMenu = new System.Windows.Forms.ContextMenu(); contextMenu.MenuItems.Add(playersItem); contextMenu.MenuItems.Add(archiversItem); contextMenu.MenuItems.Add("-"); if (locationItem != null) { contextMenu.MenuItems.Add(locationItem); } if (desktopItem != null) { contextMenu.MenuItems.Add(desktopItem); } contextMenu.MenuItems.Add(changeNameItem); contextMenu.MenuItems.Add("-"); contextMenu.MenuItems.Add(aboutItem); contextMenu.MenuItems.Add("-"); contextMenu.MenuItems.Add(exitItem); iComponents = new System.ComponentModel.Container(); notifyIcon = new NotifyIcon(iComponents); notifyIcon.Icon = new Icon("Streamer.ico"); // notifyIcon.Icon = Streamer.Properties.Resources.Streamer; // notifyIcon.Icon = new Icon(System.Reflection.Assembly.GetExecutingAssembly().GetManifestResourceStream("FXPAL.DisplayCast.Streamer.Streamer.ico")); notifyIcon.ContextMenu = contextMenu; notifyIcon.Text = "FXPAL Displaycast Streamer"; notifyIcon.Visible = true; notifyIcon.DoubleClick += new System.EventHandler(this.notifyIcon_DoubleClick); player = new NetServiceBrowser(); //player.InvokeableObject = this; player.AllowMultithreadedCallbacks = true; player.DidFindService += new NetServiceBrowser.ServiceFound(nsBrowser_DidFindService); player.DidRemoveService += new NetServiceBrowser.ServiceRemoved(nsBrowser_DidRemoveService); player.SearchForService(Shared.DisplayCastGlobals.PLAYER, Shared.DisplayCastGlobals.BONJOURDOMAIN); archiver = new NetServiceBrowser(); // archiver.InvokeableObject = this; archiver.AllowMultithreadedCallbacks = true; archiver.DidFindService += new NetServiceBrowser.ServiceFound(nsBrowser_DidFindService); archiver.DidRemoveService += new NetServiceBrowser.ServiceRemoved(nsBrowser_DidRemoveService); archiver.SearchForService(Shared.DisplayCastGlobals.ARCHIVER, Shared.DisplayCastGlobals.BONJOURDOMAIN); }
private bool StartDeviceSearch() { UpdateDeviceList(null, true); if (_cli == null) { return(false); } try { _deviceList.Clear(); BluetoothComponent bco = new BluetoothComponent(_cli); bco.DiscoverDevicesProgress += (sender, args) => { if (args.Error == null && !args.Cancelled && args.Devices != null) { try { foreach (BluetoothDeviceInfo device in args.Devices) { device.Refresh(); } } catch (Exception) { // ignored } BeginInvoke((Action)(() => { UpdateDeviceList(args.Devices, false); })); } }; bco.DiscoverDevicesComplete += (sender, args) => { _searching = false; UpdateButtonStatus(); BeginInvoke((Action)(() => { if (args.Error == null && !args.Cancelled) { UpdateDeviceList(args.Devices, true); UpdateStatusText(listViewDevices.Items.Count > 0 ? "Devices found" : "No devices found"); } else { // ReSharper disable once ConvertIfStatementToConditionalTernaryExpression if (args.Error != null) { UpdateStatusText(string.Format("Searching failed: {0}", args.Error.Message)); } else { UpdateStatusText("Searching failed"); } } })); }; bco.DiscoverDevicesAsync(1000, true, false, true, IsWinVistaOrHigher(), bco); _searching = true; UpdateStatusText("Searching ..."); UpdateButtonStatus(); } catch (Exception) { UpdateStatusText("Searching failed"); return(false); } return(true); }
private void button1_Click(object sender, EventArgs e) { ClearLogging(); Component.DiscoverDevicesAsync(byte.MaxValue, true, true, false, false, null); }
// кнопка для открытия (чтобы не прописывать в конструкторе) private void Open_Click(object sender, EventArgs e) { Open.Enabled = false; label1.Visible = true; // проверка работает ли bluetooth if (BluetoothRadio.IsSupported) { // проверка расширения string k = Path.GetExtension(path); if (k == ".code3") { // закрыываем кнопку Open.Enabled = false; // дезериализуем ключ и файл DataContractJsonSerializer json2 = new DataContractJsonSerializer(typeof(Connectwithakey)); DataContractJsonSerializer json = new DataContractJsonSerializer(typeof(ToCode)); FileStream st = null; if (File.Exists(path)) { try { st = new FileStream(path, FileMode.Open); } catch (IOException ex) { Console.WriteLine("Try again"); } try { Connectwithakey con = null; con = (Connectwithakey)json2.ReadObject(st); FindkeyNumber = con.file; // номер ключа this.num = int.Parse(Encoding.ASCII.GetString(con.keynumber)); st.Close(); byte[] serkey = null; // извлечение ключа из файла if (File.Exists($"C:/Users/{Environment.UserName}/AppData/Roaming/Palon/Pakman{num}.txt")) { serkey = File.ReadAllBytes($"C:/Users/{Environment.UserName}/AppData/Roaming/Palon/Pakman{num}.txt"); IntPtr accountToken = WindowsIdentity.GetCurrent().Token; WindowsIdentity win = new WindowsIdentity(accountToken); // раскодируем ID = win.User.ToString(); // ксорим с id в ASCII byte[] tocodekey = Encoding.ASCII.GetBytes(ID); int q = 0; for (int i = 0; i < serkey.Length; i++) { if (q == tocodekey.Length) { q = 0; } serkey[i] = (byte)(serkey[i] ^ tocodekey[q]); } // создём вспомогательный файл для десериализации и извдечение полей класса string help; if (Directory.Exists($"C:/Users/{Environment.UserName}/AppData/Roaming")) { help = $"C:/Users/{Environment.UserName}/AppData/Roaming/Palon/Pakman{num}Help.txt"; } else { help = $"../Pakman{num}Help.txt"; } // файл нужен для десериализации (так быстрее чем с memorystream так как есть writeallbytes) File.Create(help).Close(); File.WriteAllBytes(help, serkey); FileStream l = new FileStream(help, FileMode.Open); cod = (ToCode)json.ReadObject(l); l.Close(); // удаляем вспомогательный файл File.Delete(help); // проверяем совпадение устройста devicename = cod.DeviceName; deviceadress = cod.DeviceAdress; // компонента bluetooth BluetoothComponent component = new BluetoothComponent(); // добавляем метод который будет сделать если найдено новое устройство component.DiscoverDevicesProgress += BluetoothDescovery; // метод в конце работы component.DiscoverDevicesComplete += BluetoothEndDescovery; // поиск устройства component.DiscoverDevicesAsync(10, true, false, true, true, 0); } else { if (File.Exists($"../Palon/Pakman{num}.txt")) { serkey = File.ReadAllBytes($"../Palon/Pakman{num}.txt"); IntPtr accountToken = WindowsIdentity.GetCurrent().Token; WindowsIdentity win = new WindowsIdentity(accountToken); // раскодируем ID = win.User.ToString(); // ксорим с id в ASCII byte[] tocodekey = Encoding.ASCII.GetBytes(ID); int q = 0; for (int i = 0; i < serkey.Length; i++) { if (q == tocodekey.Length) { q = 0; } serkey[i] = (byte)(serkey[i] ^ tocodekey[q]); } // создём вспомогательный файл для десериализации и извдечение полей класса string help; if (Directory.Exists($"C:/Users/{Environment.UserName}/AppData/Roaming")) { help = $"C:/Users/{Environment.UserName}/AppData/Roaming/Palon/Pakman{num}Help.txt"; } else { help = $"../Pakman{num}Help.txt"; } // файл нужен для десериализации (так быстрее чем с memorystream так как есть writeallbytes) File.Create(help).Close(); File.WriteAllBytes(help, serkey); FileStream l = new FileStream(help, FileMode.Open); cod = (ToCode)json.ReadObject(l); l.Close(); // удаляем вспомогательный файл File.Delete(help); // проверяем совпадение устройста devicename = cod.DeviceName; deviceadress = cod.DeviceAdress; // компонента bluetooth BluetoothComponent component = new BluetoothComponent(); // добавляем метод который будет сделать если найдено новое устройство component.DiscoverDevicesProgress += BluetoothDescovery; // метод в конце работы component.DiscoverDevicesComplete += BluetoothEndDescovery; // поиск устройства component.DiscoverDevicesAsync(10, true, false, true, true, 0); } else { MessageBox.Show("Something has happened with keys"); this.Close(); } } //безопастность (учетная запись) } catch (Exception ex) { MessageBox.Show("Two programms are trying to encript file"); this.Close(); } } else { MessageBox.Show("Two programms are trying to encript file"); this.Close(); } } else { DataContractJsonSerializer json2 = new DataContractJsonSerializer(typeof(Connectwithakey)); DataContractJsonSerializer json = new DataContractJsonSerializer(typeof(ToCode)); // десереализуем файл FileStream st = null; if (File.Exists(path)) { try { st = new FileStream(path, FileMode.Open); Connectwithakey con = null; con = (Connectwithakey)json2.ReadObject(st); FindkeyNumber = con.file; // номер ключа this.num = int.Parse(Encoding.ASCII.GetString(con.keynumber)); st.Close(); // извлечение ключа из файла byte[] serkey = null; // извлечение ключа из файла if (File.Exists($"C:/Users/{Environment.UserName}/AppData/Roaming/Palon/PakmanD{num}.txt")) { serkey = File.ReadAllBytes($"C:/Users/{Environment.UserName}/AppData/Roaming/Palon/PakmanD{num}.txt"); } else { if (File.Exists($"../Palon/PakmanD{num}.txt")) { serkey = File.ReadAllBytes($"../Palon/PakmanD{num}.txt"); } else { MessageBox.Show("Something has happened with keys"); this.Close(); } } //безопастность (учетная запись) IntPtr accountToken = WindowsIdentity.GetCurrent().Token; WindowsIdentity win = new WindowsIdentity(accountToken); // раскодируем ксоря c ID в ASCII ID = win.User.ToString(); byte[] tocodekey = Encoding.ASCII.GetBytes(ID); int q = 0; for (int i = 0; i < serkey.Length; i++) { if (q == tocodekey.Length) { q = 0; } serkey[i] = (byte)(serkey[i] ^ tocodekey[q]); } // создём вспомогательный файл для десериализации и извдечение полей класса string help; if (Directory.Exists($"C:/Users/{Environment.UserName}/AppData/Roaming")) { help = $"C:/Users/{Environment.UserName}/AppData/Roaming/Palon/PakmanD{num}Help.txt"; } else { help = $"../PakmanD{num}Help.txt"; } // перезаписываем файл для десериализации так удобней чем при memorystream так как writeallbytes File.Create(help).Close(); File.WriteAllBytes(help, serkey); FileStream l = new FileStream(help, FileMode.Open); cod = (ToCode)json.ReadObject(l); l.Close(); // удаляем вспомогательный файл File.Delete(help); // проверяем совпадение устройста devicename = cod.DeviceName; deviceadress = cod.DeviceAdress; // создаём компоненту поиска BluetoothComponent component = new BluetoothComponent(); // добавляем метод при каждом нахождении нового устройствва component.DiscoverDevicesProgress += BluetoothDescovery; // метод в конце поиска component.DiscoverDevicesComplete += BluetoothEndDescovery; // начало писка component.DiscoverDevicesAsync(10, true, false, true, true, 0); } catch (Exception ex) { MessageBox.Show("Two programms are trying to encript file"); this.Close(); } } else { MessageBox.Show("Two programms are trying to encript file"); this.Close(); } } } // раскодируем по паролю else { // аналогично смотрим расширение string k = Path.GetExtension(path); if (k == ".code3") { // откючаем кнопку Open.Enabled = false; DataContractJsonSerializer json2 = new DataContractJsonSerializer(typeof(Connectwithakey)); DataContractJsonSerializer json = new DataContractJsonSerializer(typeof(ToCode)); // десериализуем основной файл FileStream st = null; if (File.Exists(path)) { try { st = new FileStream(path, FileMode.Open); Connectwithakey con = null; con = (Connectwithakey)json2.ReadObject(st); FindkeyNumber = con.file; // номер ключа this.num = int.Parse(Encoding.ASCII.GetString(con.keynumber)); st.Close(); // извлечение ключа из файла byte[] serkey = null; // извлечение ключа из файла if (File.Exists($"C:/Users/{Environment.UserName}/AppData/Roaming/Palon/Pakman{num}.txt")) { serkey = File.ReadAllBytes($"C:/Users/{Environment.UserName}/AppData/Roaming/Palon/Pakman{num}.txt"); } else { if (File.Exists($"../Palon/Pakman{num}.txt")) { serkey = File.ReadAllBytes($"../Palon/Pakman{num}.txt"); } else { MessageBox.Show("Something has happened with keys"); this.Close(); } } //безопастность (учетная запись) IntPtr accountToken = WindowsIdentity.GetCurrent().Token; WindowsIdentity win = new WindowsIdentity(accountToken); // раскодируем ксоря с id ASCII ID = win.User.ToString(); byte[] tocodekey = Encoding.ASCII.GetBytes(ID); int q = 0; for (int i = 0; i < serkey.Length; i++) { if (q == tocodekey.Length) { q = 0; } serkey[i] = (byte)(serkey[i] ^ tocodekey[q]); } // создём вспомогательный файл для десериализации и извдечение полей класса string help; if (Directory.Exists($"C:/Users/{Environment.UserName}/AppData/Roaming")) { help = $"C:/Users/{Environment.UserName}/AppData/Roaming/Palon/Pakman{num}Help.txt"; } else { help = $"../Pakman{num}Help.txt"; } File.Create(help).Close(); File.WriteAllBytes(help, serkey); FileStream l = new FileStream(help, FileMode.Open); cod = (ToCode)json.ReadObject(l); l.Close(); // удаляем вспомогательный файл File.Delete(help); // проверяем совпадение устройста devicename = cod.DeviceName; deviceadress = cod.DeviceAdress; // если устройства нет рядом просим ввести пароль NotFoundCheckingPassword password = new NotFoundCheckingPassword(cod); password.ShowDialog(); // проверка верности пароля if (password.Pasbool) { Redeem(); } } catch (Exception ex) { MessageBox.Show("Two programms are trying to encript file"); this.Close(); } } else { MessageBox.Show("Two programms are trying to encript file"); this.Close(); } } else { // десериализуем основной файл DataContractJsonSerializer json2 = new DataContractJsonSerializer(typeof(Connectwithakey)); DataContractJsonSerializer json = new DataContractJsonSerializer(typeof(ToCode)); FileStream st = null; if (File.Exists(path)) { try { st = new FileStream(path, FileMode.Open); Connectwithakey con = null; con = (Connectwithakey)json2.ReadObject(st); FindkeyNumber = con.file; // номер ключа this.num = int.Parse(Encoding.ASCII.GetString(con.keynumber)); st.Close(); // извлечение ключа из файла byte[] serkey = null; // извлечение ключа из файла if (File.Exists($"C:/Users/{Environment.UserName}/AppData/Roaming/Palon/PakmanD{num}.txt")) { serkey = File.ReadAllBytes($"C:/Users/{Environment.UserName}/AppData/Roaming/Palon/PakmanD{num}.txt"); } else { if (File.Exists($"../Palon/PakmanD{num}.txt")) { serkey = File.ReadAllBytes($"../Palon/PakmanD{num}.txt"); } else { MessageBox.Show("Something has happened with keys"); this.Close(); } }//безопастность (учетная запись) IntPtr accountToken = WindowsIdentity.GetCurrent().Token; WindowsIdentity win = new WindowsIdentity(accountToken); // раскодируем ксоря с ID в ASCII ID = win.User.ToString(); byte[] tocodekey = Encoding.ASCII.GetBytes(ID); int q = 0; for (int i = 0; i < serkey.Length; i++) { if (q == tocodekey.Length) { q = 0; } serkey[i] = (byte)(serkey[i] ^ tocodekey[q]); } // создём вспомогательный файл для десериализации и извдечение полей класса string help; if (Directory.Exists($"C:/Users/{Environment.UserName}/AppData/Roaming")) { help = $"C:/Users/{Environment.UserName}/AppData/Roaming/Palon/PakmanD{num}Help.txt"; } else { help = $"../PakmanD{num}Help.txt"; } // так быстрее так как в memorystream нет writeallbytes File.Create(help).Close(); File.WriteAllBytes(help, serkey); FileStream l = new FileStream(help, FileMode.Open); cod = (ToCode)json.ReadObject(l); l.Close(); // удаляем вспомогательный файл File.Delete(help); // проверяем совпадение устройста devicename = cod.DeviceName; deviceadress = cod.DeviceAdress; // если устройства нет рядом просим ввести пароль NotFoundCheckingPassword password = new NotFoundCheckingPassword(cod); password.ShowDialog(); // проверка верности пароля if (password.Pasbool) { Redeem(); } } catch (Exception ex) { MessageBox.Show("Two programms are trying to encript file"); this.Close(); } } else { MessageBox.Show("Two programms are trying to encript file"); this.Close(); } } } }
private void searchForNewDevices() { component.DiscoverDevicesComplete += new EventHandler <DiscoverDevicesEventArgs>(DiscoverDevicesFinish); component.DiscoverDevicesAsync(255, true, true, true, true, null); }
void BlueTimer_Tick(object sender, EventArgs e) { BlueTimer.Stop(); using (BluetoothComponent bt = new BluetoothComponent()) { bt.DiscoverDevicesComplete += new EventHandler<DiscoverDevicesEventArgs>(bt_DiscoverDevicesComplete); bt.DiscoverDevicesAsync(100, false, false, false, true, null); } }