Example #1
0
 public bool connectDevice()
 {
     if (Code == 11)
     {
         return(false);
     }
     try
     {
         string comname = SerialHelper.GetOneCom();
         ReadDone = false;
         if (comname.Length > 0)
         {
             SerialPortFixer.Execute(comname);
             spt = new SerialPortTran(comname, false);
             return(true);
         }
         else
         {
             //throw new Exception("can not found any device connected");
             _tracing.Error("can not found any device connected");
             return(false);
         }
     }
     catch {
         return(false);
     }
 }
Example #2
0
    public void Open()
    {
        lock (portThreadSync)
        {
            lock (threadsync)
            {
                if (!_isAlive)
                {
                    throw new Exception("The port has been disposed;");
                }

                try
                {
                    SerialPortFixer.Execute(_port.PortName);
                }
                catch (Exception ex)
                {
                }
                _port.Open();
                try
                {
                    _internalSerialStream = _port.BaseStream;
                    _port.DiscardInBuffer();
                    _port.DiscardOutBuffer();
                }
                catch (Exception ex)
                {
                    Stream internalSerialStream = _internalSerialStream;
                    if (internalSerialStream == null)
                    {
                        FieldInfo field = typeof(SerialPort).GetField("internalSerialStream", BindingFlags.Instance | BindingFlags.NonPublic);
                        if (field == null)
                        {
                            throw;
                        }
                        else
                        {
                            internalSerialStream = (Stream)field.GetValue(_port);
                        }
                    }
                    logMessage = logMessage + "\nAn error occurred while constructing the serial port adaptor:" + ex.ToString();
                    SafeDisconnect(_port, internalSerialStream);
                    throw;
                }
            }
        }
    }
Example #3
0
        public async void connect()
        {
            if (config.transceiverType == 1)
            {
                tciClient?.DisConnectAsync();
                tciClient = null;
                List <SerialDeviceInfo> devices = SerialDevice.SerialDevice.listSerialDevices();
                SerialDeviceInfo        device  = devices.FirstOrDefault(item => item.deviceID == config.serialDeviceId);
                if (device != null)
                {
                    string portName = device.portName;
                    serialPort = new SerialPort(portName);
                    try
                    {
                        SerialPortFixer.Execute(portName);
                        serialPort.Open();
                        initializePort();
                    }
                    catch (Exception ex)
                    {
                        Logger.Error(ex, "Error opening port " + portName + " " + ex.ToString());
                    }
                }
                else
                {
                    serialPort = null;
                }
            }
            else if (config.transceiverType == 2)
            {
                serialPort?.Close();
                try
                {
                    tciClient = TciClient.Create(config.tciHost, config.tciPort, _cancellationTokenSource.Token);
                    await tciClient.ConnectAsync();

                    tciTranceiverController = tciClient.TransceiverController;
                }
                catch (Exception ex)
                {
                    Logger.Error(ex, $"Error opening TCI connection to {config.tciHost}:{config.tciPort} {ex.ToString()}");
                }
            }
        }
Example #4
0
 public void listenPort(string portName)
 {
     stopListenWirelessGW();
     if (sport?.PortName != portName)
     {
         sport?.Close();
         sport = new SerialPort(portName, 4800, Parity.None, 8, StopBits.One);
         sport.DataReceived += sportDataReceived;
         try
         {
             SerialPortFixer.Execute(portName);
             sport.Open();
             gpsConnectionChanged?.Invoke(this, null);
         }
         catch (Exception e)
         {
             System.Diagnostics.Trace.TraceInformation("Error opening port " + portName + " " + e.ToString());
         }
     }
 }
        public ThinkifySerialConnection(string comport)
        {
            // Create a new SerialPort object with default settings.
            serialPort = new SerialPort(comport, 115200, Parity.None, 8, StopBits.One);

            // Set the read/write timeouts
            serialPort.ReadTimeout            = 2500;
            serialPort.WriteTimeout           = 500;
            serialPort.ReceivedBytesThreshold = 1;

            serialPort.DataReceived += new SerialDataReceivedEventHandler(serialPort_DataReceived);

            SerialPortFixer.Execute(comport);

            if (serialPort.IsOpen == false)
            {
                serialPort.Open();
                serialPort.BaseStream.Flush();
            }

            rxBuffer     = "";
            replyPending = false;
        }
Example #6
0
        public void InitializeModem()
        {
            try
            {
                //bool status = false;
                SerialPortFixer serialPortFix = new SerialPortFixer();
                ComPortSetup();
                serialPortFix.Execute(PortNo);

                OpenPort();
                if (SMSPort.IsOpen)
                {
                    SMSPort.WriteLine("AT");
                    Sleep(SleepValue);
                    if (ModemVersion == "2.0")
                    {
                        StrValue = @"AT+CPMS=" + @"""" + MemoryType + @""",""" + MemoryType + @""",""" + MemoryType + @"""";
                        SMSPort.WriteLine(StrValue + Environment.NewLine);  //set memory use is gsm at+cpms? for me storage
                    }
                    else if (ModemVersion == "1.0")
                    {
                        StrValue = @"AT+CPMS=""" + MemoryType + @""",""" + MemoryType + @"""";
                        SMSPort.WriteLine(StrValue + Environment.NewLine); //set memory use is gsm at+cpms? for sm storage
                    }

                    Sleep(SleepValue);
                    SMSPort.WriteLine("AT&W" + Environment.NewLine);
                    Sleep(SleepValue);
                    SMSPort.WriteTimeout = 30;
                }
                //ClosePort();
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
Example #7
0
        private void Validate(List <string> ports)
        {
            SetStatus(new ModemLogEntry {
                Message = "Перевірка портів", Status = Common.ModemStatus.INFO
            });
            ports.ForEach(port =>
            {
                Task.Run(async() =>
                {
                    if (!SerialPort.GetPortNames().Contains(port))
                    {
                        SetStatus(new ModemLogEntry {
                            Message = "Порт відсутній у системі", Status = Common.ModemStatus.ERROR, Port = port
                        });
                        return;
                    }

                    try
                    {
                        SerialPortFixer.Execute(port);
                    }
                    catch (Exception)
                    {
                        return;
                    }

                    if (!_statuses.ContainsKey(port))
                    {
                        _statuses.Add(port, new ModemStatus {
                            Port = new SerialPort()
                        });
                    }

                    var serialPort = _statuses[port].Port;

                    serialPort.PortName     = port;
                    serialPort.BaudRate     = Baudrate;
                    serialPort.DataBits     = DataBits;
                    serialPort.StopBits     = StopBits;
                    serialPort.Parity       = Parity;
                    serialPort.Handshake    = Handshake.None;
                    serialPort.WriteTimeout = Timeout * 1000;
                    serialPort.ReadTimeout  = Timeout * 1000;
                    serialPort.DtrEnable    = true;

                    if (!serialPort.IsOpen)
                    {
                        SetStatus(new ModemLogEntry {
                            Message = "Відкриття порту", Status = Common.ModemStatus.INFO, Port = port
                        });
                        serialPort.Open();

                        var response = new byte[1024];
                        var stream   = serialPort.BaseStream;

                        serialPort.DiscardInBuffer();
                        serialPort.DiscardOutBuffer();

                        await Task.Delay(WriteDelay * 1000);
                        SetStatus(new ModemLogEntry {
                            Message = "AT", Status = Common.ModemStatus.SEND, Port = port
                        });
                        serialPort.WriteLine(@"AT" + "\r\n");
                        await Task.Delay(ReadDelay * 1000);
                        var task = stream.ReadAsync(response, 0, response.Length).ContinueWith(result =>
                        {
                            if (result.IsCompleted && !(result.IsFaulted || result.IsCanceled))
                            {
                                SetStatus(new ModemLogEntry {
                                    Message = $"Отримано {result.Result} байтів", Status = Common.ModemStatus.RECEIVE, Port = port
                                });
                            }
                        });
                        await Task.WhenAny(task, Task.Delay(Timeout * 1000));

                        var status = Encoding.ASCII.GetString(response);
                        SetStatus(new ModemLogEntry {
                            Message = $"{status}", Status = Common.ModemStatus.RECEIVE, Port = port
                        });
                        if (status.Contains("OK"))
                        {
                            _statuses[port].Status = PortStatus.OK;
                        }
                    }
                    else
                    {
                        SetStatus(new ModemLogEntry {
                            Message = "Порт відкрито", Status = Common.ModemStatus.INFO, Port = port
                        });
                    }
                });
            });
        }