コード例 #1
0
 private void button3_Click(object sender, EventArgs e)
 {
     if (client.Connected)
     {
         client.Close();
         stream.Close();
         client.Dispose();
         stream.Dispose();
         label3.Text           = "Status: Disconnect";
         btnConnect.Enabled    = !client.Connected;
         btnDisconnect.Enabled = client.Connected;
         btnSend.Enabled       = client.Connected;
     }
 }
コード例 #2
0
        void BluetoothConnect()
        {
            string androidTabletMAC = "68:05:71:AA:2B:C7"; // The MAC address of my phone, lets assume we know it

            BluetoothAddress addr = BluetoothAddress.Parse(androidTabletMAC);
            //var btEndpoint = new BluetoothEndPoint(addr, 1600);
            var btClient = new BluetoothClient();
            //btClient.Connect(btEndpoint);

            Stream peerStream = btClient.GetStream();

            StreamWriter sw = new StreamWriter(peerStream);
            sw.WriteLine("Hello World");
            sw.Flush();
            sw.Close();

            btClient.Close();
            btClient.Dispose();
               // btEndpoint = null;
        }
コード例 #3
0
ファイル: Form4.cs プロジェクト: katadam/wockets
        //Search
        private void button_search_Click(object sender, EventArgs e)
        {
            try
            {
                this.label_status.Text = "Please wait... searching for wockets";
                this.Refresh();
                this.button_search.Enabled = false;

                this.dataGridView1.Rows.Clear();
                this.macaddresses.Clear();
                bluetoothlist.Clear();
                int wocketCount = 0;

                if (BluetoothRadio.PrimaryRadio.Mode != RadioMode.Connectable)
                {
                    BluetoothRadio.PrimaryRadio.Mode = RadioMode.Connectable;
                }
                BluetoothClient btc = new BluetoothClient();

                label_status.Text = "Searching for wockets...";
                Application.DoEvents();

                devices = btc.DiscoverDevices(60, true, true, true);

                for (int i = 0; (i < devices.Length); i++)
                {
                    //if the device is a wocket
                    if (((devices[i].DeviceName.IndexOf("Wocket") >= 0)
                        || (devices[i].DeviceName.IndexOf("WKT") >= 0)
                        || (devices[i].DeviceName.IndexOf("FireFly") >= 0)
                        || (devices[i].DeviceName.IndexOf("00:06:66") >= 0)
                        && (wocketCount < 100)))
                    {
                        string hex = "";
                        hex = devices[i].DeviceAddress.ToString();

                        System.Threading.Thread.Sleep(1000);

                        if (this.macaddresses.IndexOf(hex) < 0)
                        {
                            int row = this.dataGridView1.Rows.Add();

                            this.dataGridView1.Rows[row].Cells[0].Value = devices[i].DeviceName;
                            this.dataGridView1.Rows[row].Cells[1].Value = hex;
                            this.dataGridView1.Rows[row].Cells[2].Value = "Not tested";
                            this.dataGridView1.Rows[row].Cells[3].Value = "Not tested";

                            macaddresses.Add(hex);
                            bluetoothlist.Add(devices[i]);

                            System.Threading.Thread.Sleep(1000);

                        }

                        wocketCount++;
                    }
                }

                btc.Dispose();
                btc.Close();

                if (this.dataGridView1.Rows.Count > 0)
                {
                    this.button_test.Enabled = true;
                    this.button_settings.Enabled = true;
                }

                label_status.Text = "Waiting for wocket...";

            }
            catch
            {
                label_status.Text = "BT module not responding.";
            }

            this.button_search.Enabled = true;
        }
コード例 #4
0
ファイル: Form1.cs プロジェクト: katadam/wockets
        private void button_search_Click(object sender, EventArgs e)
        {
            this.label_status.Text = "Please wait... searching for wockets";
            this.Refresh();
            this.button_search.Enabled = false;
            this.listBox1.Items.Clear();
            BluetoothRadio.PrimaryRadio.Mode = RadioMode.Connectable;
            BluetoothClient btc = new BluetoothClient();

            devices = btc.DiscoverDevices(60, false, false, true);
            int wocketCount = 0;
            for (int i = 0; (i < devices.Length); i++)
            {
                //if the device is a wocket
                if (((devices[i].DeviceName.IndexOf("Wocket") >= 0)
                    || (devices[i].DeviceName.IndexOf("WKT") >= 0)
                    || (devices[i].DeviceName.IndexOf("FireFly") >= 0)
                    || (devices[i].DeviceName.IndexOf("00:06:66") >= 0))
                    && (wocketCount < 100))
                {
                    string hex = "";
                    hex = devices[i].DeviceAddress.ToString();
                    if (this.listBox1.Items.IndexOf(hex) < 0)
                    {
                        this.listBox1.Items.Add(devices[i].DeviceName + " (" + hex + ")");
                        macaddresses.Add(hex);
                    }
                    wocketCount++;
                }
            }
            btc.Dispose();
            btc.Close();

            if (this.listBox1.Items.Count > 0)
                this.button_configure.Enabled = true;
            this.button_search.Enabled = true;
        }
コード例 #5
0
        private void SendZip()
        {
            Logger.LogEvent(true, "MainViewModel.SendZip 200");

            this.wasCanceled = false;
            this.IsScanning = true;
            this.Status = "Trying to establish connection and transfer file..";
            var success = false;
            Exception lastEx = null;

            if (BluetoothRadio.PrimaryRadio.Mode == RadioMode.PowerOff)
            {
                BluetoothRadio.PrimaryRadio.Mode = RadioMode.Connectable;
            }

            Logger.LogEvent(true, "MainViewModel.SendZip 201");

            Task.Factory.StartNew(() =>
            {
                if (this.selectedDevice != null)
                {
                    var bluetoothClient = new BluetoothClient();
                    NetworkStream bluetoothStream = null;

                    this.connectionIntervalFinished = false;

                    System.Timers.Timer aTimer = new System.Timers.Timer();
                    aTimer.Elapsed += this.OnTimedEvent;
                    // Set the Interval to 20 second.
                    aTimer.Interval = 20000;
                    aTimer.Start();

                    var device = this.realDevices.FirstOrDefault(x => x.DeviceAddress.Sap == this.selectedDevice.DeviceAddressSap);

                    Logger.LogEvent(true, "MainViewModel.SendZip 201.5 device.DeviceName: {0}", device.DeviceName);

                    var ep = new BluetoothEndPoint(device.DeviceAddress, _serviceClassId);

                    Logger.LogEvent(true, "MainViewModel.SendZip 201.75 ep.Address: {0}", ep.Address);

                    while (!this.connectionIntervalFinished && !success && !this.wasCanceled)
                    {
                        try
                        {
                            Logger.LogEvent(true, "MainViewModel.SendZip 201.8 connectionIntervalFinished: {0} , \n success: {1} , \n wasCanceled: {2}",
                                connectionIntervalFinished, success, wasCanceled);

                            // connecting
                            bluetoothClient.Connect(ep);

                            Logger.LogEvent(true, "MainViewModel.SendZip 201.9");

                            // get stream for send the data
                            bluetoothStream = bluetoothClient.GetStream();

                            Logger.LogEvent(true, "MainViewModel.SendZip 201.95");

                            // if all is ok to send
                            if (bluetoothClient.Connected && bluetoothStream != null)
                            {
                                this.Status = "Connection is established and ready to send.";
                                // write the data in the stream

                                var fileInfo = new FileInfo(this.lastZipPath);

                                Logger.LogEvent(true, "MainViewModel.SendZip 202");

                                //var buffer = System.Text.Encoding.UTF8.GetBytes();
                                int fileLength;
                                if (int.TryParse(fileInfo.Length.ToString(), out fileLength))
                                {
                                    var sizeBuffer = LastMileHealth.Helpers.Utils.IntToByteArray(fileLength);
                                    //var sizeBuffer = BitConverter.GetBytes(fileLength);

                                    Logger.LogEvent(true, "MainViewModel.SendZip 203 sizeBuffer: {0}", sizeBuffer.Length);

                                    //TODO: CHUNKS! 4096 //BinaryWriter bw = new BinaryWriter(bluetoothStream);
                                    var fileBuffer = System.IO.File.ReadAllBytes(this.lastZipPath);

                                    var buffer = LastMileHealth.Helpers.Utils.Combine(sizeBuffer, fileBuffer);

                                    Logger.LogEvent(true, "MainViewModel.SendZip 204 sizeBuffer: {0}", buffer.Length);

                                    bluetoothStream.Write(buffer, 0, buffer.Length);
                                    //bluetoothStream.Flush();

                                    // TODO: async method StartListen for responce
                                    byte[] receivedIntBytes = new byte[4];
                                    var tst = bluetoothStream.Read(receivedIntBytes, 0, 4);
                                    var receivedInt = LastMileHealth.Helpers.Utils.ByteArrayToInt(receivedIntBytes);

                                    Logger.LogEvent(true, "MainViewModel.SendZip 205 sizeBuffer: {0}", receivedInt);

                                    if (receivedInt == fileLength)
                                    {
                                        success = true;
                                        Logger.LogEvent(true, "MainViewModel.SendZip 206");
                                    }
                                }
                                else
                                {
                                    this.Status = "Too big file!";
                                    MessageBox.Show("Too big file!");
                                }
                            }
                        }
                        catch (Exception ex)
                        {
                            Logger.LogEvent(true, "MainViewModel.SendZip 207 Exception = {0} , \nStack = {1}", ex.Message, ex.StackTrace);
                            lastEx = ex;
                        }
                        finally
                        {
                            //if (bluetoothClient != null)
                            //{
                            //    //bluetoothStream.Flush();
                            //    //bluetoothStream.Close();

                            //    bluetoothClient.Close();
                            //    bluetoothClient.Dispose();
                            //}
                        }
                    }

                    Logger.LogEvent(true, "MainViewModel.SendZip 208");

                    this.StopTimer(aTimer);
                    //if (bluetoothStream != null)
                    //{
                    //    bluetoothStream.Flush();
                    //    bluetoothStream.Close();
                    //}

                    if (bluetoothClient != null)
                    {
                        Logger.LogEvent(true, "MainViewModel.SendZip 209");

                        bluetoothClient.Close();
                        bluetoothClient.Dispose();
                        bluetoothClient = null;
                    }

                    Logger.LogEvent(true, "MainViewModel.SendZip 210");
                }
            }).ContinueWith(taskState =>
            {
                Logger.LogEvent(true, "MainViewModel.SendZip 211");

                this.IsScanning = false;

                if (success)
                {
                    this.Status = string.Format("File \"{0}\" has been transferred to {1}!", Path.GetFileNameWithoutExtension(this.lastZipPath) + ".lmu", this.selectedDevice.Name);
                    this.ClearAfterSendOrCancel();
                }
                else if (!this.wasCanceled)
                {
                    this.Status = "Form transfering failed.";

                    Logger.LogEvent(true, "MainViewModel.SendZip 212 lastEx: {0}", lastEx == null ? "IsNULL" : "Not NULL");

                    if (lastEx != null)
                    {
                        if (lastEx is SocketException)
                        {
                            var socketEx = (SocketException)lastEx;

                            BluetoothRadio.PrimaryRadio.Mode = RadioMode.PowerOff;

                            if (socketEx.SocketErrorCode == SocketError.AddressNotAvailable || socketEx.SocketErrorCode == SocketError.TimedOut)
                            {
                                MessageBox.Show("Selected bluetooth device is not available. Please press \"App Update\" button on an appropriate device before sending forms.", "Destination device is not reachable.",
                                    MessageBoxButton.OK, MessageBoxImage.Warning);
                            }
                            else if (socketEx.SocketErrorCode == SocketError.InvalidArgument || socketEx.SocketErrorCode == SocketError.Shutdown)
                            {
                                MessageBox.Show("Try one of next solutions:\n- Try to restart the application\n- Unpair devices in settings (for both devices) and pair them again.\n",
                                    "Bluetooth connection problem.", MessageBoxButton.OK, MessageBoxImage.Error);
                            }
                            else// if (lastEx.Message.Contains("invalid argument was supplied")) // (lastEx as SocketException).SocketErrorCode == SocketError.Shutdown
                            {
                                MessageBox.Show("Try one of next solutions:\n- Try to restart the application;\n- Unpair devices in settings (for both devices) and pair them again;\n- Go to Start > Type services.msc > Services Local > Then scroll down the list till you see 'Bluetooth Support Service' > Right click on it and then Stop the process and then start it up again;\n- Update bluetooth drivers;",
                                    "Bluetooth connection problem.", MessageBoxButton.OK, MessageBoxImage.Error);
                            }
                        }

                        Logger.LogEvent(true, "MainViewModel.SendZip 213");

                        this.AddExceptionToLog(lastEx);
                    }

                    this.SelectedDeviceIndex = -1;
                }

                Logger.LogEvent(true, "MainViewModel.SendZip 214");

            }, TaskScheduler.FromCurrentSynchronizationContext());

            Logger.LogEvent(true, "MainViewModel.SendZip 215");
        }
コード例 #6
0
ファイル: Form1.cs プロジェクト: katadam/wockets
        private void button1_Click(object sender, EventArgs e)
        {
            this.listBox1.Items.Clear();
            this.label2.Text = "Searching... please wait";
            this.label2.Update();
            try
            {
                BluetoothRadio.PrimaryRadio.Mode = RadioMode.Connectable;
                BluetoothClient btc = new BluetoothClient();

                devices = btc.DiscoverDevices(60, false, true, true);

                for (int i = 0; (i < devices.Length); i++)
                {
                    //if the device is a wocket
                    if (((devices[i].DeviceName.IndexOf("Wocket") >= 0)
                        || (devices[i].DeviceName.IndexOf("WKT") >= 0)
                        || (devices[i].DeviceName.IndexOf("FireFly") >= 0)
                        || (devices[i].DeviceName.IndexOf("0006660") >= 0)
                        && (wocketCount < 100)))
                    {
                        string hex = "";
                        hex = devices[i].DeviceAddress.ToString();

                        #region Commented
                        // if (this.WocketsList_Box.Items.IndexOf(hex) < 0)
                        //{
                        //    this.WocketsList_Box.Items.Add(devices[i].DeviceName + " (" + hex + ")");
                        //macaddresses.Add(hex);
                        //}
                        #endregion Commented

                        this.listBox1.Items.Add(hex);
                        bluetoothlist.Add(hex, devices[i]);

                        wocketCount++;
                    }
                }

                btc.Dispose();
                btc.Close();
            }
            catch
            {
                MessageBox.Show("Cannot connect: please check your Bluetooth radio is plugged in and active");
                Environment.Exit(0);
            }
        }
コード例 #7
0
        public override void receive_file(String devicename, String bluid, int not)
        {
            try
            {
                _stopwatch.Start();
                scan_transfer_speed();                

                _bluetooth_guid = Guid.Parse(bluid);
                _bluetooth_listener = new BluetoothListener(_bluetooth_guid);
                _bluetooth_listener.Start();

                _bluetooth_client = _bluetooth_listener.AcceptBluetoothClient();
                _netstream = _bluetooth_client.GetStream();

                _filestream = new FileStream(this.filepath, FileMode.Create, FileAccess.ReadWrite);

                int length;
                _buffer = new byte[65000];
                
                while ((length = _netstream.Read(_buffer, 0, _buffer.Length)) != 0)
                {
                    while (_writing) { }

                    _count_received_bytes += length;

                    _filestream.Write(_buffer, 0, length);
                }

                _timer_ts.Close();
                _stopwatch.Stop();

                int _transferspeed = _count_received_bytes / 1024;
                _message = format_message(_stopwatch.Elapsed, "Transferspeed", _transferspeed.ToString(), "kB/s");
                this.callback.on_transfer_speed_change(_message, this.results);
                this.main_view.text_to_logs(_message);

                _filestream.Dispose();
                _filestream.Close();

                _netstream.Dispose();
                _netstream.Close();

                _bluetooth_client.Dispose();
                _bluetooth_client.Close();

                _bluetooth_listener.Stop();

                _message = format_message(_stopwatch.Elapsed, "File Transfer", "OK", this.filepath);
                this.callback.on_file_received(_message, this.results);
                this.main_view.text_to_logs(_message);
            }
            catch (Exception e)
            {
                append_error_tolog(e, _stopwatch.Elapsed, devicename);
            }
        }               
コード例 #8
-2
        public override void send_file(String devicename, String bluid, int not)
        {
            try
            {
                _stopwatch.Start();

                _bluetooth_client = new BluetoothClient();

                BluetoothDeviceInfo[] devinfos = _bluetooth_client.DiscoverDevices();

                foreach (var device in devinfos)
                {
                    if (device.DeviceName == devicename)
                    {
                        _bluetooth_address = device.DeviceAddress;
                        break;
                    }
                }

                _bluetooth_guid = Guid.Parse(bluid);

                _bluetooth_client.Connect(_bluetooth_address, _bluetooth_guid);

                _netstream = _bluetooth_client.GetStream();

                byte[] dataToSend = File.ReadAllBytes(this.filepath);

                _netstream.Write(dataToSend, 0, dataToSend.Length);
                _netstream.Flush();

                _netstream.Dispose();
                _netstream.Close();

                _bluetooth_client.Dispose();
                _bluetooth_client.Close();

                _message = format_message(_stopwatch.Elapsed, "File Transfer", "OK", this.filepath);
                this.callback.on_file_received(_message, this.results);
                this.main_view.text_to_logs(_message);

                _stopwatch.Stop();
            }
            catch (Exception e)
            {
                append_error_tolog(e, _stopwatch.Elapsed, devicename);
            }
        }