Exemplo n.º 1
0
 public bool Open(int channel)
 {
     CheckChannel(channel);
     if (Available(channel))
     {
         if (stream is null)
         {
             try
             {
                 stream = device.Open();
             }
             catch (IOException)
             {
                 throw new HardwareException(DeviceType.Generator, ErrorCode.CommunicationError, "Generator unavailable", "Connect the generator");
             }
             stream.BaudRate     = 57600;
             stream.ReadTimeout  = 500;
             stream.WriteTimeout = 500;
         }
         open[channel] = true;
         return(true);
     }
     else
     {
         return(false);
     }
 }
Exemplo n.º 2
0
        static void Main(string[] args)
        {
            Console.WriteLine("Hello Serial port!");
            var  ports = SerialDevice.GetPortNames();
            bool isTTY = false;

            foreach (var prt in ports)
            {
                Console.WriteLine($"Serial name: {prt}");
                if (prt.Contains("ttyS0"))
                {
                    isTTY = true;
                }
            }
            if (!isTTY)
            {
                Console.WriteLine("No ttyS0 serial port!");
                return;
            }
            Console.WriteLine("Yes, we have the embedded serial port available, opening it");
            SerialDevice mySer = new SerialDevice("/dev/ttyS0", BaudRate.B1152000);

            mySer.DataReceived += MySer_DataReceived;
            mySer.Open();
            while (!Console.KeyAvailable)
            {
                ;
            }
            mySer.Close();
        }
Exemplo n.º 3
0
        static void Main(string[] args)
        {
            SerialDevice sd;
            STPv3Reader reader;
            STPv3Request request;
            STPv3Response response;
            Tag tag = new Tag();
            tag.Type = TagType.AUTO_DETECT;
            string port;
            byte[] resp;
            float temp;

            if (args.Length < 1)
                port = "COM1";
            else
                port = args[0];

            sd = new SerialDevice();
            reader = new STPv3Reader(sd);
            try
            {
                sd.Address = port;
                sd.BaudRate = 38400;
                sd.Open();

                // read product code, reader name, hw version, fw version, and reader ID
                Console.Out.WriteLine(String.Format("Product Code: {0}", reader.ProductCode));
                Console.Out.WriteLine(String.Format("Reader Name: {0}", reader.ReaderName));
                Console.Out.WriteLine(String.Format("Hardware Version: {0}", reader.HardwareVersion));
                Console.Out.WriteLine(String.Format("Firmware Version: {0}", reader.FirmwareVersion));
                Console.Out.WriteLine(String.Format("Reader ID: {0}",
                    String.Join("", Array.ConvertAll<byte, string>(reader.ReaderID, delegate(byte value){ return String.Format("{0:X2}", value); }))));

                //scan for tags
                request = new STPv3Request();
                request.Tag = tag;
                request.Command = STPv3Commands.SELECT_TAG;
                request.Inventory = true;
                request.Issue(sd);

                while (((response = request.GetResponse()) != null) && (response.Success))
                {
                    if (response.ResponseCode == STPv3ResponseCode.SELECT_TAG_PASS)
                    {
                        Console.Out.WriteLine(String.Format("Tag found: {0} -> {1}",
                            Enum.GetName(typeof(SkyeTek.Tags.TagType),
                            response.TagType), String.Join("",
                            Array.ConvertAll<byte, string>(response.TID,
                            delegate(byte value) { return String.Format("{0:X2}", value); }))));
                    }
                }
            }

            catch (Exception ex)
            {
                Console.Out.WriteLine(ex.ToString());
            }

            Console.In.ReadLine();
        }
Exemplo n.º 4
0
        public static LoRaArduinoSerial CreateFromPort(string port)
        {
            var isWindows = RuntimeInformation.IsOSPlatform(OSPlatform.Windows);

            LoRaArduinoSerial result = null;

            if (!isWindows)
            {
                Console.WriteLine($"Starting serial port '{port}' on non-Windows");

                var serialPort = new SerialDevice(port, BaudRate.B115200);
                result = new LoRaArduinoSerial(serialPort);

                Console.WriteLine($"Opening serial port");
                try
                {
                    serialPort.Open();
                }
                catch (Exception ex)
                {
                    Console.WriteLine($"Error opening serial port '{port}': {ex.ToString()}");
                    throw;
                }
            }
            else
            {
                Console.WriteLine($"Starting serial port '{port}' on Windows");

                var serialPortWin = new SerialPort(port)
                {
                    BaudRate  = 115200,
                    Parity    = Parity.None,
                    StopBits  = StopBits.One,
                    DataBits  = 8,
                    DtrEnable = true,
                    Handshake = Handshake.None
                };
                result = new LoRaArduinoSerial(serialPortWin);

                try
                {
                    serialPortWin.Open();
                }
                catch (Exception ex)
                {
                    Console.WriteLine($"Error opening serial port '{port}': {ex.ToString()}");
                    throw;
                }
            }

            return(result);
        }
Exemplo n.º 5
0
        static void Main(string[] args)
        {
            var parser = new NmeaParser();

            var dummy = File.ReadAllText("/home/lubuntu/sample.nmea");
            //var dummyBytes = Encoding.UTF8.GetBytes(dummy);
            var nm = parser.Parse(dummy);

            return;

            var portNames = SerialDevice.GetPortNames();

            var serial = new SerialDevice("/dev/ttyACM0", BaudRate.B1152000);

            serial.DataReceived += (o, eventArgs) =>
            {
            };


            serial.Open();

            while (true)
            {
                Thread.Sleep(200);
            }
            return;

            var client = new UdpClient(5554);
            var sender = new UdpClient(5556);

            var ip     = "192.168.100.55";
            var exitBs = Encoding.ASCII.GetBytes("AT*CONFIG=\"general:navdata_demo\",\"TRUE\"\r");
            var ack    = Encoding.ASCII.GetBytes("AT*CTRL=0\r");

            sender.Send(exitBs, exitBs.Length, ip, 5556);
            sender.Send(ack, ack.Length, ip, 5556);
            client.Send(new byte[] { 1 }, 1, ip, 5554);

            var nav = new NavDataRetriever("192.168.100.55", 5554, 2000, client);

            nav.SendMessage = i => client.Send(new byte[] { (byte)i }, 1, ip, 5554);
            nav.Start();
            nav.WaitForFirstMessageToArrive();
            var navData = nav.CurrentNavigationData;

            while (true)
            {
                navData = nav.CurrentNavigationData;
            }
        }
Exemplo n.º 6
0
        public void Open()
        {
            lock (_openCloseLock)
            {
#if !NETCORE
                _serialPort.Open();
                //_serialPort.ReadTimeout = 50;
#endif
                _readCancellationTokenSource = new CancellationTokenSource();
                CancellationToken cancellationToken = _readCancellationTokenSource.Token;

                _receiveTask = Task.Run(() =>
                {
                    while (!cancellationToken.IsCancellationRequested)
                    {
                        try
                        {
#if NETCORE
                            Frame frame = _frameSerializer.Deserialize(_serialPort.InputStream.AsStreamForRead());
#else
                            Frame frame = _frameSerializer.Deserialize(_serialPort);
#endif

                            var handler = FrameReceived;
                            if (handler != null)
                            {
                                Task.Run(() =>
                                {
                                    handler(this, new FrameReceivedEventArgs(frame.Payload.Content));
                                }, cancellationToken).ConfigureAwait(false);
                            }
                        }
                        catch (Exception)
                        {
                            if (!cancellationToken.IsCancellationRequested && !_isClosing)
                            {
                                throw;
                            }
                        }
                    }
                    // ReSharper disable MethodSupportsCancellation
                }, cancellationToken);
// ReSharper restore MethodSupportsCancellation

                _receiveTask.ConfigureAwait(false);
                //_receiveExtraTask.ConfigureAwait(false);
            }
        }
Exemplo n.º 7
0
 /// <summary>
 /// 打开串口资源
 /// </summary>
 /// <returns></returns>
 public bool Open()
 {
     try
     {
         if (!SerialDevice.IsOpen)
         {
             SerialDevice.Open();
         }
         return(SerialDevice.IsOpen);
     }
     catch (Exception ex)
     {
         ExceptionProcess(ex);
     }
     return(false);
 }
Exemplo n.º 8
0
 static void Main(string[] args)
 {
     //Classify();
     //Console.ReadLine();
     while (!IsSerialAvailable())
     {
         Console.WriteLine("Serial port not available, waiting 5 seconds");
         Thread.Sleep(5000);
     }
     Console.WriteLine("Serial port available, opening");
     mySer = new SerialDevice("/dev/ttyUSB0", BaudRate.B9600);
     mySer.DataReceived += MySer_DataReceived;
     outputComponents    = new IOutputComponent[] { new EmailOutput(), new SerialOutput(mySer) };
     mySer.Open();
     while (!Console.KeyAvailable)
     {
         ;
     }
     mySer.Close();
 }
Exemplo n.º 9
0
 public override void Open()
 {
     NativeStream = NativeDevice.Open();
     Task.Run(() =>
     {
         while (IsOpen)
         {
             try
             {
                 int temp = NativeStream.ReadByte();
                 if (temp != -1)
                 {
                     ReceivedData.Enqueue((byte)temp);
                     DataReceived?.Invoke(this, new System.EventArgs());
                 }
             }
             catch
             {
             }
         }
     });
 }
Exemplo n.º 10
0
        protected override async Task ConnectSlave()
        {
            if (config.SlaveConnection.Substring(0, 3) == "COM" || config.SlaveConnection.Substring(0, 8) == "/dev/tty")
            {
                try
                {
                    Console.WriteLine($"Opening...{config.SlaveConnection}");

                    m_serialPort = new SerialDevice(config.SlaveConnection, (int)config.BaudRate.Value, config.Parity.Value, (int)config.DataBits.Value, config.StopBits.Value);

                    m_serialPort.Open();
                    //m_serialPort.DataReceived += new SerialDataReceivedEventHandler(sp_DataReceived);
                    await Task.Delay(2000); //Wait target to be ready to write the modbus package
                }
                catch (Exception e)
                {
                    Console.WriteLine("Connect Slave failed");
                    Console.WriteLine(e.Message);
                    m_serialPort = null;
                }
            }
        }
Exemplo n.º 11
0
        public void Init()
        {
            bool validsp = false;

            if (SerialPortName.Length == 0)
            {
                return;
            }

            foreach (var str in GetSerialPorts())
            {
                if (str == SerialPortName)
                {
                    validsp = true;
                    break;
                }
            }
            if (!validsp)
            {
                return;
            }

            WiringPi.SetBaudRate(SerialPortName, 57600);

            //Selected serialport is valid
            _sps = new SerialDevice(SerialPortName, BaudRate.B57600);
            _sps.DataReceived += Sps_DataReceived;
            try
            {
                _sps.Open();
            }
            catch (Exception)
            {
                return;
            }

            IsInitialised = true;
        }
Exemplo n.º 12
0
 public void Open()
 {
     device.Open();
 }
Exemplo n.º 13
0
        static void Main(string[] args)
        {
            SerialDevice  sd;
            STPv3Reader   reader;
            STPv3Request  request;
            STPv3Response response;
            Tag           tag = new Tag();

            tag.Type = TagType.AUTO_DETECT;
            string port;

            byte[] resp;
            float  temp;

            if (args.Length < 1)
            {
                port = "COM1";
            }
            else
            {
                port = args[0];
            }

            sd     = new SerialDevice();
            reader = new STPv3Reader(sd);
            try
            {
                sd.Address  = port;
                sd.BaudRate = 38400;
                sd.Open();

                // read product code, reader name, hw version, fw version, and reader ID
                Console.Out.WriteLine(String.Format("Product Code: {0}", reader.ProductCode));
                Console.Out.WriteLine(String.Format("Reader Name: {0}", reader.ReaderName));
                Console.Out.WriteLine(String.Format("Hardware Version: {0}", reader.HardwareVersion));
                Console.Out.WriteLine(String.Format("Firmware Version: {0}", reader.FirmwareVersion));
                Console.Out.WriteLine(String.Format("Reader ID: {0}",
                                                    String.Join("", Array.ConvertAll <byte, string>(reader.ReaderID, delegate(byte value){ return(String.Format("{0:X2}", value)); }))));

                //scan for tags
                request           = new STPv3Request();
                request.Tag       = tag;
                request.Command   = STPv3Commands.SELECT_TAG;
                request.Inventory = true;
                request.Issue(sd);

                while (((response = request.GetResponse()) != null) && (response.Success))
                {
                    if (response.ResponseCode == STPv3ResponseCode.SELECT_TAG_PASS)
                    {
                        Console.Out.WriteLine(String.Format("Tag found: {0} -> {1}",
                                                            Enum.GetName(typeof(SkyeTek.Tags.TagType),
                                                                         response.TagType), String.Join("",
                                                                                                        Array.ConvertAll <byte, string>(response.TID,
                                                                                                                                        delegate(byte value) { return(String.Format("{0:X2}", value)); }))));
                    }
                }
            }

            catch (Exception ex)
            {
                Console.Out.WriteLine(ex.ToString());
            }

            Console.In.ReadLine();
        }
Exemplo n.º 14
0
        private static void HidSharpMethod()
        {
            Console.WriteLine("HIDSharp looking for a USB Serial devices...");

            List <SerialDevice> devices = DeviceList.Local.GetSerialDevices().ToList();

            if (!devices.Any())
            {
                Console.WriteLine("No Devices Found");
                return;
            }

            foreach (SerialDevice device in devices)
            {
                Console.WriteLine($"Found {device}");

                if (device.DevicePath.Contains("GBA ST2"))
                {
                    Console.WriteLine($"Found Match! { device.GetFriendlyName()}");
                    if (billAcceptor == null)
                    {
                        billAcceptor = device;
                        break;
                    }
                }
            }

            if (billAcceptor == null)
            {
                Console.WriteLine("Bill Acceptor not found!");
                return;
            }

            StringBuilder builder;
            SerialStream  stream = billAcceptor.Open();

            using (stream)
            {
                while (!CancelationToken)
                {
                    byte[] buffer = new byte[8];
                    int    count  = 0;

                    try
                    {
                        count = stream.Read(buffer, 0, buffer.Length);
                    }
                    catch (TimeoutException e)
                    {
                        Console.WriteLine("Timeout - new session started");
                        continue;
                    }

                    if (count > 0)
                    {
                        string converted = Convert.ToBase64String(buffer);
                        Console.WriteLine($"Evaluating: {converted}");

                        switch (converted)
                        {
                        case "B/lPAj0BAZA=":
                        case "B/lPAj0EA5U=":
                        case "B/lPAj0EBJY=":
                        case "B/lPAj0BAI8=":
                            Console.WriteLine("10 kn entered");
                            break;

                        default:
                            ReactToUnknownBill();
                            break;
                        }

                        count = 0;
                    }
                }
            }

            Console.WriteLine("Closing session");
        }
Exemplo n.º 15
0
 public void Start()
 {
     GpsDevice.Open();
 }