/// <summary> /// Reads and writes data to an arduino controller through a serialport to /// </summary> /// <param name="force">Force applied to point of rotation</param> /// <returns>Returns current angle of pendulum</returns> public double Calculate(double force) { // Read data from MPU6050 // Write data to DC Motor // DC motor must not be based on velocity, the output should be based on torque change // IE higher motor output doesn't just increase speed, it also increases torque if (serialPort.IsOpen && serialPort.CanRead && serialPort.CanWrite) { //Write motor force to arduino serialPort.WriteLine(force.ToString()); //Read current angle from arduino Double.TryParse(serialPort.ReadLine(), out double arduinoMPUData); theta = arduinoMPUData; } else { try { serialPort.Open(); } catch (Exception ex) { } //Use to test functionality of this application //modifier -= force * 0.001; //theta += modifier; } return(theta); }
public void WriteLine(string text) { if (IsOpen) { sp.WriteLine(text); } }
static public List <List <double> > poll_for_data(SerialPortStream port, string user_input = "0") { // Send Command to Start, send it desired speed to run at port.Write("<1>"); bool quick_three = true; while (quick_three) { if (port.BytesToRead > 0) { string s = port.ReadLine(); s = Regex.Replace(s, @"\r", string.Empty); // Either prompt user for input, or take in function line arugment for a desired RPM to run at if (s == "give") { port.WriteLine(user_input); quick_three = false; break; } } } bool stop = true; Console.WriteLine("Test Started"); //Collect data with this loop List <double> temp = new List <double>(); List <List <double> > data = new List <List <double> >(); while (stop) { if (port.BytesToRead > 0) { string s = port.ReadLine(); s = Regex.Replace(s, @"\r", string.Empty); if (s == "end") { stop = false; break; } string[] message = s.Split(','); //temp.Add(Convert.ToDouble(s)); foreach (string element in message) { //Console.WriteLine(element); double value = Convert.ToDouble(element); temp.Add(value); Console.WriteLine(element); } data.Add(temp); } } return(data); }
public void SerialPortStream_WriteReadLine_Timeout2() { using (SerialPortStream src = new SerialPortStream(c_SourcePort, 115200, 8, Parity.None, StopBits.One)) using (SerialPortStream dst = new SerialPortStream(c_DestPort, 115200, 8, Parity.None, StopBits.One)) { src.WriteTimeout = c_Timeout; src.ReadTimeout = c_Timeout; dst.WriteTimeout = c_Timeout; dst.ReadTimeout = c_Timeout; src.Open(); Assert.IsTrue(src.IsOpen); dst.Open(); Assert.IsTrue(dst.IsOpen); bool err = false; string s; src.Write("Test"); try { s = dst.ReadLine(); } catch (System.Exception e) { if (e is TimeoutException) { err = true; } } Assert.IsTrue(err, "No timeout exception occurred"); src.WriteLine("String"); s = dst.ReadLine(); Assert.AreEqual("TestString", s); } }
private void SerialPortDataReceived(object sender, SerialDataReceivedEventArgs e) { string data = serialPort.ReadExisting(); try { if (data.Contains("ACK")) { data = data.Substring(5); } data = data.Substring(data.IndexOf('#') + 1, data.IndexOf('$') - data.IndexOf('#') - 1); } catch (Exception) { // throw; } if (data.StartsWith("DONE:")) { serialPort.Write("#SEND$"); } else if (data.StartsWith("MAC:")) { serialPort.WriteLine("#ACK$"); } Console.WriteLine(data); }
private void WriteLine(SerialPortStream serialPort, string line) { if (serialPort == null || !serialPort.IsOpen) { return; } logger.Trace("Sending \"{0}\" to NTI XL2 on port {1}", line, portName); serialPort.WriteLine(line); }
public void SerialPortStream_SendAndFlush2() { using (SerialPortStream dst = new SerialPortStream(c_DestPort, 115200, 8, Parity.None, StopBits.One)) using (SerialPortStream src = new SerialPortStream(c_SourcePort, 115200, 8, Parity.None, StopBits.One)) { // Required for com0com to send the data (the remote side must receive it) dst.Open(); Trace.WriteLine("1. Open()"); src.Open(); Trace.WriteLine("2. WriteLine()"); src.WriteLine("Connected"); Trace.WriteLine("3. Sleep()"); System.Threading.Thread.Sleep(100); Trace.WriteLine("4. WriteLine()"); src.WriteLine("Disconnected"); Trace.WriteLine("5. Flush()"); src.Flush(); Trace.WriteLine("6. Dispose()"); } }
public void CanRead() { EnsureConnected(); var task = extension.ReadOnce(); ourPort.WriteTimeout = 1000; ourPort.WriteLine("Hello, World!"); Task.WaitAny(task, Task.Delay(5000)); Assert.True(task.IsCompleted); (string _, List <object> data) = task.Result; Assert.AreEqual("Hello, World!", data[1]); }
public void SerialPortStream_SendAndFlush1() { using (SerialPortStream dst = new SerialPortStream(c_DestPort, 115200, 8, Parity.None, StopBits.One)) using (SerialPortStream src = new SerialPortStream(c_SourcePort, 115200, 8, Parity.None, StopBits.One)) { // Required for com0com to send the data (the remote side must receive it) dst.Open(); src.Open(); src.WriteLine("Connected"); src.Flush(); } }
public void SerialPortStream_WriteReadLine() { using (SerialPortStream src = new SerialPortStream(c_SourcePort, 115200, 8, Parity.None, StopBits.One)) using (SerialPortStream dst = new SerialPortStream(c_DestPort, 115200, 8, Parity.None, StopBits.One)) { src.WriteTimeout = c_Timeout; src.ReadTimeout = c_Timeout; dst.WriteTimeout = c_Timeout; dst.ReadTimeout = c_Timeout; src.Open(); Assert.IsTrue(src.IsOpen); dst.Open(); Assert.IsTrue(dst.IsOpen); string s; src.WriteLine("TestString"); s = dst.ReadLine(); Assert.AreEqual("TestString", s); } }
public void WriteLineReadLine() { using (SerialPortStream src = new SerialPortStream(SourcePort, 115200, 8, Parity.None, StopBits.One)) using (SerialPortStream dst = new SerialPortStream(DestPort, 115200, 8, Parity.None, StopBits.One)) { src.WriteTimeout = TimeOut; src.ReadTimeout = TimeOut; dst.WriteTimeout = TimeOut; dst.ReadTimeout = TimeOut; src.Open(); Assert.That(src.IsOpen, Is.True); dst.Open(); Assert.That(dst.IsOpen, Is.True); string s; src.WriteLine("TestString"); s = dst.ReadLine(); Assert.That(s, Is.EqualTo("TestString")); } }
internal static void Send() { if (myPort == null) { init(); } while (_queue.Count > 0) { var text = _queue[0]; _queue.RemoveAt(0); myPort.WriteLine(text); Console.WriteLine($"Sent message: {text}"); Thread.Sleep(250); } }
public async Task Execute() { if (_source != null || _destination != null) { Logger.Log($"Moving: {_source.Name} -> {_destination.Name}"); } else { Logger.Log($"Moving: {_x} -> {_y}"); } if (_x != 0 || _y != 0) { _serial.WriteLine($"G00 X{_x} Y{_y}"); await MoveFinished(); } }
public Dictionary <string, int> GetAvailablePortsAndAutoDiscover() { trackers = new Dictionary <string, int>(); foreach (string portName in SerialPortStream.GetPortNames()) { Console.WriteLine("Autodiscover port:"); Console.WriteLine(portName); try { autoDiscoverPort = new SerialPortStream(portName, 115200, 8, Parity.None, StopBits.One) { StopBits = StopBits.One, WriteTimeout = 1000, ReadTimeout = 3000 }; stopWatch = new Stopwatch(); stopWatch.Start(); autoDiscoverPort.DataReceived += SerialPortAutoDiscover; autoDiscoverPort.Open(); autoDiscoverPort.WriteLine(SerialMessageParser.Encode("DISCOVERY")); } catch (UnauthorizedAccessException) { autoDiscoverPort.Close(); } catch (System.IO.IOException) { autoDiscoverPort.Close(); } catch (TimeoutException) { autoDiscoverPort.Close(); } while (autoDiscoverPort.IsOpen) { if (stopWatch.ElapsedMilliseconds >= 3000) { autoDiscoverPort.Close(); } } autoDiscoverPort.Dispose(); } return(trackers); }
public void SendData(string data) { _arduinoPort.WriteLine(data); }
public void SerialPortStream_WriteReadLine_Timeout2() { using (SerialPortStream src = new SerialPortStream(c_SourcePort, 115200, 8, Parity.None, StopBits.One)) using (SerialPortStream dst = new SerialPortStream(c_DestPort, 115200, 8, Parity.None, StopBits.One)) { src.WriteTimeout = c_Timeout; src.ReadTimeout = c_Timeout; dst.WriteTimeout = c_Timeout; dst.ReadTimeout = c_Timeout; src.Open(); Assert.IsTrue(src.IsOpen); dst.Open(); Assert.IsTrue(dst.IsOpen); bool err = false; string s; src.Write("Test"); try { s = dst.ReadLine(); } catch (System.Exception e) { if (e is TimeoutException) err = true; } Assert.IsTrue(err, "No timeout exception occurred"); src.WriteLine("String"); s = dst.ReadLine(); Assert.AreEqual("TestString", s); } }
static void Main(string[] args) { Boolean bPortSet = false; Boolean bCommandSet = false; String comTarget = ""; String comCommand = ""; Console.WriteLine(""); Console.WriteLine("----------------------------------------------"); Console.WriteLine(" Welcome to the CraftComputing Epson HMD tool"); Console.WriteLine("----------------------------------------------"); Console.WriteLine(""); if (args.Length != 2) { } else { comTarget = args[0]; bPortSet = int.TryParse(comTarget, out _); if (args[1].ToLower().Equals("3don")) { comCommand = "set2d3d 1"; bCommandSet = true; } if (args[1].ToLower().Equals("3doff")) { comCommand = "set2d3d 0"; bCommandSet = true; } } if (bCommandSet && bPortSet) { var serialPort = new SerialPortStream("COM" + comTarget); try { Console.WriteLine("Opening COM" + comTarget); serialPort.OpenDirect(); Console.WriteLine("Sending " + comCommand); serialPort.WriteLine(comCommand); }catch (Exception e) { Console.WriteLine("There was an error"); Console.WriteLine(e.Message); Console.WriteLine(e.StackTrace); Console.WriteLine(e.Source); Console.WriteLine(e.InnerException); } serialPort.Close(); } else { Console.WriteLine("You did not provide the correct arguments."); Console.WriteLine(""); Console.WriteLine("The syntax is: Epson3DSwitcher <port> <command>"); Console.WriteLine("Where <port> is the number of the COM port the headset is attached to"); Console.WriteLine("and <command> is the command which can be 3DOn or 3DOff"); } }
static async Task Main(string[] args) { var port = new SerialPortStream(Credential.SerialPortDeviceName, 115200); port.NewLine = "\r\n"; port.Encoding = Encoding.ASCII; port.Open(); { port.WriteLine("SKVER"); Console.WriteLine(port.ReadLine()); Console.WriteLine(port.ReadLine()); port.WriteLine("SKINFO"); Console.WriteLine(port.ReadLine()); Console.WriteLine(port.ReadLine()); Console.WriteLine(port.ReadLine()); port.WriteLine("SKSETPWD C " + Credential.BRouteId); Console.WriteLine(port.ReadLine()); Console.WriteLine(port.ReadLine()); port.WriteLine("SKSETRBID " + Credential.BRoutePasscode); Console.WriteLine(port.ReadLine()); Console.WriteLine(port.ReadLine()); } var httpClient = new HttpClient(); scanretry: var duration = 4; var map = new Dictionary <string, string>(); while (!map.ContainsKey("Channel")) { port.WriteLine("SKSCAN 2 FFFFFFFF " + duration++); var scanEnd = false; while (!scanEnd) { var line = port.ReadLine(); Console.WriteLine(line); if (line.StartsWith("EVENT 22")) { scanEnd = true; } else if (line.StartsWith(" ")) { var str = line.Trim().Split(':'); map[str[0]] = str[1]; } } if (duration > 8) { Console.WriteLine("Duration Exceeded"); goto scanretry; } } port.WriteLine("SKSREG S2 " + map["Channel"]); Console.WriteLine(port.ReadLine()); Console.WriteLine(port.ReadLine()); port.WriteLine("SKSREG S3 " + map["Pan ID"]); Console.WriteLine(port.ReadLine()); Console.WriteLine(port.ReadLine()); port.WriteLine("SKLL64 " + map["Addr"]); Console.WriteLine(port.ReadLine()); var ipv6 = port.ReadLine().Trim(); Console.WriteLine(ipv6); port.WriteLine("SKJOIN " + ipv6); Console.WriteLine(port.ReadLine()); Console.WriteLine(port.ReadLine()); var pana = false; while (!pana) { var line = port.ReadLine(); Console.WriteLine(line); if (line.StartsWith("EVENT 24")) { Console.WriteLine("失敗"); break; } else if (line.StartsWith("EVENT 25")) { pana = true; } } port.ReadTimeout = 2000; port.WriteTimeout = 2000; while (pana) { retry: try { var echonetFrame = ""; echonetFrame += "\x10\x81"; echonetFrame += "\x00\x01"; echonetFrame += "\x05\xFF\x01"; echonetFrame += "\x02\x88\x01"; echonetFrame += "\x62"; echonetFrame += "\x01"; echonetFrame += "\xE7"; echonetFrame += "\x00"; var memory = new MemoryStream(); var writer = new BinaryWriter(memory); var tt = $"SKSENDTO 1 {ipv6} 0E1A 1 {echonetFrame.Length.ToString("X4")} "; writer.Write(Encoding.ASCII.GetBytes(tt)); writer.Write((byte)0x10); writer.Write((byte)0x81); writer.Write((byte)0x00); writer.Write((byte)0x01); writer.Write((byte)0x05); writer.Write((byte)0xFF); writer.Write((byte)0x01); writer.Write((byte)0x02); writer.Write((byte)0x88); writer.Write((byte)0x01); writer.Write((byte)0x62); writer.Write((byte)0x01); writer.Write((byte)0xE7); writer.Write((byte)0x00); var b = memory.ToArray(); port.Write(b, 0, b.Length); Console.WriteLine(port.ReadLine()); Console.WriteLine(port.ReadLine()); Console.WriteLine(port.ReadLine()); var erxudp = port.ReadLine(); Console.WriteLine(erxudp); if (erxudp.StartsWith("ERXUDP")) { var str = erxudp.Split(' '); var res = str[8]; var seoj = res.Substring(8, 6); var esv = res.Substring(20, 2); if (seoj == "028801" && esv == "72") { var epc = res.Substring(24, 2); if (epc == "E7") { var wat = int.Parse(erxudp.Substring(erxudp.Length - 8), NumberStyles.HexNumber); var request = new HttpRequestMessage(HttpMethod.Post, Credential.ApiEndpoint); request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", Credential.BearerToken); var pairs = new List <KeyValuePair <string, string> >(); pairs.Add(new KeyValuePair <string, string>("wat", wat.ToString())); request.Content = new FormUrlEncodedContent(pairs); await httpClient.SendAsync(request); Console.WriteLine("瞬時電力計測値:" + wat + " W"); } } } } catch (TimeoutException) { goto retry; } } }