/// <summary> /// Sends a string message. /// </summary> /// <param name="message">Message.</param> public void SendMessage(string message) { if (serialPort.IsConnected) { byte[] msg = Encoding.UTF8.GetBytes(message); serialPort.SendMessage(msg); } }
static void GetReadeInfo(byte reader)//04 ff 21 19 95 { byte cmd = 0x21; byte len = 0x04; var crc = CheckSum(new byte[] { len, reader, cmd }); byte[] buffer = new byte[4] { len, reader, cmd, crc }; _port485.SendMessage(buffer); //System.Console.WriteLine(CommonHelper.ByteArrayToHexString(buffer)); }
// Finger save method public static void Set(int id, Action onFinger1, Action onFinger2, Action onFinger3, Action onError) { try { onSetFinger1 = onFinger1; onSetFinger2 = onFinger2; onSetFinger3 = onFinger3; onSetError = onError; sp.SendMessage(Encoding.Default.GetBytes(id.ToString())); } catch { onError.Invoke(); } }
public static void Main(string[] args) { var servicesProvider = BuildDi(); using (servicesProvider as IDisposable) { serialPort = servicesProvider.GetRequiredService <SerialPortInput>(); serialPort.ConnectionStatusChanged += SerialPort_ConnectionStatusChanged; serialPort.MessageReceived += SerialPort_MessageReceived; while (true) { Console.WriteLine("\nPlease enter serial to open (eg. \"COM7\" or \"/dev/ttyUSB0\" without double quotes),"); Console.WriteLine("or enter \"QUIT\" to exit.\n"); Console.Write("Port [{0}]: ", defaultPort); string port = Console.ReadLine(); if (String.IsNullOrWhiteSpace(port)) { port = defaultPort; } else { defaultPort = port; } // exit if the user enters "quit" if (port.Trim().ToLower().Equals("quit")) { break; } serialPort.SetPort(port, 115200); serialPort.Connect(); Console.WriteLine("Waiting for serial port connection on {0}.", port); while (!serialPort.IsConnected) { Console.Write("."); Thread.Sleep(1000); } // This is a test message (ZWave protocol message for getting the nodes stored in the Controller) var testMessage = new byte[] { 0x01, 0x03, 0x00, 0x02, 0xFE }; // Try sending some data if connected if (serialPort.IsConnected) { Console.WriteLine("\nConnected! Sending test message 5 times."); for (int s = 0; s < 5; s++) { Thread.Sleep(2000); Console.WriteLine("\nSEND [{0}]", (s + 1)); serialPort.SendMessage(testMessage); } } Console.WriteLine("\nTest sequence completed, now disconnecting."); serialPort.Disconnect(); } } }
public static void OldMain(string[] args) { // NOTE: To disable debug output uncomment the following two lines //LogManager.Configuration.LoggingRules.RemoveAt(0); //LogManager.Configuration.Reload(); serialPort = new SerialPortInput(); serialPort.ConnectionStatusChanged += SerialPort_ConnectionStatusChanged; serialPort.MessageReceived += SerialPort_MessageReceived; while (true) { Console.WriteLine("\nPlease enter serial to open (eg. \"COM7\" or \"/dev/ttyUSB0\" without double quotes),"); Console.WriteLine("or enter \"QUIT\" to exit.\n"); Console.Write("Port [{0}]: ", defaultPort); string port = Console.ReadLine(); if (String.IsNullOrWhiteSpace(port)) { port = defaultPort; } else { defaultPort = port; } // exit if the user enters "quit" if (port.Trim().ToLower().Equals("quit")) { break; } serialPort.SetPort(port, 115200); serialPort.Connect(); Console.WriteLine("Waiting for serial port connection on {0}.", port); while (!serialPort.IsConnected) { Console.Write("."); Thread.Sleep(1000); } // This is a test message (ZWave protocol message for getting the nodes stored in the Controller) var testMessage = new byte[] { 0x01, 0x03, 0x00, 0x02, 0xFE }; // Try sending some data if connected if (serialPort.IsConnected) { Console.WriteLine("\nConnected! Sending test message 5 times."); for (int s = 0; s < 5; s++) { Thread.Sleep(1000); Console.WriteLine("\nSEND [{0}]", (s + 1)); serialPort.SendMessage(testMessage); } } Console.WriteLine("\nTest sequence completed, now disconnecting."); serialPort.Disconnect(); } }
static void Send(string data) { byte[] arr = Encoding.ASCII.GetBytes(data); byte[] packetArray = new byte[arr.Length + 2]; arr.CopyTo(packetArray, 0); packetArray[arr.Length] = byte_CarriageReturn; packetArray[arr.Length + 1] = byte_LineFeed; _port0.SendMessage(packetArray); }
static void SerialPort_MessageReceived(object sender, MessageReceivedEventArgs args) { if (args.Data != null && args.Data.Buffer != null) { Console.WriteLine("Received message: {0}", BitConverter.ToString(args.Data.Buffer)); } // On every message received we send an ACK message back to the device serialPort.SendMessage(new byte[] { 0x06 }); }
public void Write(string data) { data = "~" + data + "!"; for (int i = 0; i < data.Length; i += 1024) { byte[] bytes = Encoding.ASCII.GetBytes(data.Substring(i, i + 1024 >= data.Length ? data.Length - i : 1024)); serialPort.SendMessage(bytes); Thread.Sleep(10); } }
public void SendMessage(IPTZMessage message) { MessageSending?.Invoke(this, message.DataBytes); _logger.LogInfoMessage($"Send message. Data: {BitConverter.ToString(message.DataBytes)}"); var sendResult = _serialPort.SendMessage(message.DataBytes); if (!sendResult) { _logger.LogError($"Send message fail."); } }
public void SendFrame(FrameHeaderType header, byte[] data) { MemoryStream ms = new MemoryStream(); BinaryWriter bw = new BinaryWriter(ms); bw.Write((ushort)header); bw.Write((ushort)data.Length); bw.Write(data); bw.Write(Crc.Get_CRC16(data)); serialPort.SendMessage(ms.ToArray()); }
private void SerialPort_ConnectionStatusChanged(object sender, SerialPortLib.ConnectionStatusChangedEventArgs args) { logger.Debug("Serial Port Connected = {0}", args.Connected); if (args.Connected) { serialPort.SendMessage(ackRequest); } else { logger.Debug("W800Rf32 is offline"); OnConnectionStatusChanged(new ConnectionStatusChangedEventArgs(false)); } }
private void SendCommandsToRadio() { if (_counter < prepareRadioForCommunicationCommands.Count) { WriteSendedDataToLBox(prepareRadioForCommunicationCommands[_counter].Command); _sp.SendMessage(prepareRadioForCommunicationCommands[_counter].Command); _counter++; } else { _sp.MessageReceived -= OnMessageReceivedHandler; _sp.Disconnect(); } }
public void writeDirect(string data) { if (SerialConnection.IsConnected) { // This text is always added, making the file longer over time // if it is not deleted. if (logging) { Log(data); } SerialConnection.SendMessage(Encoding.ASCII.GetBytes(data + '\r')); } }
/// <summary> /// Sends the message. /// </summary> /// <returns>True if sending succesfull, False otherwise.</returns> /// <param name="message">Message.</param> public bool SendMessage(ZWaveMessage message) { #region Debug Utility.logger.Trace("[[[ BEGIN REQUEST ]]]"); var stopWatch = new Stopwatch(); stopWatch.Start(); #endregion SetQueryStage(QueryStage.WaitAck); pendingRequest = message; sendMessageAck.Reset(); Utility.logger.Trace("Sending Message (Node={0}, CallbackId={1}, Function={2}, CommandClass={3})", pendingRequest.NodeId, pendingRequest.CallbackId.ToString("X2"), pendingRequest.Function, pendingRequest.CommandClass); if (serialPort.SendMessage(message.RawData)) { if (!sendMessageAck.WaitOne(ZWaveMessage.SendMessageTimeoutMs)) { SetQueryStage(QueryStage.Error); // TODO: Dump Diagnostic Statistics Utility.logger.Warn("Message timeout (Node={0}, CallbackId={0}, Function={1}, CommandClass={2})", pendingRequest.NodeId, pendingRequest.CallbackId.ToString("X2"), pendingRequest.Function, pendingRequest.CommandClass); if (message.NodeId > 1) { UpdateOperationProgress(message.NodeId, NodeQueryStatus.Timeout); } //System.Diagnostics.Debugger.Break(); } } else { SetQueryStage(QueryStage.Error); Utility.logger.Warn("Controller status error (Node={0}, CallbackId={0}, Function={1}, CommandClass={2})", pendingRequest.NodeId, pendingRequest.CallbackId.ToString("X2"), pendingRequest.Function, pendingRequest.CommandClass); } pendingRequest = null; #region Debug stopWatch.Stop(); Utility.logger.Trace("[[[ END REQUEST ]]] took {0} ms", stopWatch.ElapsedMilliseconds); #endregion return(currentStage != QueryStage.Error); }
private async Task <bool> TryConnect([NotNull] string portName) { _serialPort.SetPort(portName, 57600); _currentPort = portName; _serialPort.Connect(); await Task.Delay(TimeSpan.FromMilliseconds(500)); var timer = Observable.Timer(TimeSpan.FromMilliseconds(1000)); timer.TakeUntil(_serialDataStream).Subscribe(_ => Close(null)); _serialPort.SendMessage(Encoding.ASCII.GetBytes("get info")); await timer; return(_serialPort.IsConnected); }
private static bool RequestPort(PortEnvRequest portEnvRequest) { bool isSend = false; byte[] buffer = PortEnvRequest.Pack(portEnvRequest); isSend = serialPortInput.SendMessage(buffer); if (!isSend) { Console.WriteLine("串口数据发送失败"); return(false); } else { Console.WriteLine($"串口发送: + {BitConverter.ToString(buffer)}"); return(true); } }
// PaketGonder Metodu private void PaketGonder(CommPro commPro) { commPro.txBuffer.Clear(); commPro.txBuffer.Add(SendPacket.sof1); commPro.txBuffer.Add(SendPacket.sof2); commPro.txBuffer.Add(SendPacket.packetType); commPro.txBuffer.Add(++SendPacket.packetCounter); commPro.txBuffer.Add(SendPacket.dataSize); for (int i = 0; i < SendPacket.dataSize; i++) { commPro.txBuffer.Add(SendPacket.data[i]); } commPro.txBuffer.Add(SendPacket.eof1); commPro.txBuffer.Add(SendPacket.eof2); serialPort.SendMessage(commPro.txBuffer.ToArray()); }
private static void Senden(byte[] b, bool warte_freigabe = true) { while (!freigabe && warte_freigabe) { } string s = BitConverter.ToString(b); if (DebugAusgabe) { Ausgabe("Schreibe " + s); } byte[] b_tmp = new byte[b.Length + 1]; b.CopyTo(b_tmp, 0); b_tmp[b.Length] = 0x0d; port.SendMessage(b_tmp); freigabe = false; }
static bool Write(string data) { byte[] packetArray = Encoding.ASCII.GetBytes(data); return(_portESP32.SendMessage(packetArray)); }
private void button1_Click(object sender, EventArgs e) { byte[] cmd = GetCommand(0, 20); serialPort.SendMessage(cmd); }
void SerialPort_MessageReceived(object sender, MessageReceivedEventArgs args) { if (cancelled) { closeSerial(); return; } // get received data for (UInt16 i = 0; i < args.Data.Length; i++) { receivedData[currentReceiveIndex++] = args.Data[i]; } // check if echo of command is correct for (UInt16 i = 0; i < Math.Min(10, currentReceiveIndex); i++) { if (receivedData[i] != readCommand[i]) { // Console.WriteLine("Received bad message: {0} {1}", receivedData[4], ByteToHexBitFiddle(args.Data)); cancelled = true; closeSerial(); return; } } // check expected length (10+1024+1) if (currentReceiveIndex < 1035) { return; } // check correct buffer end if (receivedData[currentReceiveIndex - 1] != (Byte)0x10) { cancelled = true; closeSerial(); return; } // Console.WriteLine("Received message: {0} {1}", receivedData[4], ByteToHexBitFiddle(args.Data)); if (receivedData[8] == 0xf7) { percentage = 100; readCommand = new Byte[] { (Byte)'E', (Byte)'N', (Byte)'D' }; } else { percentage += (float)2.5; readCommand = new Byte[] { 0x68, 0x31, 0x00, 0x01, (Byte)Math.Min((Byte)Math.Round(percentage), (Byte)100), 0xCD, 0x00, 0x04, (Byte)(receivedData[8] + 1), 0x1D, 0x10 }; } SetProgressBarSafe(progressPercent); // percent.Text = String.Format("Completion percentage {0}%", GetPercentage); currentReceiveIndex = 0; // Console.WriteLine("Sending message: {0}", ByteToHexBitFiddle(readCommand)); serialPort.SendMessage(readCommand); if (readCommand.Length == 3) { DialogResult result = MessageBox.Show("Read OK !", "HD1 GPS", MessageBoxButtons.OK, MessageBoxIcon.Exclamation); if (result == DialogResult.OK) { } closeSerial(); } }
public bool sendMessage(byte[] message) { return(serialPort.SendMessage(message)); }
public static bool write(byte[] packet) { return(_serialPort.SendMessage(packet)); }
public bool Write(string message) { var packet = Encoding.ASCII.GetBytes(message); return(serialPortInput.SendMessage(packet)); }
public void Discovery() { serialPort.SendMessage(new byte[] { 0x01, 0x03, 0x00, 0x02, 0xFE }); }
public HttpServer() { #region 初始化串口 int baudRate = 38400; string portName = "COM1"; try { baudRate = Convert.ToInt32(ConfigurationManager.AppSettings["BaudRate"]); } catch (Exception) { Console.WriteLine("波特率获取失败"); return; } if (Environment.OSVersion.Platform.ToString().StartsWith("Win")) { portName = ConfigurationManager.AppSettings["WinPortName"]; } else { portName = ConfigurationManager.AppSettings["LinuxPortName"]; } if (string.IsNullOrWhiteSpace(portName)) { Console.WriteLine("串口获取失败"); return; } serialPortInput.ConnectionStatusChanged += SerialPortInput_ConnectionStatusChanged; serialPortInput.MessageReceived += SerialPortInput_MessageReceived; serialPortInput.SetPort(portName, baudRate); serialPortInput.Connect(); Console.Write($"等待串口{portName}连接"); while (!serialPortInput.IsConnected) { Console.Write("."); Thread.Sleep(1000); } Console.WriteLine($"\n串口{portName}连接成功"); serialPortInput.SendMessage(new byte[] { 0x01, 0x00, 0x00, 0x00, 0x01, 0x00, 0x0A, 0x00, 0x01, 0x00 }); #endregion #region 初始化服务器 var listener = new System.Net.Http.HttpListener(IPAddress.Any, 8081); try { listener.Request += async(sender, context) => { var request = context.Request; var response = context.Response; //如果是GET请求 if (request.HttpMethod == HttpMethods.Get) { string content = @"<h2>提供POST方法测试</h2> <form method=""POST"" action=""http://192.168.123.166:8081/login""> <input name=""data""></input> <button type=""submit"">Send</button> </form>"; await response.WriteContentAsync(MakeDocument(content)); } //如果是POST请求 else if (request.HttpMethod == HttpMethods.Post) { var data = await request.ReadUrlEncodedContentAsync(); //登录 if (request.Url.LocalPath.ToLower().Contains("login")) { ProcessLogin(data, response); } //获取数据 else if (request.Url.LocalPath.ToLower().Contains("getdata")) { ProcessGetData(data, response); } //控制开关 else if (request.Url.LocalPath.ToLower().Contains("control")) { ProcessControl(data, response); } //登出 else if (request.Url.LocalPath.ToLower().Contains("logout")) { ProcessLogOut(data, response); } else { //请求出错 } } else { response.MethodNotAllowed(); } response.Close(); }; listener.Start(); Console.WriteLine("服务器已启动..."); } catch (Exception exc) { Console.WriteLine(exc.ToString()); listener.Close(); } #endregion }