protected override void OnCreate (Bundle bundle)
		{
			base.OnCreate (bundle);

			// Set our view from the "main" layout resource
			SetContentView (Resource.Layout.Main);

			status = FindViewById<TextView> (Resource.Id.statusText);
			TryToConnect ();

			FindViewById<Button> (Resource.Id.light1).Click += delegate { SendAMessage("q","toggling light 1"); };
			FindViewById<Button> (Resource.Id.light2).Click += delegate { SendAMessage("w","toggling light 2"); };
			FindViewById<Button> (Resource.Id.light3).Click += delegate { SendAMessage("e","toggling light 3"); };
			FindViewById<Button> (Resource.Id.door1).Click += delegate { SendAMessage("1","toggling door 1"); };
			FindViewById<Button> (Resource.Id.door2).Click += delegate { SendAMessage("2","toggling door 2"); };
			FindViewById<Button> (Resource.Id.door3).Click += delegate { SendAMessage("3","toggling door 3"); };
			connectorButton = FindViewById<Button> (Resource.Id.cnx);
			connectorButton.Click += delegate {
				if (socket != null && socket.IsConnected) {
					socket.Close ();
					socket.Dispose ();
					socket = null;
					connectorButton.Text = "Connect";
					status.Text = "ain't connected";
				}else{
					TryToConnect();
				}
			};
			connectorButton.Enabled = true;
		}
Example #2
0
 public ConnectedSphero(BluetoothDevice bluetoothDevice, BluetoothSocket socket)
     : base(bluetoothDevice)
 {
     _spheroSocketWrapper = new StreamSocketWrapper(socket);
     _runner = new NonAwaitingConnectedSpheroRunner(_spheroSocketWrapper);
     _runner.Disconnected += (sender, args) => RaiseDisconnected();
     _runner.Start();
 }
		/// <summary>
		/// Disconnect from the EV3 brick.
		/// </summary>
		public void Disconnect()
		{
			if(_socket != null)
			{
				_socket.Dispose();
				_socket = null;
			}
		}
 public async Task Connect()
 {
     if (this.socket == null)
     {
         this.socket = this.device.CreateRfcommSocketToServiceRecord(this.uuid);
     }
     
     await this.socket.ConnectAsync();
 }
		/// <summary>
		///     Connects this instance.
		/// </summary>
		/// <returns>Task.</returns>
		public async Task Connect()
		{
			if (_socket == null)
			{
				_socket = _device.CreateRfcommSocketToServiceRecord(_uuid);
			}

			await _socket.ConnectAsync();
		}
 private void openDeviceConnection(BluetoothDevice btDevice)
 {
     try
     {
         mSocket = btDevice.CreateRfcommSocketToServiceRecord(getUUIDFromString());
         mSocket.Connect();
         mStream = mSocket.InputStream;
         mReader = new InputStreamReader(mStream);
     }
     catch (IOException e)
     {
         throw e;
     }
 }
Example #7
0
        public bool StartPrint(string text,int noofcopy,ref string errmsg)
        {
            bool isPrinted = false;
            mBluetoothAdapter=null;
            mmSocket=null;
            mmDevice = null;
            FindBTPrinter ();
            if (mmDevice != null) {
                isPrinted =PrintToDevice (text, noofcopy);
            }
            errmsg = msg;

            return isPrinted;
        }
 public void Disconnect()
 {
     if (this.socket != null)
     {
         try
         {
             this.socket.Close();
             this.socket = null;
         }
         catch (Java.IO.IOException ex)
         {
             Log.Error("BluetoothSocket.Close()", ex.Message);
         }
     }
 }
		/// <summary>
		///     Disconnects this instance.
		/// </summary>
		public void Disconnect()
		{
			if (_socket != null)
			{
				try
				{
					_socket.Close();
					_socket = null;
				}
				catch (IOException ex)
				{
					Log.Error("BluetoothSocket.Close()", ex.Message);
				}
			}
		}
Example #10
0
        public void Connect()
        {
            BluetoothDevice device = mBluetoothAdapter.GetRemoteDevice(address);
            System.Console.WriteLine("Conexion en curso" + device);
            mBluetoothAdapter.CancelDiscovery();
            try
            {
                btSocket = device.CreateRfcommSocketToServiceRecord(MY_UUID);
                btSocket.Connect();
                System.Console.WriteLine("Conexion Correcta");
            }
            catch (System.Exception e)
            {
                Console.WriteLine(e.Message);
                try
                {
                    btSocket.Close();
                }
                catch (System.Exception)
                {
                    System.Console.WriteLine("Imposible Conectar");
                }
                System.Console.WriteLine("Socket Creado");
            }
            beginListenForData();

            var ac = FindViewById<Button>(Resource.Id.ac);
            var kapa = FindViewById<Button>(Resource.Id.kapa);
            dataToSend = new Java.Lang.String("1");

            ac.Click += delegate
            {
                dataToSend = new Java.Lang.String("1");
                writeData(dataToSend);

            };
            kapa.Click += delegate
            {
                dataToSend = new Java.Lang.String("2");
                writeData(dataToSend);

            };

            writeData(dataToSend);
        }
Example #11
0
        //--------------------------------------------------------------
        // CONSTRUCTORS
        //--------------------------------------------------------------
        public ConnectThread(BluetoothDevice device, BluetoothManager service)
        {
            _device = device;
            _service = service;
            BluetoothSocket tmp = null;

            // Get a BluetoothSocket for a connection with the
            // given BluetoothDevice
            try
            {
                tmp = device.CreateRfcommSocketToServiceRecord(BluetoothManager.MyUUID);
            }
            catch(Java.IO.IOException e)
            {
                Log.Error(BluetoothManager.Tag, "create() failed", e);
            }
            _socket = tmp;
        }
        public async Task<DeviceConnectionResponse> Connect()
        {
            if (this.socket == null)
            {
                Java.Util.UUID uuid = Java.Util.UUID.FromString("00001101-0000-1000-8000-00805F9B34FB");
                this.socket = this.device.CreateRfcommSocketToServiceRecord(uuid);
            }

            try
            {
                await this.socket.ConnectAsync();
                return DeviceConnectionResponse.Success;
            }
            catch (Java.IO.IOException ex)
            {
                Log.Error ("BluetoothSocket.Connect()", ex.Message);
                return DeviceConnectionResponse.Failure(
                    new DeviceConnectionException(this, "BluetoothSocket.ConnectAsync()", ex));
            }
        }
		/// <summary>
		/// Connect to the EV3 brick.
		/// </summary>
		public async Task ConnectAsync()
		{
			BluetoothAdapter adapter = BluetoothAdapter.DefaultAdapter;
			if(adapter == null)
				throw new Exception("No Bluetooth adapter found");

			if(!adapter.IsEnabled)
				throw new Exception("Bluetooth adapter is not enabled");

			BluetoothDevice device = (from bd in adapter.BondedDevices where bd.Name == _deviceName select bd).FirstOrDefault();
			if(device == null)
				throw new Exception("LEGO EV3 brick named '" + _deviceName + "' not found.");

			_socket = device.CreateRfcommSocketToServiceRecord(UUID.FromString("00001101-0000-1000-8000-00805f9b34fb"));
			await _socket.ConnectAsync();

			_tokenSource = new CancellationTokenSource();

			Task t = Task.Factory.StartNew(async () =>
			{
				while(!_tokenSource.IsCancellationRequested)
				{
					Stream stream = _socket.InputStream;

					// if the stream is valid and ready
					if(stream != null && stream.CanRead)
					{
						await stream.ReadAsync(_sizeBuffer, 0, _sizeBuffer.Length);

						short size = (short)(_sizeBuffer[0] | _sizeBuffer[1] << 8);
						if(size == 0)
							return;

						byte[] report = new byte[size];
						await stream.ReadAsync(report, 0, report.Length);
						if (ReportReceived != null)
							ReportReceived(this, new ReportReceivedEventArgs { Report = report });
					}
				}
			}, _tokenSource.Token, TaskCreationOptions.LongRunning, TaskScheduler.Current);
		}
Example #14
0
		public void Connect() {
			BluetoothDevice device = mBluetoothAdapter.GetRemoteDevice(address);
			System.Console.WriteLine("Conexion en curso" + device);
			mBluetoothAdapter.CancelDiscovery();
			try {
				btSocket = device.CreateRfcommSocketToServiceRecord(MY_UUID);
				btSocket.Connect();
				System.Console.WriteLine("Conexion Correcta");
			} catch (System.Exception e) {
				Console.WriteLine (e.Message);
				try {
					btSocket.Close();
				} catch (System.Exception) {
					System.Console.WriteLine("Imposible Conectar");
				}
				System.Console.WriteLine("Socket Creado");
			}
			beginListenForData();
			dataToSend = new Java.Lang.String("e");
			writeData(dataToSend);
		}
Example #15
0
        public void connected(BluetoothSocket socket, BluetoothDevice device, String socketType)
        {
            lock (mutex) {
                if (_connectThread != null) {

                    _connectThread.cancel ();
                    _connectThread = null;
                }

                if (_connectedThread != null) {

                    _connectedThread.cancel ();
                    _connectedThread = null;
                }

                if (_secureAcceptThread != null) {

                    _secureAcceptThread.cancel ();
                    _secureAcceptThread = null;
                }

                if (_insecureAcceptThread != null) {

                    _insecureAcceptThread.cancel ();
                    _insecureAcceptThread = null;
                }

                _connectedThread = new ConnectedThread (socket, socketType);
                //_connectThread.start ();

                Message msg = _handler.ObtainMessage (Utility.MESSAGE_DEVICE_NAME);
                Bundle bundle = new Bundle ();
                bundle.PutString (Utility.DEVICE_NAME, device.Name);
                msg.Data = bundle;
                _handler.SendMessage (msg);

                setState (STATE_CONNECTED);
            }
        }
Example #16
0
        //--------------------------------------------------------------
        // CONSTRUCTORS
        //--------------------------------------------------------------
        public ConnectedThread(BluetoothSocket socket, BluetoothManager service)
        {
            Log.Debug(BluetoothManager.Tag, "Create ConnectedThread: ");
            _socket = socket;
            _service = service;
            Stream tempIn = null;
            Stream tempOut = null;

            // Get the BluetoothSocket input and output streams
            try
            {
                tempIn = socket.InputStream;
                tempOut = socket.OutputStream;
            }
            catch(Java.IO.IOException e)
            {
                Log.Error(BluetoothManager.Tag, "Temp sockets not created", e);
            }

            _inStream = tempIn;
            _outStream = tempOut;
        }
Example #17
0
        public void Cancel()
        {
            _continue = false;
            if(_socket != null && !_success) // if it is a success we are trying to abort this thread so no need to wait
            {
                try
                {
                    _socket.Close();
                    _socket = null;
                }
                catch(Java.IO.IOException e)
                {
                    Log.Error(BluetoothManager.Tag, "Close() of connect socket failed", e);
                }

                // Wait for the end of the thread
                while(!_end)
                {
                    Thread.Sleep(10);
                }
            }
        }
			public ConnectThread(BluetoothChatService chatService, BluetoothDevice device, bool secure)
			{
			    this.chatService = chatService;
			    mmDevice = device;
				BluetoothSocket tmp = null;
				mSocketType = secure ? "Secure" : "Insecure";

				// Get a BluetoothSocket for a connection with the
				// given BluetoothDevice
				try
				{
					if (secure)
					{
						tmp = device.CreateRfcommSocketToServiceRecord(MY_UUID_SECURE);
					}
					else
					{
						tmp = device.CreateInsecureRfcommSocketToServiceRecord(MY_UUID_INSECURE);
					}
				}
				catch (IOException e)
				{
					Log.E(TAG, "Socket Type: " + mSocketType + "create() failed", e);
				}
				mmSocket = tmp;
			}
		/// <summary>
		/// Start the ConnectedThread to begin managing a Bluetooth connection </summary>
		/// <param name="socket">  The BluetoothSocket on which the connection was made </param>
		/// <param name="device">  The BluetoothDevice that has been connected </param>
		public void Connected(BluetoothSocket socket, BluetoothDevice device, string socketType)
		{
		    lock (this)
		    {
		        if (D)
		        {
		            Log.D(TAG, "connected, Socket Type:" + socketType);
		        }

		        // Cancel the thread that completed the connection
		        if (mConnectThread != null)
		        {
		            mConnectThread.Cancel();
		            mConnectThread = null;
		        }

		        // Cancel any thread currently running a connection
		        if (mConnectedThread != null)
		        {
		            mConnectedThread.Cancel();
		            mConnectedThread = null;
		        }

		        // Cancel the accept thread because we only want to connect to one device
		        if (mSecureAcceptThread != null)
		        {
		            mSecureAcceptThread.Cancel();
		            mSecureAcceptThread = null;
		        }
		        if (mInsecureAcceptThread != null)
		        {
		            mInsecureAcceptThread.Cancel();
		            mInsecureAcceptThread = null;
		        }

		        // Start the thread to manage the connection and perform transmissions
		        mConnectedThread = new ConnectedThread(this, socket, socketType);
		        mConnectedThread.Start();

		        // Send the name of the connected device back to the UI Activity
		        Message msg = mHandler.ObtainMessage(global::BluetoothChat.BluetoothChat.MESSAGE_DEVICE_NAME);
		        Bundle bundle = new Bundle();
		        bundle.PutString(global::BluetoothChat.BluetoothChat.DEVICE_NAME, device.GetName());
		        msg.SetData(bundle);
		        mHandler.SendMessage(msg);

		        State = STATE_CONNECTED;
		    }
		}
			public ConnectedThread (BluetoothSocket socket, BluetoothChatService service)
			{
				Log.Debug (TAG, "create ConnectedThread: ");
				mmSocket = socket;
				_service = service;
				Stream tmpIn = null;
				Stream tmpOut = null;
	
				// Get the BluetoothSocket input and output streams
				try {
					tmpIn = socket.InputStream;
					tmpOut = socket.OutputStream;
				} catch (Java.IO.IOException e) {
					Log.Error (TAG, "temp sockets not created", e);
				}
	
				mmInStream = tmpIn;
				mmOutStream = tmpOut;
			}
			public ConnectThread (BluetoothDevice device, BluetoothChatService service)
			{
				mmDevice = device;
				_service = service;
				BluetoothSocket tmp = null;
				
				// Get a BluetoothSocket for a connection with the
				// given BluetoothDevice
				try {
					tmp = device.CreateRfcommSocketToServiceRecord (MY_UUID);
				} catch (Java.IO.IOException e) {
					Log.Error (TAG, "create() failed", e);
				}
				mmSocket = tmp;
			}
		public void Connected (BluetoothSocket socket, BluetoothDevice device)
		{
			if (Debug)
				Log.Debug (TAG, "connected");
	
			// Cancel the thread that completed the connection
			if (connectThread != null) {
				connectThread.Cancel ();
				connectThread = null;
			}
	
			// Cancel any thread currently running a connection
			if (connectedThread != null) {
				connectedThread.Cancel ();
				connectedThread = null;
			}
	
			// Cancel the accept thread because we only want to connect to one device
			if (acceptThread != null) {
				acceptThread.Cancel ();
				acceptThread = null;
			}
			
			// Start the thread to manage the connection and perform transmissions
			connectedThread = new ConnectedThread (socket, this);
			connectedThread.Start ();
	
			// Send the name of the connected device back to the UI Activity
			var msg = _handler.ObtainMessage (BluetoothChat.MESSAGE_DEVICE_NAME);
			Bundle bundle = new Bundle ();
			bundle.PutString (BluetoothChat.DEVICE_NAME, device.Name);
			msg.Data = bundle;
			_handler.SendMessage (msg);
	
			SetState (STATE_CONNECTED);
		}
        /// Start the ConnectedThread to begin managing a Bluetooth connection
        public void Connected(BluetoothSocket socket, BluetoothDevice device, bool initiator)
        {
            lock (_locker)
            {
                #if DEBUG
                Log.Debug (Tag, "Connected");
                #endif

                // Cancel all the threads
                stopThreads();

                // Set the address of the device we are connected to
                _deviceAddress = device.Address;

                // Start the thread to manage the connection and perform transmissions
                _connectedThread = new ConnectedThread (socket, this);
                _connectedThread.Start ();

                if(initiator)
                    setState (StateEnum.Connected, (int) Network.ConnectionRole.Master);
                else
                    setState (StateEnum.Connected, (int) Network.ConnectionRole.Slave);
            }
        }
Example #24
0
 private bool TrytoConnect(BluetoothSocket mmSocket)
 {
     bool TrytoConnect = true;
     int count = 0;
     while (TrytoConnect) {
         try {
             Thread.Sleep(400);
             mmSocket.Connect ();
             TrytoConnect = false;
         } catch {
             count += 1;
             if (count==5)
                 TrytoConnect = false;
         }
     }
     return !TrytoConnect;
 }
			public ConnectedThread(BluetoothChatService chatService, BluetoothSocket socket, string socketType)
			{
				Log.D(TAG, "create ConnectedThread: " + socketType);
			    this.chatService = chatService;
			    mmSocket = socket;
				InputStream tmpIn = null;
				OutputStream tmpOut = null;

				// Get the BluetoothSocket input and output streams
				try
				{
					tmpIn = socket.GetInputStream();
					tmpOut = socket.GetOutputStream();
				}
				catch (IOException e)
				{
					Log.E(TAG, "temp sockets not created", e);
				}

				mmInStream = tmpIn;
				mmOutStream = tmpOut;
			}
Example #26
0
 public async Task Disconnect()
 {
     running = false;
     if (reader != null)
     {
         reader.Close();
         reader = null;
     }
     if (writer != null)
     {
         writer.Close();
         writer = null;
     }
     if (bluetoothSocket != null)
     {
         try
         {
             bluetoothSocket.Close();
         }
         catch (Exception ex)
         {
             System.Diagnostics.Debug.WriteLine(ex.Message);
         }
         bluetoothSocket = null;
     }
 }
Example #27
0
 private async void PollObd()
 {
     try
     {
         string s;
         if (simulatormode)
             s = "SIMULATOR12345678";
         else
             s = await GetVIN();
         lock (_lock)
         {
             data["vin"] = s;
         }
         while (true)
         {
             foreach (var cmd in piDs.Keys)
             {
                 var key = piDs[cmd];
                 if (simulatormode)
                     s = ObdShare.ObdUtil.GetEmulatorValue(cmd);
                 else
                     s = await RunCmd(cmd);
                 if (s != "ERROR")
                     lock (_lock)
                     {
                         data[key] = s;
                     }
                 if (!running)
                     return;
             }
             await Task.Delay(Interval);
         }
     }
     catch (Exception ex)
     {
         System.Diagnostics.Debug.WriteLine(ex.Message);
         running = false;
         if (reader != null)
         {
             reader.Close();
             reader = null;
         }
         if (writer != null)
         {
             writer.Close();
             writer = null;
         }
         if (bluetoothSocket != null)
         {
             bluetoothSocket.Close();
             bluetoothSocket = null;
         }
     }
 }
Example #28
0
        public string OpenBTAndPrintTest(BluetoothSocket mmSocket,BluetoothDevice mmDevice )
        {
            string msg = "";

            BluetoothMiniTest (mmSocket, mmDevice);
            return msg;
        }
Example #29
0
        public async Task<bool> Init(bool simulatormode = false)
        {
            running = true;
            //initialize _data
            data = new Dictionary<string, string> {{"vin", DefValue}};
            //VIN
            piDs = ObdShare.ObdUtil.GetPIDs();
            foreach (var v in piDs.Values)
            {
                data.Add(v, DefValue);
            }

            this.simulatormode = simulatormode;
            if (simulatormode)
            {
                return true;
            }

            bluetoothAdapter = BluetoothAdapter.DefaultAdapter;
            if (bluetoothAdapter == null)
            {
                System.Diagnostics.Debug.WriteLine("Bluetooth is not available");
                return false;
            }
            try
            {
                var ba = bluetoothAdapter.BondedDevices;
                foreach (var bd in ba)
                {
                    if (bd.Name.ToLower().Contains("obd"))
                        bluetoothDevice = bd;
                }
                if (bluetoothDevice == null)
                {
                    return false;
                }
                bluetoothSocket = bluetoothDevice.CreateRfcommSocketToServiceRecord(SppUuid);

                await bluetoothSocket.ConnectAsync();
                connected = true;
            }
            catch (Java.IO.IOException)
            {
                // Close the socket
                try
                {
                    connected = false;
                    bluetoothSocket.Close();
                }
                catch (Java.IO.IOException)
                {
                }
                catch (Exception)
                {
                }

                return false;
            }
            catch (Exception)
            {
            }
            if (connected)
            {
                reader = bluetoothSocket.InputStream;
                writer = bluetoothSocket.OutputStream;

                string s;
                s = await SendAndReceive("ATZ\r");
                s = await SendAndReceive("ATE0\r");
                s = await SendAndReceive("ATL1\r");
                s = await SendAndReceive("ATSP00\r");
                
                PollObd();
                
                return true;
            }
            else
                return false;
        }
Example #30
0
        public string PrintInvSumm(BluetoothSocket mmSocket,BluetoothDevice mmDevice,DateTime printDate1,DateTime printDate2)
        {
            msg = "";
            Stream mmOutputStream;
            try {
                UUID uuid = UUID.FromString ("00001101-0000-1000-8000-00805F9B34FB");
                mmSocket = mmDevice.CreateInsecureRfcommSocketToServiceRecord (uuid);
                if (mmSocket == null) {
                    msg = "Error creating sockect";
                    return msg;
                }
                if (mmDevice.BondState == Bond.Bonded) {
                    mmSocket.Connect ();
                    Thread.Sleep (300);
                    mmOutputStream = mmSocket.OutputStream;
                    byte[] charfont;
                    if (apara.PaperSize == "58mm") {
                        charfont = new Byte[] { 27, 33, 1 }; //Char font 9x17
                        mmOutputStream.Write (charfont, 0, charfont.Length);
                    }

                    if (apara.PaperSize == "80mm") {
                        charfont = new Byte[] { 27, 33, 0 }; //Char font 12x24
                        mmOutputStream.Write (charfont, 0, charfont.Length);
                    }

                    string text = GetInvoiceSumm (printDate1, printDate2);
                    //byte[] cc = ASCIIEncoding.ASCII.GetBytes(text);

                    byte[] cc = Encoding.GetEncoding ("GB18030").GetBytes (text);
                    int rem;
                    int result = Math.DivRem (cc.Length, 2048, out rem);
                    int pos = 0;
                    for (int line = 0; line < result; line++) {
                        IsStreamCanWrite (mmOutputStream);
                        mmOutputStream.Write (cc, pos, 2048);
                        pos += 2048;
                    }
                    if (rem > 0)
                        mmOutputStream.Write (cc, pos, rem);

                    //mmOutputStream.Write (cc, 0, cc.Length);
                    Thread.Sleep (3000);
                    mmOutputStream.Flush ();
                    mmOutputStream.Close ();
                    mmSocket.Close ();
                }

            } catch (Exception ex) {
                msg = ex.Message;
            }

            return msg;
        }