private static Device <Sensors> ConfigureSerialDevice() { Console.Clear(); Console.WriteLine("Enter the COM port of the device"); Device <Sensors> device; while (true) { string number = Console.ReadLine(); int portNum; if (int.TryParse(number, out portNum)) { try { device = new SerialPortDevice <Sensors>(portNum, "ArduinoBoxProp"); device.Connect(); Console.WriteLine("Connected"); return(device); } catch { Console.WriteLine("Could not connect to device, please select another COM port"); } } } }
public static Device <TData> ConnectToPropUsingSerial <TData>(int port, string name = "ArduinoProp") where : TData { Console.Clear(); Console.WriteLine("Enter the COM port of the device"); Device <TData> device; while (true) { string number = Console.ReadLine(); int portNum; if (int.TryParse(number, out portNum)) { try { device = new SerialPortDevice <TData>(portNum, "ArduinoBoxProp"); device.Connect(); Console.WriteLine("Connected"); return(device); } catch { Console.WriteLine("Could not connect to device, please select another COM port"); } } } }
private static void run() { WriteLines("All ports:"); showPortNames(SerialPort.GetPortNames); showPortNames(ParallelPort.GetPortNames); WriteLines("Physical ports:"); showPortNames(SerialPortDevice.GetPhysicalSerialPortNames); showPortNames(ParallelPortDevice.GetPhysicalParallelPortNames); WriteLines("Physical devices:"); List <SerialPortDevice> serialPortDevices = SerialPortDevice.GetSerialPortDevices(); foreach (SerialPortDevice serialPortDevice in serialPortDevices) { Console.WriteLine(serialPortDevice); } List <ParallelPortDevice> parallelPortDevices = ParallelPortDevice.GetParallelPortDevices(); foreach (ParallelPortDevice parallelPortDevice in parallelPortDevices) { Console.WriteLine(parallelPortDevice); } WriteLines("LPTENUM ports:"); showPortNames(ParallelPortDevice.GetLptEnumParallelPortNames); WriteLines("Done."); }
public DAM(ILogger logger, string comPath, byte address = 0xfe) { if (string.IsNullOrEmpty(comPath)) { throw new ArgumentException("message", nameof(comPath)); } Logger = logger; ComPath = comPath; this.address = address; var ports = SerialPortDevice.GetPortNames(); device = new SerialPortDevice(logger, comPath, BitRate.B9600); for (int i = 0; i < this.RelayPortsCount; i++) { RelayPort[i] = false; } for (int i = 0; i < this.OptocouplerPortsCount; i++) { OptocouplerPort[i] = false; } for (int i = 0; i < this.AnalogInputCount; i++) { AnalogInput[i] = 0; } device.Open(); }
private static void Main(string[] args) { var ports = SerialPortDevice.GetPortNames(); SerialPortDevice port = new SerialPortDevice(null, "COM3", BitRate.B9600); //var port = new System.IO.Ports.SerialPort("/dev/ttyUSB0", 9600); /* * FE 05 00 00 FF 00 98 35 * FE 05 00 01 FF 00 C9 F5*/ //port.PortName = "/dev/ttyUSB0"; //port.BaudRate = 9600; port.Open(); var data = new byte[] { 0xFE, 0x05, 0x00, 0x01, 0xFF, 0x00, 0xc9, 0xf5 }; //FE 05 00 01 FF 00 C9 F5 port.Write(data); data = new byte[] { 0xFE, 0x05, 0x00, 0x00, 0x00, 0x00, 0xD9, 0xC5 }; port.Write(data); port.Close(); }
public bool InitGps() { var device = new SerialPortDevice(_serialPort); device.MessageReceived += DeviceOnMessageReceived; device.OpenAsync(); return(true); }
public void Close() { if (serialPortDevice != null) { serialPortDevice.Received -= SerialPortDevice_Received; serialPortDevice.Close(); } serialPortDevice = null; }
public GPS() { // initialize UART serialDev = new SerialPort(); // WARNING: change the serial path to which corresponds to your module serialDev.PortName = "/dev/apalis-tty4"; serialDev.BaudRate = 9600; Device = new SerialPortDevice(serialDev); }
public SerialPortData() { StationName = ""; PortName = "COM1"; BaudRate = 9600; DataBit = 8; StopBit = StopBits.None; Parity = Parity.None; SerialPortDevice = SerialPortDevice.Common; }
static void Main() { string portname = "COM7"; // Change to match the name of the port your device is connected to int baudrate = 115200; // Change to the baud rate your device communicates at (usually specified in the manual) SerialPort port = new SerialPort(portname, baudrate, Parity.None, 8, StopBits.One); SerialPortDevice device = new SerialPortDevice(port); device.MessageReceived += OnNmeaMessageReceived; device.OpenAsync(); Console.ReadKey(); }
protected override void OnCreate(Bundle savedInstanceState) { base.OnCreate(savedInstanceState); var value = SerialPortDevice.Test(5); System.Diagnostics.Debug.WriteLine(value); var portNames = SerialPortDevice.GetAllDevicesPath(); foreach (var item in portNames) { System.Diagnostics.Debug.WriteLine(item); } // Set our view from the "main" layout resource SetContentView(Resource.Layout.activity_main); var serialport = new SerialPortDevice("/dev/ttyS3", 115200); int RecvCount = 0; int SendCount = 0; serialport.Received += (s, e) => { RecvCount += e.Length; }; try { serialport.Open(); } catch (System.Exception ex) { System.Diagnostics.Debug.WriteLine(ex.Message); return; } Task.Run(() => { while (true) { System.Diagnostics.Debug.WriteLine($"Count:{SendCount} {RecvCount}"); serialport.Send(new byte[] { 0x01, 0x02 }); SendCount += 2; Thread.Sleep(50); } }); }
public void For2SameInputEvents_ShouldExecuteDataParserOnce() { var testScheduler = new TestScheduler(); //arrange var target = new SerialPortDevice(_serialPortMock.Object, _dataParserMock.Object, testScheduler); //act target.ObserveDataReceived(10d); //input events _serialPortMock.Raise(port => port.DataReceived += null, "Test message 1"); _serialPortMock.Raise(port => port.DataReceived += null, "Test message 1"); //assert _dataParserMock.Verify(x => x.Parse(It.IsAny <string>()), Times.Once); }
private static Device <Sensors> ConfigureTcpNetworkDeviceAP() { //first connect over serial to the device Console.Clear(); Console.WriteLine("Setting up prop over usb..."); Console.WriteLine("Enter the WiFi network SSID: "); string ssid = Console.ReadLine(); Console.WriteLine("Enter the Wifi network Password: "******"ArduinoConfig"); string ipAddress = ""; bool isDoneConfig = false; MessageRecievedHandler <Config> messageHandler = (device, message) => { if (message.Status == "Done") { ipAddress = message.DeviceIp; isDoneConfig = true; } }; serialConfig.Recieved += messageHandler; serialConfig.Connect(); serialConfig.Send(new Config() { WifiCredentials = new WifiCredentials() { SSID = ssid, Password = pass } }); while (!isDoneConfig) { //just keep running... } serialConfig.Recieved -= messageHandler; serialConfig.Disconnect(); serialConfig.Dispose(); ConfigurationManager.AppSettings["DeviceIp"] = ipAddress; Console.WriteLine("Now recieving data, you may now disconnect the device"); return(new TCPNetworkDevice <Sensors>(ipAddress, 53005, "ArduinoProp"));; }
public void ForNoInputFor5sec_ShouldNotThrowTimeoutException() { var testScheduler = new TestScheduler(); //arrange var target = new SerialPortDevice(_serialPortMock.Object, _dataParserMock.Object, testScheduler); //act && assert try { target.ObserveDataReceived(10d); //input event _serialPortMock.Raise(port => port.DataReceived += null, "Test message"); //wait 5 sec - less than timeout limit testScheduler.AdvanceBy(TimeSpan.FromSeconds(5).Ticks); } catch (Exception) { Assert.Fail("Exception was thrown but it shouldn't"); } }
/// <summary> /// Opens every devcie in the collection and listens for an NMEA message. /// </summary> /// <param name="Devices"> /// The collection of devices to be searched.</param> /// <returns></returns> public async Task FindSerialGPS(DeviceInformationCollection Devices) { try { foreach (DeviceInformation deviceInfo in Devices) { if (!_serialGPSDeviceFound) { NMEAMessage = "Listening on " + deviceInfo.Name; _serialGPSDevice = await InitGPSAsync(deviceInfo); if (_serialGPSDevice != null) { //Subscribe and open port to check if it is NMEA _serialGPSDevice.MessageReceived += _serialGPSDevice_MessageReceived; await _serialGPSDevice.OpenAsync(); //delay 1000ms for safe guarenteed message read. await Task.Delay(1000); if (_serialGPSDeviceFound) { SelectedDevice = deviceInfo; } else { //Close if device is not found CloseAndDisposeSerialGPS(); } } } } NMEAMessage = "No GPS Found"; } catch (Exception ex) { Logger.WriteLog(ex); } }
public void ForNoInputFor20sec_ShouldThrowTimeoutException() { var testScheduler = new TestScheduler(); //arrange var target = new SerialPortDevice(_serialPortMock.Object, _dataParserMock.Object, testScheduler); //act && assert try { target.ObserveDataReceived(10d); //input event _serialPortMock.Raise(port => port.DataReceived += null, "Test message"); //wait 20 sec. - more than timeout limit testScheduler.AdvanceBy(TimeSpan.FromSeconds(20).Ticks); Assert.Fail("No exception was thrown"); } catch (Exception ex) { Assert.IsTrue(ex is TimeoutException); } }
static void Main(string[] args) { SerialPort serialDev; SerialPortDevice gps; // serial configs serialDev = new SerialPort(); serialDev.PortName = Environment.GetEnvironmentVariable("GPS_SERIAL_PORT"); serialDev.BaudRate = 9600; gps = new SerialPortDevice(serialDev); // set listener gps.MessageReceived += OnNmeaMessageReceived; gps.OpenAsync(); // on ctrl+c close connection Console.CancelKeyPress += (object sender, ConsoleCancelEventArgs eventArgs) => { gps.CloseAsync(); }; // wait for gps inputs Thread.Sleep(Timeout.Infinite); }
public bool Open(string name, int baudrate, int flags = 0) { serialPortDevice = new SerialPortDevice(name, baudrate, flags); serialPortDevice.Received += SerialPortDevice_Received; return(serialPortDevice.Open()); }
private static void Main() { ConcurrentStack <string> stack = new ConcurrentStack <string>(); GetPorts().ForEach(Console.WriteLine); var portName = "COM4"; var baudRate = 9600; #region Read Gps using var serialPort = new SerialPort(portName, baudRate); using var device = new SerialPortDevice(serialPort); device.MessageReceived += (sender, e) => { switch (e.Message.MessageType) { case "GPGLL": if (e.Message is Gll gll) { //Console.WriteLine(gll.ToString()); stack.Push(gll.ToString()); } else { Debugger.Break(); } return; case "GPRMC": if (e.Message is Rmc rmc) { //Console.WriteLine(rmc.ToString()); stack.Push(rmc.ToString()); } else { Debugger.Break(); } return; case "GPVTG": if (e.Message is Vtg vtg) { //Console.WriteLine(vtg.ToString()); stack.Push(vtg.ToString()); } else { Debugger.Break(); } return; case "GPGGA": if (e.Message is Gga gga) { //Console.WriteLine(gga.ToString()); stack.Push(gga.ToString()); } else { Debugger.Break(); } return; case "GPGSA": if (e.Message is Gsa gsa) { //Console.WriteLine(gsa.ToString()); stack.Push(gsa.ToString()); } else { Debugger.Break(); } return; case "GPGSV": if (e.Message is Gsv gsv) { //Console.WriteLine(gsv.ToString()); stack.Push(gsv.ToString()); } else { Debugger.Break(); } return; default: var type = e.Message.MessageType; Console.WriteLine($"Type of : {type}"); return; } }; var task = device.OpenAsync(); Console.WriteLine("Running"); #endregion #region Console Write Task var cts = new CancellationTokenSource(); var consoleTask = Task.Factory.StartNew(() => ConsoleWriter(cts.Token, stack)); #endregion // Shutdown Console.WriteLine("press to exit"); Console.ReadKey(); device.CloseAsync(); cts.Cancel(); consoleTask.Wait(); Console.WriteLine("alles ende"); }
public IDevice Open() { var device = new SerialPortDevice(this); return(device); }
public GpsSensor() { this.serialPort = new SerialPort("/dev/serial0"); this.SerialPortDevice = new SerialPortDevice(this.serialPort); }