示例#1
0
 protected override void AfterMyWorkStateChanged(object sender, EventArgs e)
 {
     if (myWorkState)
     {
         AiProtocol aiProtocol = new AiProtocol()
         {
             CaseNo = GateWaySetting.CaseNo, APISetting = APISetting
         };
         AbsProtocols.Add(aiProtocol);
         StateProtocol stateProtocol = new StateProtocol()
         {
             CaseNo = GateWaySetting.CaseNo, APISetting = APISetting
         };
         AbsProtocols.Add(stateProtocol);
         ReadThread = new Thread(Analysis);
         ReadThread.Start();
     }
     else
     {
         if (ReadThread != null)
         {
             ReadThread.Abort();
         }
     }
 }
示例#2
0
        private void Read()
        {
            try
            {
                StreamReader sReader = new StreamReader(Client.GetStream());

                string msg = "";

                while (true)
                {
                    msg = sReader.ReadLine();

                    Console.WriteLine("{0}", msg);
                }
            }
            catch (Exception e)
            {
                Console.WriteLine(e.Message);
            }
            finally
            {
                Client?.Close();
                ReadThread.Abort();
            }
        }
示例#3
0
        // null-safe & exception-safe: 2019-1-8
        private bool EndListen()
        {
            // catch null here.
            if (ReadThread == null)
            {
                Debugger.Log("ReadThread is null.", Debugger.LogLevel.WARN);
                return(false);
            }

            // catch other exceptions here.
            try
            {
                ReadThread.Abort();
                ReadThread = null;

                Debugger.Log("Successfully finished listening.", Debugger.LogLevel.INFO);

                Listening = false;
                return(true);
            }
            catch (Exception e)
            {
                Debugger.Log("Exception while aborting thread: \n" + e.ToString(), Debugger.LogLevel.ERROR);
                return(false);
            }
        }
示例#4
0
        // null-safe & exception-safe: 2019-1-8
        private bool StartListen()
        {
            if (ReadThread == null)
            {
                Debugger.Log("ReadThread is null.", Debugger.LogLevel.WARN);
                return(false);
            }
            if (Listening)
            {
                Debugger.Log("ReadThread already running.", Debugger.LogLevel.INFO);
                return(false);
            }

            try
            {
                ReadThread.Start();

                Debugger.Log("Successfully started listening.", Debugger.LogLevel.INFO);

                Listening = true;
                return(true);
            }
            catch (Exception e)
            {
                Debugger.Log("Exception while starting ReadThread: \n" + e.ToString(), Debugger.LogLevel.WARN);
                return(false);
            }
        }
示例#5
0
        public override void Connect(ServerInfo serverInfo)
        {
            if (Connected)
            {
                throw new ProtocolException("Connection error: Already connected to server.");
            }

            foreach (var modAPI in ModAPIs)
            {
                modAPI.OnConnect(serverInfo);
            }


            // -- Connect to server.
            Stream.Connect(serverInfo.Address.IP, serverInfo.Address.Port);

            // -- Begin data reading.
            if (ReadThread != null && ReadThread.IsRunning)
            {
                throw new ProtocolException("Connection error: Thread already running.");
            }
            else
            {
                ReadThread = ThreadWrapper.Create(ReadCycle);
                ReadThread.IsBackground = true;
                ReadThread.Name         = "PacketReaderThread";
                ReadThread.Start();
            }
        }
示例#6
0
        /// <summary>
        /// Initializes the message queues, read and write thread
        /// </summary>
        public IrcConnection()
        {
#if LOG4NET
            Logger.Init();
            Logger.Main.Debug("IrcConnection created");
#endif
            _SendBuffer[Priority.High]        = Queue.Synchronized(new Queue());
            _SendBuffer[Priority.AboveMedium] = Queue.Synchronized(new Queue());
            _SendBuffer[Priority.Medium]      = Queue.Synchronized(new Queue());
            _SendBuffer[Priority.BelowMedium] = Queue.Synchronized(new Queue());
            _SendBuffer[Priority.Low]         = Queue.Synchronized(new Queue());

            // setup own callbacks
            OnReadLine        += new ReadLineEventHandler(_SimpleParser);
            OnConnectionError += new EventHandler(_OnConnectionError);

            _ReadThread       = new ReadThread(this);
            _WriteThread      = new WriteThread(this);
            _IdleWorkerThread = new IdleWorkerThread(this);

            Assembly     assm      = Assembly.GetAssembly(this.GetType());
            AssemblyName assm_name = assm.GetName(false);

            AssemblyProductAttribute pr = (AssemblyProductAttribute)assm.GetCustomAttributes(typeof(AssemblyProductAttribute), false)[0];

            _VersionNumber = assm_name.Version.ToString();
            _VersionString = pr.Product + " " + _VersionNumber;
        }
示例#7
0
 protected void RestartWorkingThread()
 {
     readThread = new ReadThread(this);
     readThread.Start();
     while (!readThread.IsAlive)
     {
     }                               // Busy waiting
 }
示例#8
0
 protected void KillWorkingThread()
 {
     if (readThread != null)
     {
         readThread.StopThread();
         readThread = null;
     }
 }
示例#9
0
 //Запуск потоков
 public void StartThreads()
 {
     StartLog("Запуск потоков").Run(() =>
     {
         ReadThread.StartProcess();
         UserThread.StartProcess();
         ArchiveThread.StartProcess();
     });
 }
示例#10
0
 //Останов потоков
 public void StopThreads()
 {
     StartLog("Остановка потоков").Run(() =>
     {
         ReadThread.StopProcess();
         UserThread.StartProcess();
         ArchiveThread.StartProcess();
     });
 }
示例#11
0
 public void Cancel()
 {
     ReaderRunning = false;
     ReadThread.Abort();
     if (OscPacketIO.IsOpen())
     {
         OscPacketIO.Close();
     }
 }
示例#12
0
        /// <summary>
        /// Connects this WebSocketClient to the WebSocket Server.
        /// </summary>
        /// <returns>Task.</returns>
        /// <exception cref="Exception">If the WebSocket Connection is already Connected or Connecting.</exception>
        public async Task ConnectAsync()
        {
            if (Status == WebSocketState.Open || Status == WebSocketState.Connecting)
            {
                throw new Exception("Websocket already Connected or Connecting");
            }
            await ClientWebSocket.ConnectAsync(Uri, CancellationToken);

            Exit = false;
            Open?.Invoke(this, EventArgs.Empty);
            ReadThread.Start();
        }
示例#13
0
        public static void Main(string[] args)
        {
            var writeThread  = new WriteThread <SampleData>(WriteBlockingCollection, "Output.txt"); //Create a object for write thread
            var writeThread1 = new Thread(writeThread.WriteData);                                   //Create write thread

            writeThread1.Start();                                                                   //start the write thread

            var readThread  = new ReadThread <SampleData>(ReadBlockingCollection, "Output.txt");    //Create a object for write thread
            var readThread1 = new Thread(readThread.ReadItem);                                      //Create read thread

            readThread1.Start();                                                                    //start read thread

            var random       = new Random(50000);
            int count        = 0;
            int totalObjects = 50000;
            var writeTask    = Task.Run(() =>
            {
                //create some random objects and add them to write queue
                while (count < totalObjects)
                {
                    WriteBlockingCollection.Add(new SampleData(random.Next(), $"Random Data {random.Next()}",
                                                               DateTime.Now.ToString(CultureInfo.InvariantCulture)));
                    count++;
                }
                //End adding new items to queue thus mentioning end of write operation
                WriteBlockingCollection.CompleteAdding();
                while (WriteBlockingCollection.Count > 0)
                {
                    Thread.Sleep(100);
                    //Just to make sure all are read
                }
                //Set this so that read thread can stop further reading from file
                Running = false;
            });
            var readTask = Task.Run(() =>
            {
                var readCount = 0;
                foreach (var item in ReadBlockingCollection.GetConsumingEnumerable())
                {
                    Console.WriteLine(item.ToString());
                    readCount++;
                }
                //Just verify total count should be
                Console.WriteLine($"Read Count From Read Thread :  {readCount}");
                Debug.Assert(totalObjects == count, "Either File is appended with new values or something wrong, delete Output.txt and recreate it");
            });

            Task.WaitAll(writeTask, readTask);
            writeThread1.Join();
            readThread1.Join();
            Console.WriteLine("Reading and writing from file Completed!. Press any key to continue");
            Console.ReadLine();
        }
示例#14
0
        /**
         * Clear socket and threads
         */
        private void Clear()
        {
            if (ReadThread.IsAlive)
            {
                ReadThread.Abort();
            }

            if (WriteThread.IsAlive)
            {
                WriteThread.Abort();
            }

            Socket.Close();
        }
示例#15
0
        public void Close()
        {
            try
            {
                Console.WriteLine($"Goodbye {Username}!");

                TcpClient.Client.Close();
                TcpClient.Close();
                Program.Server.LeaveRoom(Username, Roomname);
                Program.Server.RemoveClient(Username);
                ReadThread.Abort();
            }
            catch (Exception e) {}
        }
示例#16
0
 protected override void AfterMyWorkStateChanged(object sender, EventArgs e)
 {
     if (myWorkState)
     {
         ReadThread = new Thread(SqlRecord);
         ReadThread.Start();
     }
     else
     {
         if (ReadThread != null)
         {
             ReadThread.Abort();
         }
     }
 }
示例#17
0
 private void StopThreads()
 {
     lock (this)
     {
         if (ReadThread != null)
         {
             ReadThread.Abort();
             ReadThread = null;
         }
         if (ReadTriggerThread != null)
         {
             ReadTriggerThread.Abort();
             ReadTriggerThread = null;
         }
     }
 }
示例#18
0
 protected override void AfterMyWorkStateChanged(object sender, EventArgs e)
 {
     if (myWorkState)
     {
         APIMethod.APISetting = APISetting;
         ReadThread           = new Thread(Analysis);
         ReadThread.Start();
     }
     else
     {
         if (ReadThread != null)
         {
             ReadThread.Abort();
         }
     }
 }
示例#19
0
    public static void iceManMinds()
    {
        string FileName            = file;
        long   ThreadReadBlockSize = 50000;
        int    NumberOfThreads     = 4;

        byte[] _inputString;
        var    fi             = new FileInfo(FileName);
        long   totalBytesRead = 0;
        long   fileLength     = fi.Length;
        long   readPosition   = 0L;

        Console.WriteLine("Reading Lines From {0}", FileName);
        var threads   = new Thread[NumberOfThreads];
        var instances = new ReadThread[NumberOfThreads];

        _inputString = new byte[fileLength];
        while (totalBytesRead < fileLength)
        {
            for (int i = 0; i < NumberOfThreads; i++)
            {
                var rt = new ReadThread {
                    StartPosition = readPosition, BlockSize = ThreadReadBlockSize
                };
                instances[i] = rt;
                threads[i]   = new Thread(rt.Read);
                threads[i].Start();
                readPosition += ThreadReadBlockSize;
            }
            for (int i = 0; i < NumberOfThreads; i++)
            {
                threads[i].Join();
            }
            for (int i = 0; i < NumberOfThreads; i++)
            {
                if (instances[i].BlockSize > 0)
                {
                    Array.Copy(instances[i].Output, 0L, _inputString, instances[i].StartPosition,
                               instances[i].BlockSize);
                    totalBytesRead += instances[i].BlockSize;
                }
            }
        }
        string finalString = Encoding.ASCII.GetString(_inputString);

        Console.WriteLine(finalString);    //.Substring(104250000, 50000));
    }
示例#20
0
        /*
         * Kill workingThread; This must be called when closing a device
         */

        protected void KillWorkingThread()
        {
            if (mr1Version && workerThread != null)
            {
                workerThread.StopThread();
                //while (workerThread.IsAlive) { } // Busy waiting
                Log.Info("UsbSerialDevice", "Read Thread stopped.");
                workerThread = null;
            }
            else if (!mr1Version && readThread != null)
            {
                readThread.StopThread();
                //while (readThread.IsAlive) { } // Busy waiting
                Log.Info("UsbSerialDevice", "Read Thread stopped.");
                readThread = null;
            }
            //Thread.Sleep(1000);
        }
示例#21
0
        private void HidDevices_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (HidDevices.SelectedItems.Count < 1)
            {
                return;
            }

            ReadThread_Stop();

            SelectedHid        = UsbHid.HidDevices[HidDevices.Items.IndexOf(HidDevices.SelectedItems[0])];
            SendGroup.Enabled  = !SelectedHid.WriteHandle.IsClosed;
            SendGroup.Enabled &= (SelectedHid.Caps.OutputReport > 0);
            Logs.Text          = "";

            if (!ReadThread.IsBusy)
            {
                ReadThread.RunWorkerAsync();
            }
        }
示例#22
0
        public TCPServer()
        { // start constructor
            dB = new LoginDatabase();

            listener = new TcpListener(4300);
            listener.Start();

            movesMade = new Queue <string>();

            dB.connectToDatabase();

            Console.Write("Press Enter to start the server:  ");
            Console.Read();

            // counting by t
            for (int t = 0; t < numberPlayers; ++t)
            { // start for loop
                Socket sock = listener.AcceptSocket();
                Console.WriteLine("Player Socket has accepted the socket");

                NetworkStream nws = new NetworkStream(sock);
                //StreamReader reader = new StreamReader(nws);
                // StreamWriter writer = new StreamWriter(nws);
                //writer.AutoFlush = true;

                // Console.WriteLine("stream created");

                activePlayers[t]           = new PlayerSocket(nws, sock);
                activePlayers[t].connected = true;

                // Console.WriteLine(" connected true");

                // string data = activePlayers[t].playerReader.ReadLine();
                // Console.Write(data);

                // creates a ReadThread, passes in the player value t
                ReadThread thread = new ReadThread(t);

                activePlayers[t].psThread = new Thread(new ThreadStart(thread.Service));
                activePlayers[t].psThread.Start();
                Console.Write("bottom of for loop!\n");
            } // end for loop
        }     // end constructor
示例#23
0
 //Открытие потоков
 public void OpenThreads(double periodSeconds, double lateSeconds)
 {
     StartLog("Открытие потоков").Run(() =>
     {
         ReadThread    = OpenRealTimeThread(1, "Source", periodSeconds, lateSeconds);
         var aproxy    = new QueuedProxyConnect("ArchiveProxy");
         ReturnConnect = new ProxyConnect("UserProxy");
         ReadThread.Proxies.Add(aproxy.Code, aproxy);
         ReadThread.Proxies.Add(ReturnConnect.Code, ReturnConnect);
         foreach (var s in SchemeSources.Values)
         {
             var con = (IReadingConnect)ReadThread.AddConnect(s.Code);
             aproxy.InConnects.Add(s.Code, con);
             ReturnConnect.InConnects.Add(s.Code, con);
         }
         ArchiveThread = OpenProxyThread(2, "Archive", aproxy);
         ArchiveThread.AddConnect("Archive");
         ArchiveThread.Proxies.Add("ArchiveProxy", aproxy);
         UserThread = OpenRealTimeThread(3, "Return", periodSeconds);
         UserThread.Proxies.Add(ReturnConnect.Code, ReturnConnect);
     });
 }
示例#24
0
        /// <summary>
        /// Verwendete Ressourcen bereinigen.
        /// </summary>
        /// <param name="disposing">True, wenn verwaltete Ressourcen gelöscht werden sollen; andernfalls False.</param>
        protected override void Dispose(bool disposing)
        {
            if (disposing && (components != null))
            {
                components.Dispose();
            }


            if (ReadThread != null && ReadThread.IsAlive)
            {
                ThreadActive = false;
                ReadThread.Join(50);
                ReadThread.Abort();
            }

            if (ShmemChannel != null)
            {
                ShmemChannel.Unregister();
            }

            base.Dispose(disposing);
        }
示例#25
0
        /*
         * Restart workingThread if it has been killed before
         */

        protected void RestartWorkingThread()
        {
            if (mr1Version && workerThread == null)
            {
                workerThread = new WorkerThread(this);
                workerThread.Start();
                workerThread.SetCallback(readCallback);
                while (!workerThread.IsAlive)
                {
                }                                 // Busy waiting
                Log.Info("UsbSerialDevice", "Read Thread started.");
            }
            else if (!mr1Version && readThread == null)
            {
                readThread = new ReadThread(this);
                readThread.Start();
                readThread.SetCallback(readCallback);
                while (!readThread.IsAlive)
                {
                }                               // Busy waiting
                Log.Info("UsbSerialDevice", "Read Thread started.");
            }
        }
示例#26
0
        private void FinishConnect(IAsyncResult result)
        {
            try
            {
                var beginClient = (TcpClient)result.AsyncState;
                if (beginClient == null)
                {
                    Close();
                    return;
                }
                beginClient.EndConnect(result);
                if (beginClient.Connected)
                {
                    // 启动读取和写入线程。
                    _readThread = new ReadThread(this, beginClient, _msgQueue);
                    _readThread.Start();

                    _writeThread = new WriteThread(this, beginClient, _msgQueue);
                    _writeThread.Start();

                    // 已经连接上。
                    Status  = SocketStatus.Connected;
                    _client = beginClient;
                }
                else
                {
                    // 未连接成功,关闭当前连接。
                    Close();
                }
            }
            catch (Exception e)
            {
                MyLog.ErrorAsync(Tag, string.Format("end connect error: {0}\n{1}", e.Message, e.StackTrace));
                Close();
            }
        }
        public void ReadFromPrinter(ReadThread readThreadHolder)
		{
			string dataLastRead = string.Empty;

			Thread.CurrentThread.CurrentCulture = CultureInfo.InvariantCulture;
			timeSinceLastReadAnything.Restart();
			// we want this while loop to be as fast as possible. Don't allow any significant work to happen in here
			while (CommunicationState == CommunicationStates.AttemptingToConnect
				|| (PrinterIsConnected && serialPort != null && serialPort.IsOpen && !Disconnecting && readThreadHolder.IsCurrentThread()))
			{
				if (PrinterIsPrinting
					&& PrinterIsConnected
					&& CommunicationState != CommunicationStates.PrintingFromSd)
				{
					TryWriteNextLineFromGCodeFile();
				}

				try
				{
					while (serialPort != null
						&& serialPort.BytesToRead > 0
						&& readThreadHolder.IsCurrentThread())
					{
						lock (locker)
						{
							string allDataRead = serialPort.ReadExisting();
							//Debug.Write("r: " + allDataRead);
							dataLastRead += allDataRead.Replace('\r', '\n');
							do
							{
								int returnPosition = dataLastRead.IndexOf('\n');

								// Abort if we're AttemptingToConnect, no newline was found in the accumulator string and there's too many non-ascii chars
								if (this.communicationState == CommunicationStates.AttemptingToConnect && returnPosition < 0)
								{
									int totalInvalid = dataLastRead.Count(c => c == '?');
									if (totalInvalid > MAX_INVALID_CONNECTION_CHARS)
									{
										AbortConnectionAttempt("Invalid printer response".Localize(), false);
									}
								}

								if (returnPosition < 0)
								{
									// there is no return keep getting characters
									break;
								}

								if (dataLastRead.Length > 0)
								{
									lastLineRead = dataLastRead.Substring(0, returnPosition);
									dataLastRead = dataLastRead.Substring(returnPosition + 1);

									// process this command
									{
										StringEventArgs currentEvent = new StringEventArgs(lastLineRead);
										if (PrinterIsPrinting)
										{
											CommunicationUnconditionalFromPrinter.CallEvents(this, new StringEventArgs("{0} [{1:0.000}]\n".FormatWith(lastLineRead, timeSinceStartedPrint.Elapsed.TotalSeconds)));
										}
										else
										{
											CommunicationUnconditionalFromPrinter.CallEvents(this, currentEvent);
										}

										FoundStringEventArgs foundResponse = new FoundStringEventArgs(currentEvent.Data);
										ReadLineStartCallBacks.CheckForKeys(foundResponse);
										ReadLineContainsCallBacks.CheckForKeys(foundResponse);

										if (foundResponse.SendToDelegateFunctions)
										{
											ReadLine.CallEvents(this, currentEvent);
										}
									}

									// If we've encountered a newline character and we're still in .AttemptingToConnect
									if (CommunicationState == CommunicationStates.AttemptingToConnect)
									{
										// TODO: This is an initial proof of concept for validating the printer response after DTR. More work is
										// needed to test this technique across existing hardware and/or edge cases where this simple approach
										// (initial line having more than 3 non-ASCII characters) may not be adequate or appropriate.
										// TODO: Revise the INVALID char count to an agreed upon threshold
										string[] segments = lastLineRead.Split('?');
										if (segments.Length <= MAX_INVALID_CONNECTION_CHARS)
										{
											CommunicationState = CommunicationStates.Connected;
											// new send any command that initialize this printer
											string connectGCode = ActiveSliceSettings.Instance.GetActiveValue("connect_gcode");
											SendLineToPrinterNow(connectGCode);
										}
										else
										{
											// Force port shutdown and cleanup
											AbortConnectionAttempt("Invalid printer response".Localize(), false);
										}
									}
								}
							} while (true);
						}
						timeSinceLastReadAnything.Restart();
					}

					Thread.Sleep(1);
				}
				catch (TimeoutException e)
				{
					Debug.Print(e.Message);
					GuiWidget.BreakInDebugger();
				}
				catch (IOException e2)
				{
					Debug.Print(e2.Message);
					GuiWidget.BreakInDebugger();
					OnConnectionFailed(null);
				}
				catch (InvalidOperationException ex)
				{
					Debug.Print(ex.Message);
					GuiWidget.BreakInDebugger();
					Debug.WriteLine(ex.Message);
					// this happens when the serial port closes after we check and before we read it.
				}
				catch (UnauthorizedAccessException e3)
				{
					Debug.Print(e3.Message);
					GuiWidget.BreakInDebugger();
					OnConnectionFailed(null);
				}
				catch (Exception e4)
				{
					Debug.Print(e4.Message);
					GuiWidget.BreakInDebugger();
					// Let's track this issue if possible.
					MatterControlApplication.Instance.ReportException(e4, this.GetType().Name, MethodBase.GetCurrentMethod().Name);
				}
			}
		}
示例#28
0
        /// <summary>
        /// Initializes the message queues, read and write thread
        /// </summary>
        public IrcConnection()
        {
            #if LOG4NET
            Logger.Init();
            Logger.Main.Debug("IrcConnection created");
            #endif
            _SendBuffer[Priority.High]        = Queue.Synchronized(new Queue());
            _SendBuffer[Priority.AboveMedium] = Queue.Synchronized(new Queue());
            _SendBuffer[Priority.Medium]      = Queue.Synchronized(new Queue());
            _SendBuffer[Priority.BelowMedium] = Queue.Synchronized(new Queue());
            _SendBuffer[Priority.Low]         = Queue.Synchronized(new Queue());

            // setup own callbacks
            OnReadLine        += new ReadLineEventHandler(_SimpleParser);
            OnConnectionError += new EventHandler(_OnConnectionError);

            _ReadThread  = new ReadThread(this);
            _WriteThread = new WriteThread(this);
            _IdleWorkerThread = new IdleWorkerThread(this);

            Assembly assm = Assembly.GetAssembly(this.GetType());
            AssemblyName assm_name = assm.GetName(false);

            AssemblyProductAttribute pr = (AssemblyProductAttribute)assm.GetCustomAttributes(typeof(AssemblyProductAttribute), false)[0];

            _VersionNumber = assm_name.Version.ToString();
            _VersionString = pr.Product+" "+_VersionNumber;
        }
示例#29
0
 private void Form1_FormClosed(object sender, FormClosedEventArgs e)
 {
     ReadThread.Abort();
     SaveOptions();
     LogLine("Program terminated");
 }
示例#30
0
        /// <summary>
        /// Initializes the message queues, read and write thread
        /// </summary>
        public IrcConnection()
        {
            #if LOG4NET
            Logger.Main.Debug("IrcConnection created");
            #endif

            // setup own callbacks
            OnReadLine        += new ReadLineEventHandler(_SimpleParser);
            OnConnectionError += new EventHandler(_OnConnectionError);

            _ReadThread  = new ReadThread(this);
            _WriteThread = new WriteThread(this);
            _IdleWorkerThread = new IdleWorkerThread(this);

            Assembly assm = Assembly.GetAssembly(this.GetType());
            AssemblyName assm_name = assm.GetName(false);

            AssemblyProductAttribute pr = (AssemblyProductAttribute)assm.GetCustomAttributes(typeof(AssemblyProductAttribute), false)[0];

            _VersionNumber = assm_name.Version.ToString();
            _VersionString = pr.Product+" "+_VersionNumber;
        }
示例#31
0
 private void Start()
 {
     _helloRequester = new ReadThread();
     Debug.Log("start thread");
     _helloRequester.Start();
 }
示例#32
0
        /// <summary>
        /// Initializes the message queues, read and write thread
        /// </summary>
        public IrcConnection()
        {
            ProxyType = ProxyType.None;
            PingTimeout = 300;
            PingInterval = 60;
            IdleWorkerInterval = 60;
            SocketSendTimeout = 600;
            SocketReceiveTimeout = 600;
            Encoding = Encoding.Default;
            AutoRetryLimit = 3;
            AutoRetryDelay = 30;
            SendDelay = 200;
            sendBuffer[Priority.High] = Queue.Synchronized(new Queue());
            sendBuffer[Priority.AboveMedium] = Queue.Synchronized(new Queue());
            sendBuffer[Priority.Medium] = Queue.Synchronized(new Queue());
            sendBuffer[Priority.BelowMedium] = Queue.Synchronized(new Queue());
            sendBuffer[Priority.Low] = Queue.Synchronized(new Queue());

            // setup own callbacks
            OnReadLine += SimpleParser;
            OnConnectionError += _OnConnectionError;

            readThread = new ReadThread(this);
            writeThread = new WriteThread(this);
            idleWorkerThread = new IdleWorkerThread(this);

            Assembly assembly = Assembly.GetAssembly(GetType());
            AssemblyName assemblyName = assembly.GetName(false);

            var pr = (AssemblyProductAttribute)assembly.GetCustomAttributes(typeof(AssemblyProductAttribute), false)[0];

            VersionNumber = assemblyName.Version.ToString();
            VersionString = pr.Product + " " + VersionNumber;
        }
        public bool Connect(string ScannerModel)//Connect to Paired BT Device containing
        {
            try
            {
                BluetoothAdapter.DefaultAdapter.Enable();
                BluetoothAdapter.DefaultAdapter.CancelDiscovery();
            }
            catch (System.Exception) { }
            ScannerModel = ScannerModel.ToLower();
            foreach (BluetoothDevice device in BluetoothAdapter.DefaultAdapter.BondedDevices)
            {
                Log.Info(TAG, "found: " + device.Name);
                MainActivity.onStatusChanged("found: " + device.Name);
                if (device.Name.ToLower().Contains(ScannerModel))
                {
                    if (device != null && Connected == false)
                    {
                        string SPP_UUID = "00001101-0000-1000-8000-00805f9b34fb";
                        bluetoothSocket = device.CreateInsecureRfcommSocketToServiceRecord(Java.Util.UUID.FromString(SPP_UUID));
                        try
                        {
                            bluetoothSocket.Connect();
                        }
                        catch (Java.Lang.Exception Ex)
                        {
                            Toast.MakeText(m_context, Ex.Message.ToString(), ToastLength.Long).Show();
                            MainActivity.onStatusChanged(Ex.Message);
                            try
                            {
                                System.Threading.Thread.Sleep(1000);
                                bluetoothSocket.Connect();
                            }
                            catch (Java.Lang.Exception Ex2)
                            {
                                Connected = false;
                                Toast.MakeText(m_context, Ex2.Message.ToString(), ToastLength.Long).Show();
                                MainActivity.onStatusChanged(Ex2.Message);
                                m_state = eStatus.STATE_NONE;
                            }
                        }
                        if (bluetoothSocket != null && bluetoothSocket.IsConnected)
                        {
                            Toast.MakeText(m_context, "Bluetooth Scanner Connected", ToastLength.Long).Show();
                            Connected = true;
                            // Start the thread to manage the connection and perform transmissions
                            readThread = new ReadThread(bluetoothSocket);
                            readThread.Start();

                            return(true);
                        }
                    }
                    else
                    {
                        Toast.MakeText(m_context, "DEVICE NOT FOUND : " + ScannerModel, ToastLength.Long).Show();
                        Connected = false;
                        m_state   = eStatus.STATE_NONE;
                    }
                }
            }
            return(false);
        }
            /// <summary>
            /// Process a message from the queue (CONNECT, DISCONNECT, SEND or STOP)
            /// </summary>
            /// <param name="msg">The message being delivered by the Looper</param>
            public override void HandleMessage(Message msg)
            {
                string command = msg.Data.GetString(BundleConst.bundleCmdTag);
                Intent statusIntent;
                bool   done = true;

                if (!done)
                {
                    return;
                }

                AppLog.Log("RCS-HandleMessage: " + command);

                try
                {
                    switch (command)
                    {
                    case BundleConst.cmdConnect:                                                                 // Connection request
                        if (serviceContext.serviceState != AppConst.ActivityState.idle && serviceContext.serviceState != AppConst.ActivityState.error)
                        {
                            // If we're already connected, prod the UI with the last reported status
                            serviceContext.serviceState = AppConst.ActivityState.connected;
                            outputStream.Write(promptSequence, 0, promptSequence.Length);                                                      // Try to elicit a response in case we were previously connected.
                            SendData(serviceContext.lastReport);
                            return;
                        }

                        try
                        {
                            string deviceAddr = msg.Data.GetString(BundleConst.bundleAddrTag);                   // Get the Bluetooth device address

                            btDevice = BluetoothAdapter.DefaultAdapter.GetRemoteDevice(deviceAddr);
                            btSocket = btDevice.CreateInsecureRfcommSocketToServiceRecord(AppConst.uuid);
                            btSocket.Connect();                                                             // Connect the socket

                            AppLog.Log("RCS-HandleMessage: " + command + "; connected device " + deviceAddr);

                            inputStream  = Stream.Synchronized(btSocket.InputStream);
                            outputStream = Stream.Synchronized(btSocket.OutputStream);
                            serviceContext.serviceState = AppConst.ActivityState.connected;
                            readThreadObject            = new ReadThread(inputStream);
                            readThread = new System.Threading.Thread(readThreadObject.ReadProc);                             // Start the read thread
                            readThread.Start(serviceContext);
                            outputStream.Write(promptSequence, 0, promptSequence.Length);                                    // Try to elicit a response in case we were previously connected.
                            AppLog.Log("RCS-HandleMessage: " + command + "; created threads");
                        }
                        catch (Throwable e)
                        {
                            try
                            {
                                if (btSocket != null)
                                {
                                    btSocket.Close();
                                }
                            }
                            catch
                            {
                            }

                            AppLog.Log("RCS-HandleMessage: " + command + "; exception: " + e.ToString());
                            done = false;
                        }

                        statusIntent = new Intent(AppConst.rxIntentName);                                         // Send the status to the activity
                        statusIntent.PutExtra(BundleConst.bundleCmdTag, BundleConst.bundleStatusTag);
                        if (done)
                        {
                            serviceContext.serviceState = AppConst.ActivityState.connected;
                        }
                        else
                        {
                            serviceContext.serviceState = AppConst.ActivityState.error;
                        }
                        statusIntent.PutExtra(BundleConst.bundleValTag, (int)serviceContext.serviceState);
                        serviceContext.SendBroadcast(statusIntent);

                        if (!done)
                        {
                            CloseConnection(msg.Arg1);
                        }
                        break;

                    case BundleConst.cmdDisconnect:                                                                      // Disconnect request
                        CloseConnection(msg.Arg1);
                        serviceContext.serviceState = AppConst.ActivityState.idle;
                        statusIntent = new Intent(AppConst.rxIntentName);
                        statusIntent.PutExtra(BundleConst.bundleCmdTag, BundleConst.bundleStatusTag);
                        statusIntent.PutExtra(BundleConst.bundleValTag, (int)serviceContext.serviceState);
                        serviceContext.SendBroadcast(statusIntent);                                                 // Update status
                        break;

                    case BundleConst.cmdSend:                                                                            // Send data
                        if (serviceContext.serviceState == AppConst.ActivityState.connected || serviceContext.serviceState == AppConst.ActivityState.synced)
                        {
                            try
                            {
                                byte[] devCmd;

                                devCmd = msg.Data.GetByteArray(BundleConst.bundleDataTag);
                                outputStream.Write(devCmd, 0, devCmd.Length);
                                AppLog.Log("RCS-HandleMessage: " + command + "; sent: " + devCmd.ToString());
                            }
                            catch (Throwable e)
                            {
                                AppLog.Log("RCS-HandleMessage: " + command + "; exception: " + e.ToString());
                                done = false;
                            }
                        }
                        else
                        {
                            done = false;
                        }

                        if (!done)                                                                                      // Update status on error
                        {
                            statusIntent = new Intent(AppConst.rxIntentName);
                            statusIntent.PutExtra(BundleConst.bundleCmdTag, BundleConst.bundleStatusTag);
                            statusIntent.PutExtra(BundleConst.bundleValTag, (int)AppConst.ActivityState.error);
                            serviceContext.SendBroadcast(statusIntent);
                            CloseConnection(msg.Arg1);
                        }
                        break;
                    }
                }
                catch (Throwable e)
                {
                    AppLog.Log("RCS-HandleMessage: " + command + "; exception: " + e.ToString());
                }
            }