/// <summary>
 /// Инициализация параметров подключаемого устройства
 /// </summary>
 /// <param name="deviceProps">Контейнер параметров устройства</param>
 /// <param name="device">Интерфейс устройства</param>
 private void InitConnectableDevice(ConnectableDeviceProperties deviceProps,
                                    ISerialDevice device)
 {
     // параметры связи
     device.PortName = deviceProps.Port;
     device.Baud     = deviceProps.BaudRate;
 }
Beispiel #2
0
        private void SetSerialPort(string devName)
        {
            ISerialDevice dev = null;

            try
            {
                if (devName.ToLower().StartsWith("com"))        // TODO: allow /dev/nnn for Unix/Linux!
                {
                    // COM port.  Try to instantiate & assign to system.
                    dev = new PhysicalPort(devName);
                }
                else if (devName.ToLower().StartsWith("rsx:"))
                {
                    // RSX device.
                    dev = new RSXFilePort();
                }
                else
                {
                    throw new ArgumentOutOfRangeException("Invalid device name. Expected COMn: or RSX:");
                }

                Z80System.Instance.SetSerialPort(dev);
            }
            catch (Exception e)
            {
                Console.WriteLine("Unable to set rs232 port - {0}", e.Message);
            }
        }
Beispiel #3
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}");
             if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
             {
                 m_serialPort = WinSerialDevice.CreateDevice(config.SlaveConnection, (int)config.BaudRate, config.Parity, (int)config.DataBits, config.StopBits);
             }
             else
             {
                 m_serialPort = UnixSerialDevice.CreateDevice(config.SlaveConnection, (int)config.BaudRate, config.Parity, (int)config.DataBits, config.StopBits);
             }
             m_serialPort.Open();
             //m_serialPort.DataReceived += new SerialDataReceivedEventHandler(sp_DataReceived);
             await Task.Delay(0);
         }
         catch (Exception e)
         {
             Console.WriteLine("Connect Slave failed");
             Console.WriteLine(e.Message);
             m_serialPort = null;
         }
     }
 }
Beispiel #4
0
 public HalfDuplexSerialDevice(ISerialDevice serialDevice, GpioPin directionPin, GpioPinValue txDirection, GpioPinValue rxDirection)
 {
     _serialDevice        = serialDevice;
     _directionPin        = directionPin;
     _txDirectionPinValue = txDirection;
     _rxDirectionPinValue = rxDirection;
 }
Beispiel #5
0
 public static Wheelchair Instance(ISerialDevice serialDevice)
 {
     if (instance == null)
     {
         instance = new Wheelchair(serialDevice, null, 0);
     }
     return(instance);
 }
Beispiel #6
0
 public static Wheelchair Instance(ISerialDevice serialDevice, string portName, int baudRate)
 {
     if (instance == null)
     {
         instance = new Wheelchair(serialDevice, portName, baudRate);
     }
     return(instance);
 }
Beispiel #7
0
        /// <summary>
        /// Sets the host device to use for the serial port.
        /// </summary>
        public void SetDevice(ISerialDevice device)
        {
            if (device == null)
            {
                throw new ArgumentNullException("device");
            }

            _serialDevice = device;
        }
 public override void ReleaseSession()
 {
     this.ReleaseOperations();
     if (this.m_serialPort != null)
     {
         this.m_serialPort.Dispose();
         this.m_serialPort = null;
     }
 }
 public BGCentralManager(ISerialDevice serialDevice)
 {
     _bgApi = new BGLibApi(serialDevice);
     _bgApi.GAPScanResponse           += BGApi_OnGAPScanResponse;
     _bgApi.ConnectionStatus          += BGApi_OnConnectionStatus;
     _bgApi.ConnectionDisconnected    += BGApi_OnConnectionDisconnected;
     _connectionStatusWaitHandle       = new AsyncAutoResetEvent(false);
     _connectionDisconnectedWaitHandle = new AsyncAutoResetEvent(false);
 }
Beispiel #10
0
 public override void ReleaseSession()
 {
     ReleaseOperations();
     if (m_serialPort != null)
     {
         m_serialPort.Dispose();
         m_serialPort = null;
     }
 }
Beispiel #11
0
        public DeviceConnection(DeviceNode deviceNode, ISerialDevice device)
        {
            DeviceNode  = deviceNode;
            this.device = device;
            State       = ConnectionState.Initializing;

            ReadBuffer        = new byte[] { };
            WriteASCIICommand = new DelegateCommand <string>(OnWriteASCII, _ => State == ConnectionState.Ready);
            WriteBytesCommand = new DelegateCommand <string>(OnWriteBytes, _ => State == ConnectionState.Ready);
        }
        /// <summary>
        /// Open the initialized serial port
        /// </summary>
        private static ISerialDevice OpenSerial(string connection, int baudRate, Parity parity, int dataBits, StopBits stopBits, string direction)
        {
            ISerialDevice serialDevice = SerialDeviceFactory.CreateSerialDevice(connection, baudRate, parity, dataBits, stopBits);

            serialDevice.Open();

            Log.Information($"Serial port '{connection}' opened for '{direction}'");

            return(serialDevice);
        }
Beispiel #13
0
        public static async Task Main(string[] args)
        {
            DeviceEnumerator en = new DeviceEnumerator();
            var arr             = await en.FindAll <ISerialDevice <SerialDeviceName> >().ToArrayAsync();

            ISerialDevice <SerialDeviceName> device = arr[0];

            device.Start();
            await device.Send(new byte[] { 0, 1, 2 });
        }
Beispiel #14
0
        public DeviceConnection(DeviceNode deviceNode, ISerialDevice device)
        {
            DeviceNode = deviceNode;
            this.device = device;
            State = ConnectionState.Initializing;

            ReadBuffer = new byte[] { };
            WriteASCIICommand = new DelegateCommand<string>(OnWriteASCII, _ => State == ConnectionState.Ready);
            WriteBytesCommand = new DelegateCommand<string>(OnWriteBytes, _ => State == ConnectionState.Ready);
        }
Beispiel #15
0
        public override async Task ReleaseSessionAsync()
        {
            await this.ReleaseOperationsAsync().ConfigureAwait(false);

            if (this.serialPort != null)
            {
                this.serialPort.Dispose();
                this.serialPort = null;
            }
        }
Beispiel #16
0
 public Keithley2400Model(ISerialDevice keithley2400SerialDevice)
 {
     DeviceIdentifier          = "Keithley";
     _reportingFields          = new List <string>();
     _keithley2400SerialDevice = keithley2400SerialDevice;
     _configurations           = new Keigthley2400Configuration[]
     {
         VSource,
         ISource
     };
 }
        /// <summary>
        /// Disposing a serial port in case of updating desired properties
        /// </summary>
        private static void DisposeSerialPort(ISerialDevice serialPort)
        {
            if (serialPort != null)
            {
                serialPort.Close();

                Log.Debug($"Serial port disposed");
            }

            Log.Debug("No serial port to dispose");
        }
Beispiel #18
0
        public Device(ISerialDevice serialDevice)
        {
#if DEBUG
            Serializer.MemberDeserialized  += OnMemberDeserialized;
            Serializer.MemberDeserializing += OnMemberDeserializing;
            Serializer.MemberSerialized    += OnMemberSerialized;
            Serializer.MemberSerializing   += OnMemberSerializing;
#endif

            _serialDevice = serialDevice;
        }
Beispiel #19
0
        protected XBeeControllerBase(ISerialDevice serialDevice)
        {
            SerialDevice = serialDevice;

#if DEBUG
            Serializer.MemberDeserialized  += OnMemberDeserialized;
            Serializer.MemberDeserializing += OnMemberDeserializing;
            Serializer.MemberSerialized    += OnMemberSerialized;
            Serializer.MemberSerializing   += OnMemberSerializing;
#endif
        }
Beispiel #20
0
 public BGLibApi(ISerialDevice serialDevice)
 {
     _serialDevice = serialDevice;
     if (!_serialDevice.IsAttached)
     {
         serialDevice.AttachAsync(256000).GetAwaiter().GetResult();
     }
     _bglib = new BGLib(_serialDevice);
     StartSerialRxConsumerTask();
     _serialDevice.DataReceived += Serial_DataReceived;
     SubscribeToCommandResponses();
     SubscribeToEvents();
 }
Beispiel #21
0
        private Wheelchair(string port)
        {
            xOffset = 0;

            this.serialDevice = new SerialDevice(port, 9600);
            this.commThread   = new Thread(ThreadCommunication);
            xval       = (byte)100;
            yval       = (byte)100;
            message    = new byte[8];
            response   = new byte[8];
            message[0] = (byte)250;
            this.Start();
        }
        public static ISerialDevice CreateSerialDevice(string portName, int baudRate, Parity parity, int dataBits, StopBits stopBits)
        {
            ISerialDevice device = null;

            if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
            {
                device = WinSerialDevice.CreateDevice(portName, baudRate, parity, dataBits, stopBits);
            }
            else if (RuntimeInformation.IsOSPlatform(OSPlatform.Linux))
            {
                device = UnixSerialDevice.CreateDevice(portName, baudRate, parity, dataBits, stopBits);
            }
            return(device);
        }
Beispiel #23
0
        protected XBeeControllerBase(ISerialDevice serialDevice)
        {
            SerialDevice = serialDevice;

            Serializer            = new BinarySerializer();
            Serializer.Endianness = Endianness.Big;

//#if DEBUG
//            Serializer.MemberDeserialized += OnMemberDeserialized;
//            Serializer.MemberDeserializing += OnMemberDeserializing;
//            Serializer.MemberSerialized += OnMemberSerialized;
//            Serializer.MemberSerializing += OnMemberSerializing;
//#endif
        }
Beispiel #24
0
 public Memory(CPU cpu, ROM rom)
 {
     this.cpu  = cpu;
     this.mbc  = rom.MBC;
     this.rom  = rom;
     hdma      = new HDMA(this);
     wram      = new byte[8, 0x1000];
     wrambank  = 1;
     hram      = new byte[0x7F];
     Audio     = new Audio.Audio(SoundOutMode.NAudio);
     serial    = new SerialConsole();
     Interrupt = new Interrupt(cpu);
     Video     = new Video(Interrupt, hdma, rom);
     Joypad    = new Joypad(Interrupt);
     Timer     = new Timer(Interrupt);
 }
Beispiel #25
0
        public async Task <bool> ConnectDevice(ISerialDevice device, Action <byte[]> receivedDataAction)
        {
            _receivedDataAction = receivedDataAction ?? throw new ArgumentNullException(nameof(receivedDataAction));
            var connectDevice = device as SerialDevice;

            if (connectDevice == null)
            {
                throw new ArgumentNullException(nameof(device));
            }

            bool result = false;

            IUsbSerialDriver driver = connectDevice.Driver;

            if (await _usbManager.RequestPermissionAsync(driver.Device, _context))
            {
                _connectedPortManager = new PortManager(driver.Ports[0])
                {
                    BaudRate = 115200,
                    DataBits = DataBits.Eight,
                    StopBits = StopBits.One,
                    Parity   = Parity.None,
                };

                _connectedPortManager.DataReceived += (sender, args) =>
                {
                    if (args?.Data?.Any() ?? false)
                    {
                        _receivedDataAction?.Invoke(args.Data);
                    }
                };

                _connectedPortManager.ErrorReceived += (sender, args) =>
                {
                    Debugger.Break(); //To look at args
                    Debug.WriteLine($"An error occurred on the serial device: {(args?.ExceptionObject as Exception)?.ToString() ?? "(unknown)"}");
                };

                _connectedPortManager.Run(_usbManager);
                result = true;
            }

            return(result);
        }
Beispiel #26
0
        private Wheelchair(ISerialDevice serialDevice, string portName, int baudRate)
        {
            xOffset = 0;

            this.serialDevice = serialDevice;
            if (portName != null)
            {
                this.serialDevice.PortName = portName;
            }
            if (baudRate > 0)
            {
                this.serialDevice.BaudRate = baudRate;
            }
            this.commThread = new Thread(ThreadCommunication);
            xval            = (byte)100;
            yval            = (byte)100;
            message         = new byte[8];
            response        = new byte[8];
            message[0]      = (byte)250;
            this.Start();
        }
Beispiel #27
0
        /// <summary>
        /// Initialize the XY values to
        /// </summary>
        /// <param name="portName"></param>
        /// <param name="baudRate"></param>
        private Wheelchair(string portName = "COM7", int baudRate = 9600)
        {
            xOffset = 0;

            this.portName     = portName;
            this.baudRate     = baudRate;
            this.commThread   = new Thread(ThreadCommunication);
            xval              = (byte)100;
            yval              = (byte)100;
            message           = new byte[8];
            response          = new byte[8];
            message[0]        = (byte)250;
            this.serialDevice = new SerialDevice(portName, baudRate);
            this.Start();

            // Check whether the thread has previously been named
            // to avoid a possible InvalidOperationException.
            if (System.Threading.Thread.CurrentThread.Name == null)
            {
                System.Threading.Thread.CurrentThread.Name = "WheelchairThread";
            }
        }
Beispiel #28
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 = SerialDeviceFactory.CreateSerialDevice(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;
                }
            }
        }
Beispiel #29
0
        protected override async Task <byte[]> SendRequest(byte[] request, int reqLen)
        {
            //double slient_interval = 1000 * 5 * ((double)1 / (double)config.BaudRate);
            byte[] response = null;

            m_semaphore_connection.Wait();

            if (m_serialPort != null && m_serialPort.IsOpen())
            {
                try
                {
                    m_serialPort.DiscardInBuffer();
                    m_serialPort.DiscardOutBuffer();
                    Task.Delay(m_silent).Wait();
                    m_serialPort.Write(request, 0, reqLen);
                    response = ReadResponse();
                }
                catch (Exception e)
                {
                    Console.WriteLine("Something wrong with the connection, disposing...");
                    Console.WriteLine(e.Message);
                    m_serialPort.Close();
                    m_serialPort.Dispose();
                    m_serialPort = null;
                    Console.WriteLine("Connection lost, reconnecting...");
                    await ConnectSlave();
                }
            }
            else
            {
                Console.WriteLine("Connection lost, reconnecting...");
                await ConnectSlave();
            }

            m_semaphore_connection.Release();

            return(response);
        }
Beispiel #30
0
        protected override async Task <byte[]> SendRequestAsync(byte[] request)
        {
            byte[] response = null;

            await this.semaphoreConnection.WaitAsync().ConfigureAwait(false);

            if (this.serialPort != null && this.serialPort.IsOpen())
            {
                try
                {
                    this.serialPort.DiscardInBuffer();
                    this.serialPort.DiscardOutBuffer();
                    await Task.Delay(this.Silent).ConfigureAwait(false);

                    this.serialPort.Write(request, 0, request.Length);
                    response = await this.ReadResponseAsync().ConfigureAwait(false);
                }
                catch (Exception e)
                {
                    Console.WriteLine("Something wrong with the connection, disposing...");
                    Console.WriteLine(e.Message);
                    this.serialPort.Dispose();
                    this.serialPort = null;
                    Console.WriteLine("Connection lost, reconnecting...");
                    await this.ConnectSlaveAsync().ConfigureAwait(false);
                }
            }
            else
            {
                Console.WriteLine("Connection lost, reconnecting...");
                await this.ConnectSlaveAsync().ConfigureAwait(false);
            }

            this.semaphoreConnection.Release();

            return(response);
        }
Beispiel #31
0
		public DebugHandler (ISerialDevice com)
		{
			this.com = com;
		}
Beispiel #32
0
 public SerialDeviceStream(ISerialDevice serialDevice)
 {
     _serialDevice = serialDevice;
 }