private void SendDisplayString(string displayString) { if (displayString == null || String.Equals(displayString, _lastDisplayStringSent, StringComparison.Ordinal)) { return; } lock (_serialPortLock) { try { if (_serialPort == null || !_serialPort.IsOpen || displayString == null) { return; } var cobsEncodedPacket = COBS.Encode(Encoding.ASCII.GetBytes(displayString)); _serialPort.Write(cobsEncodedPacket, offset: 0, count: cobsEncodedPacket.Length); _serialPort.Write(new byte[] { 0 }, 0, 1); _serialPort.BaseStream.Flush(); _lastDisplayStringSent = displayString; _bytesSentSignal.State = cobsEncodedPacket.Length; } catch (Exception e) { _log.Error(e.Message, e); } } }
/// <summary> /// Arduino Initialization Method /// </summary> public void Initialize() { if (!_comPort.IsOpen) { throw new InvalidOperationException(String.Format( "[{0}] Unable to initialize arduino because the port {1} is closed!", MethodBase.GetCurrentMethod().Name, _comPortName)); } Log.Print(String.Format("Initializing Arduino with initialization byte on port {0}...", _comPortName), eCategory.Error, LogTag.COMMUNICATION); try { byte initByte = _encoder.EncodeInitialization(); _comPort.Write(initByte); } catch (Exception ex) { throw new InvalidOperationException(String.Format( "[{0}] Unable to initialize arduino. Reason: {1}", MethodBase.GetCurrentMethod().Name, ex.Message), ex); } _isInitialized = true; }
void SendCommand(byte cmd, byte[] args = null, byte argn = 0) { serialPort.Write(new byte[] { 0x56, serialNum, cmd }); for (byte i = 0; i < argn; i++) { serialPort.Write(new byte[] { args[i] }); } }
public void sendRegCommand(Accel_Register reg) { if (!highLevelSerialPort.IsPortOpen()) { MessageBox.Show("Port is not opened yet"); return; } byte[] DataOut = { DOLLAR_SIGN, SET_ACCEL_REGISTER, reg.address, reg.value, CHAR_CR }; highLevelSerialPort.Write(DataOut); }
protected override bool SetupDevice() { m_timer.SetInterval(base.Interval); if (!OpenSerialPort()) { return(false); } if (m_delayafteropen > 0) { m_stop.WaitOne(m_delayafteropen / 1000); } //bytes per channel m_bytes = 1; while (Math.Round(Math.Pow(256, m_bytes)) <= m_max) { m_bytes++; } //allocate a buffer, that can hold the prefix,the number of bytes per channel and the postfix m_buffsize = m_prefix.Count + m_channels.Count * m_bytes + m_postfix.Count; m_buff = new byte[m_buffsize]; //copy in the prefix if (m_prefix.Count > 0) { Array.Copy(m_prefix.ToArray(), m_buff, m_prefix.Count); } //copy in the postfix if (m_postfix.Count > 0) { Array.Copy(m_postfix.ToArray(), 0, m_buff, m_prefix.Count + m_channels.Count * m_bytes, m_postfix.Count); } //memcpy(m_buff + m_prefix.Count + m_channels.Count * m_bytes, &m_postfix[0], m_postfix.Count); //set channel bytes to 0, write it twice to make sure the controller is in sync //memset(m_buff + m_prefix.Count, 0, m_channels.Count * m_bytes); for (int i = 0; i < 2; i++) { if (m_serialport.Write(m_buff, m_buffsize) == -1) { Util.LogError($"{Name}: {m_serialport.GetError()}"); return(false); } } return(true); }
void SendMessage(object o) { if (o is byte[]) { _port.Write((byte[])o); Thread.Sleep(_port.AfterWriteDelay); return; } Message m = (Message)o; #if DEBUG m.PerformanceInfo.TimeStartedProcessing = DateTime.Now; #endif MessageEventArgs args = null; var e = BeforeMessageSent; if (e != null) { args = new MessageEventArgs(m); e(args); if (args.Cancel) { return; } } _port.Write(m.Packet); // Flush DBus port if (_port.WriteBufferSize == 1) { _port.Flush(); } #if DEBUG m.PerformanceInfo.TimeEndedProcessing = DateTime.Now; #endif e = AfterMessageSent; if (e != null) { if (args == null) { args = new MessageEventArgs(m); } e(args); } Thread.Sleep(m.AfterSendDelay > 0 ? m.AfterSendDelay : _port.AfterWriteDelay); // Don't flood iBus m = null; // will it optimize memory usage??? }
private async void Send(string text) { _serialPort.Write(text); ReceivedText += await _serialPort.ReadAsync() + Environment.NewLine; SendText = string.Empty; }
public SerialPortHub(params ISerialPort[] ports) { this.ports = ports; queues = new QueueThreadWorker[ports.Length]; for (int i = 0; i < ports.Length; i++) { int index = i; ISerialPort port = ports[index]; queues[index] = new QueueThreadWorker((o) => { byte[] data = (byte[])o; port.Write(data, 0, data.Length); }); } for (int i = 0; i < ports.Length; i++) { int index = i; ISerialPort port = ports[index]; // Read each port and forward data to other ports port.DataReceived += (s, e) => { byte[] data = port.ReadAvailable(); Write(data, 0, data.Length, index); OnDataReceived(data, data.Length); }; } }
/// <summary> /// Write the buffer of data to the COM port (i.e. the display). /// </summary> /// <param name="buffer">Bytes of data to be sent to the display.</param> private void Send(byte[] buffer) { // critical section so we don't have mixed messages lock (_lock) { comPort.Write(buffer, 0, buffer.Length); } }
static void SendMessage(object o) { if (o is byte[]) { iBus.Write((byte[])o); Thread.Sleep(iBus.AfterWriteDelay); return; } Message m = (Message)o; #if DEBUG m.PerformanceInfo.TimeStartedProcessing = DateTime.Now; #endif MessageEventArgs args = null; var e = BeforeMessageSent; if (e != null) { args = new MessageEventArgs(m); e(args); if (args.Cancel) { return; } } iBus.Write(m.Packet); #if DEBUG m.PerformanceInfo.TimeEndedProcessing = DateTime.Now; #endif e = AfterMessageSent; if (e != null) { if (args == null) { args = new MessageEventArgs(m); } e(args); } Thread.Sleep(m.AfterSendDelay > 0 ? m.AfterSendDelay : iBus.AfterWriteDelay); // Don't flood iBus }
private void SendCommandList(IEnumerable <RWRCommand> commandList) { var rwrCommands = commandList as RWRCommand[] ?? commandList.ToArray(); if (!rwrCommands.Any()) { return; } lock (_serialPortLock) { using (var ms = new MemoryStream()) { var totalBytes = 0; foreach (var command in rwrCommands) { //write out device identifier to memory stream var deviceIdBytes = Encoding.ASCII.GetBytes(_deviceID); ms.Write(deviceIdBytes, 0, deviceIdBytes.Length); totalBytes += deviceIdBytes.Length; //write out the bytes for this command to memory stream var thisCommandBytes = command.ToBytes(); if (thisCommandBytes != null && thisCommandBytes.Length > 0) { ms.Write(thisCommandBytes, 0, thisCommandBytes.Length); totalBytes += thisCommandBytes.Length; } //write contents of memory stream to COM port ms.Seek(0, SeekOrigin.Begin); var bytesToWrite = new byte[totalBytes]; Array.Copy(ms.GetBuffer(), 0, bytesToWrite, 0, totalBytes); if (bytesToWrite.SequenceEqual(_lastBytesWritten)) { continue; } try { _log.DebugFormat( $"Sending bytes to serial port {_comPort}:{BytesToString(bytesToWrite, 0, totalBytes)}"); for (var i = 0; i < bytesToWrite.Length; i++) { _serialPort.Write(bytesToWrite, i, 1); Thread.Sleep((int)_delayBetweenCharactersMillis); _serialPort.BaseStream.Flush(); } _lastBytesWritten = bytesToWrite; } catch (Exception e) { _log.Error(e.Message, e); } Thread.Sleep((int)_delayBetweenCommandsMillis); } } } }
public bool Send(string strcmd) { bool rt = false; int errorCode = 0; string errorMsg = "发送成功"; try { if (ISerialPort == null || (!ISerialPort.IsOpen)) { errorCode = 1; if (ISerialPort == null) { errorMsg = "SerialPort对象为空"; errorMsg = string.Format("串口:[{0}]{1}", ISerialPort.PortName, errorMsg); } if (!ISerialPort.IsOpen) { errorMsg = "SerialPort对象未连接"; errorMsg = string.Format("串口:[{0}]{1}", ISerialPort.PortName, errorMsg); } return(rt); } // Convert to byte array and send. byte[] cmdBuffer = Encoding.Default.GetBytes(strcmd); ISerialPort.Write(cmdBuffer, 0, cmdBuffer.Length); rt = true; } catch (Exception ex) { Close(); Property.IsConnected = false; if (ClosedEvt != null) { System.Windows.Forms.Control target = ClosedEvt.Target as System.Windows.Forms.Control; errorCode = 1; errorMsg = string.Format("串口[{0}]{1}", ISerialPort.PortName, ex.Message); if (target != null && target.InvokeRequired) { //非创建控件线程同步调用事件:SerialPortClosed target.Invoke(ClosedEvt, new object[] { errorCode, errorMsg }); } else { //创建控件线程调用事件 ClosedEvt(Property, errorCode, errorMsg); } } } finally { } return(rt); }
private void SendDrawingCommands(String drawingCommands) { lock (_serialPortLock) { try { if (_serialPort != null && _serialPort.IsOpen && drawingCommands != null) { var bytesToWrite = Encoding.ASCII.GetBytes(drawingCommands + " "); _serialPort.Write(bytesToWrite, 0, bytesToWrite.Length); _serialPort.Write(PacketMarker, 0, 1); _serialPort.BaseStream.Flush(); } } catch (Exception e) { _log.Error(e.Message, e); } } }
private bool TrySendReceive() { //Console.WriteLine("Trying with {0}", _port.BaudRate); _internalOp = true; _port.Write(Encoding.ASCII.GetBytes("AT")); if (!_signal.WaitOne(2000)) { _internalOp = false; //Console.WriteLine("timeout"); return(false); } byte[] buffer = new byte[_port.BytesToRead]; _port.Read(buffer, 0, buffer.Length); string response = Encoding.ASCII.GetString(buffer); //Console.WriteLine(response); return(response == "OK"); }
private void Write(byte[] bytes) { try { _serialPort.DiscardInBuffer(); _serialPort.DiscardOutBuffer(); _serialPort.Write(bytes, 0, bytes.Length); } catch (Exception e) { throw new TransmissionException(e); } }
// FIXME public override void AdjustInterval(uint index, uint interval) { port.WriteByte((byte)Command.AdjustInterval); var bInterval = new byte[4]; bInterval[0] = (byte)((byte)interval & 0xFF); interval >>= 8; bInterval[1] = (byte)((byte)interval & 0xFF); interval >>= 8; bInterval[2] = (byte)((byte)interval & 0xFF); interval >>= 8; bInterval[3] = (byte)((byte)interval & 0xFF); port.Write(bInterval); }
public EchoStatus Send(byte[] message, bool retryOnNak, int echoLength) { if (port == null) { throw new InvalidOperationException(); } port.SetNotify(null); EchoStatus status = EchoStatus.None; try { ProcessData(); // process any pending data before sending a new command var input = new byte[message.Length + 1]; input[0] = Constants.MessageStartByte; message.CopyTo(input, 1); int retry = -1; while (retry++ < Constants.sendMessageRetries) { if (retry <= 0) { logger.DebugFormat("TX: {0}", Utilities.ByteArrayToString(input)); } else { Thread.Sleep(retry * Constants.sendMessageWaitTime); logger.DebugFormat("TX: {0} - RETRY {1} of {2}", Utilities.ByteArrayToString(input), retry, Constants.sendMessageRetries); } port.Write(input); status = ProcessEcho(echoLength + 2); // +1 for leading 02 byte, +1 for trailing ACK/NAK byte if (status == EchoStatus.ACK) { return(status); } if (status == EchoStatus.NAK && !retryOnNak) { return(status); } } logger.DebugFormat("Send failed after {0} retries", Constants.sendMessageRetries); return(status); } finally { port.SetNotify(DataAvailable); } }
private void SendDrawingCommands(string svgPathString) { lock (_serialPortLock) { try { if (_serialPort == null || !_serialPort.IsOpen || svgPathString == null) { return; } var drawPoints = new SVGPathToVectorScopePointsListConverter(bezierCurveInterpolationSteps: BEZIER_CURVE_INTERPOLATION_STEPS) .ConvertToDrawPoints(svgPathString) .ApplyCentering(_config.Centering) .ApplyInversion(VIEWBOX_WIDTH, VIEWBOX_HEIGHT, invertX: false, invertY: true) .ApplyRotation(VIEWBOX_WIDTH / 2.0, VIEWBOX_HEIGHT / 2.0, _config.RotationDegrees) .ApplyScaling(_config.Scaling.ScaleX, _config.Scaling.ScaleY, VIEWBOX_WIDTH, VIEWBOX_HEIGHT) .ApplyCalibration(_config.XAxisCalibrationData, _config.YAxisCalibrationData) .ApplyClipping(VIEWBOX_WIDTH, VIEWBOX_HEIGHT) ; var drawPointsAsBytes = drawPoints.Select(x => (byte[])x).SelectMany(x => x).ToArray(); var cobsEncodedPacket = COBS.Encode(drawPointsAsBytes); _serialPort.Write(cobsEncodedPacket, offset: 0, count: cobsEncodedPacket.Length); _serialPort.Write(new byte[] { 0 }, 0, 1); _serialPort.BaseStream.Flush(); _numDrawPointsSentSignal.State = drawPoints.Count(); _bytesSent.State = cobsEncodedPacket.Length; } catch (Exception e) { _log.Error(e.Message, e); } } }
private void WriteSerialData(string msg) { switch (CurrentTransmissionType) { case TransmissionType.Text: //first make sure the port is open //if its not open then open it if (!(comSerialPort.IsOpen == true)) { comSerialPort.Open(_serialPortConnectInformation); } //send the message to the port comSerialPort.Write(msg + "\r"); // Add 0x0D at the end, to match Nuvo Essentia needs //display the message DisplayData(MessageType.Outgoing, msg + "\n"); break; case TransmissionType.Hex: //display error message DisplayData(MessageType.Error, "Transmission type 'Hex' is not supported for this serial port"); break; default: //first make sure the port is open //if its not open then open it if (!(comSerialPort.IsOpen == true)) { comSerialPort.Open(_serialPortConnectInformation); } //send the message to the port comSerialPort.Write(msg); //display the message DisplayData(MessageType.Outgoing, msg + "\n"); break; } }
private void SendCommand(Commands command, byte data1 = 0, byte data2 = 0) { byte[] sendBuffer = new byte[8]; Thread.Sleep(20); // Command Structure 0x7E 0xFF 0x06 CMD FBACK DAT1 DAT2 0xEF sendBuffer[0] = 0x7E; // Start byte sendBuffer[1] = 0xFF; // Version sendBuffer[2] = 0x06; // Command length not including Start and End byte. sendBuffer[3] = (byte)command; // Command sendBuffer[4] = 0x01; // Feedback 0x00 NO, 0x01 YES sendBuffer[5] = data2; // DATA1 datah sendBuffer[6] = data2; // DATA2 datal sendBuffer[7] = 0xEF; // End byte serialPort.Write(sendBuffer); }
/// <summary> /// Send telegram. Add leading '*' and 'carriage return' sign at end /// </summary> /// <param name="telegram">The telegram without leading '*' and ending 'carriage return'</param> public void SendTelegram(string telegram) { if ((telegram != null) && (telegram.Length > 0)) { string text = telegram; if (text[0] != _startSendCharacter[0]) { text = text.Insert(0, _startSendCharacter); } if (text[text.Length - 1] != '\r') { text += '\r'; // Add 0x0D at the end, to match Nuvo Essentia needs } _serialPort.Write(text); } else { _log.Warn(m => m("Empty telegram received, not passed to the serial port!")); } }
public virtual bool SendData(byte[] buffer, int wait = 1000, [CallerMemberName] string memberName = "") { CommandReplyed = false; WriteResponse = false; if (_port != null) { _port.Write(buffer, 0, buffer.Length); } if (wait > 0) { DateTime start = DateTime.Now; TimeSpan ts = new TimeSpan(wait * TICK_TO_MILISECONDS); while (!CommandReplyed && ts > DateTime.Now - start) { Thread.Sleep(1); } } return(CommandReplyed); //_logger.LogDebug("Tx : " + BitConverter.ToString(buffer) + Environment.NewLine); }
protected void SendCommandToCamera(Command command, byte[] args) { var commandIndex = 0; _command[commandIndex++] = CommandSend; _command[commandIndex++] = CameraSerial; _command[commandIndex++] = (byte)command; var argsLength = 0; if (args != null) { argsLength = args.Length; _command[commandIndex++] = (byte)argsLength; Array.Copy(args, 0, _command, commandIndex, argsLength); } else { _command[commandIndex++] = 0; } _serialPort.Write(_command, 0, argsLength + 4); }
public string ExecCommand(ISerialPort port, string command, int responseTimeout, string errorMessage) { try { port.DiscardOutBuffer(); port.DiscardInBuffer(); _receiveNow.Reset(); port.Write(command + "\r"); string input = ReadResponse(port, responseTimeout); if ((input.Length == 0) || ((!input.EndsWith("\r\n> ")) && (!input.EndsWith("\r\nOK\r\n")))) { throw new ApplicationException("No success message was received."); } return(input); } catch (Exception ex) { throw ex; } }
private Acknowledgement WriteCommand(Command cmd) { _commandID++; Acknowledgement ack = new Acknowledgement(cmd, _commandID); byte[] wbuffer = _protocol.GetWriteBytes(ack); try { _port.Write(wbuffer, 0, wbuffer.Length); Console.Write("Writing: "); Protocol.PrintArray(wbuffer); } catch (IOException) { Console.WriteLine("While writing an IOException occured"); StopConnection(); return(null); } return(ack); }
private bool CheckIfHeater(ISerialPort port) { if (!port.IsOpen) { throw new ArgumentException("The serial port has to be open to check if the heater is connected to it.", "port"); } HeaterCommand cmd = HeaterCommand.build(HeaterCommand.commandType.MagicByte); byte[] buff; try { port.Write(cmd.toByte()); buff = port.ReadBytes(1); } catch (TimeoutException) { return false; } return buff[0] == magicResponse; }
/// <summary> /// Validates version, burning the bundled firmware if needed. /// </summary> /// <returns>The version.</returns> /// <param name="aPort">A port.</param> IEnumerator CheckVersion(ISerialPort aPort) { m_portPath = m_serialPort.OpenPortPath(); #if UNITY_STANDALONE_WIN || UNITY_WP8 int comPortNumber; #endif aPort.Write(@"version? "); yield return(new UnityEngine.WaitForSeconds(0.05f)); string versionString; aPort.Read(16, out versionString); versionString = versionString.Trim(); UnityEngine.Debug.Log("Firmware Version from Propeller = \"" + versionString + "\""); UnityEngine.Debug.Log("Firmware Version in Li = \"" + versionAsset.text + "\""); if (versionString.Contains(versionAsset.text.Trim())) { Text.Log(@"Firmware version {0}.", versionString); m_wasProgrammingSuccessful = true; } #if UNITY_STANDALONE_WIN || UNITY_WP8 else if (int.TryParse(m_portPath.Substring(3), out comPortNumber) && comPortNumber > 9) { string message = string.Format(@"Update failed: Try removing unused/hidden com ports in Device Manager & restart Li."); Dispatcher <string> .Broadcast(PanelController.kEventShowMessage, message); Text.Log("Aborting after detecting {0} com ports.", comPortNumber); yield return(new WaitForSeconds(20.0f)); enabled = false; Dispatcher <Panel> .Broadcast(PanelController.kEventClosePanel, Panel.Message); } #endif else { m_serialPort.Close(); string message = string.Format(@"Burning firmware v. {0} /", versionAsset.text.Trim()); Dispatcher <string> .Broadcast(PanelController.kEventShowMessage, message); Text.Log("{0} over {1}", message, versionString); int timeout = 3; int spinIndex = 0; while (timeout-- > 0) { m_programmingThread = new Thread(new ParameterizedThreadStart(ProgramEeprom)); m_programmingThread.Start(Application.streamingAssetsPath + @"/Firmware/"); //encodedBinary); int programmingTimeoutSec = 60; while (m_programmingThread.IsAlive && programmingTimeoutSec-- > 0) { yield return(new WaitForSeconds(1.0f)); message = message.Remove(message.Length - 1); message += kSpinning[++spinIndex % kSpinning.Length]; Dispatcher <string> .Broadcast(PanelController.kEventShowMessage, message); } if (programmingTimeoutSec < 1) { Text.Log("Aborting programming thread; passed {0}", m_programmingError); m_programmingThread.Abort(); } m_programmingThread = null; Text.Log("Burning result: {0}", m_programmingError); if (m_wasProgrammingSuccessful) { message = string.Format(@"Burning successful."); Dispatcher <string> .Broadcast(PanelController.kEventShowMessage, message); Text.Log(message); yield return(new WaitForSeconds(1.0f)); Dispatcher <Panel> .Broadcast(PanelController.kEventClosePanel, Panel.Message); break; } else { message = string.Format(@"Still burning {0}", kSpinning[++spinIndex % kSpinning.Length]); Dispatcher <string> .Broadcast(PanelController.kEventShowMessage, message); Text.Log(message); yield return(new WaitForSeconds(0.5f)); } } if (timeout <= 0) { message = string.Format(@"Burning failed. Try closing Li, rebooting the printer, and restarting."); Dispatcher <string> .Broadcast(PanelController.kEventShowMessage, message); Text.Log(message); yield return(new WaitForSeconds(1.0f)); enabled = false; Dispatcher <Panel> .Broadcast(PanelController.kEventClosePanel, Panel.Message); } m_serialPort.OpenPort(m_portPath, kBaudRate); } }
public async Task SetCtcss_on_2digit() { await rig.SetCtcss(80); A.CallTo(() => fakeSerialPort.Write(0x4a, 0, 0, 0, 0x0a)).MustHaveHappened(); A.CallTo(() => fakeSerialPort.Write(0x08, 0x00, 0, 0, 0x0b)).MustHaveHappened(); }
public Dictionary <PropertyKey, int> Connect(InsteonConnection connection) { port?.Close(); port = SerialPortCreator.Create(connection); port.Open(); byte[] input = { Constants.MessageStartByte, (byte)InsteonModemSerialCommand.GetImInfo }; var properties = new Dictionary <PropertyKey, int>(); var response = new List <byte>(); try { for (int i = 1; i <= Constants.negotiateRetries; ++i) { logger.DebugFormat("TX: {0}", Utilities.ByteArrayToString(input)); port.Write(input); port.Wait(Constants.openTimeout); var output = port.ReadAll(); if (output.Length <= 0) { Thread.Sleep(100); continue; // try again } response.Clear(); response.AddRange(output); while (output.Length > 0 && response.Count < 9) { port.Wait(Constants.openTimeout); output = port.ReadAll(); response.AddRange(output); } logger.DebugFormat("RX: {0}", Utilities.ByteArrayToString(response.ToArray())); int offset = 0; // determins the start location of the actual message returned for (int j = 0; j < response.Count; ++j) { if (response[j] == Constants.MessageStartByte) { offset = j; } } if (response.Count >= offset + 9 && response[offset] == Constants.MessageStartByte && response[offset + 1] == (byte)InsteonModemSerialCommand.GetImInfo && response[offset + 8] == Constants.MessageEndByte) { properties[PropertyKey.Address] = response[offset + 2] << 16 | response[offset + 3] << 8 | response[offset + 4]; properties[PropertyKey.DevCat] = response[offset + 5]; properties[PropertyKey.SubCat] = response[offset + 6]; properties[PropertyKey.FirmwareVersion] = response[offset + 7]; break; // found } } } finally { if (response.Count == 0) { throw new IOException("Failed to open port, timeout waiting for response from port."); } if (properties.Keys.Count == 0) { port.Close(); port = null; throw new IOException("Failed to open port, unable to negotiate with INSTEON controller."); } } logger.DebugFormat("Successfully negotiated with INSTEON controller on connection '{0}'...", connection); port.SetNotify(DataAvailable); return(properties); }
public Dictionary<PropertyKey, int> Connect(InsteonConnection connection) { port?.Close(); port = SerialPortCreator.Create(connection); port.Open(); byte[] input = { Constants.MessageStartByte, (byte)InsteonModemSerialCommand.GetImInfo }; var properties = new Dictionary<PropertyKey, int>(); var response = new List<byte>(); try { for (int i = 1; i <= Constants.negotiateRetries; ++i) { logger.DebugFormat("TX: {0}", Utilities.ByteArrayToString(input)); port.Write(input); port.Wait(Constants.openTimeout); var output = port.ReadAll(); if (output.Length <= 0) { Thread.Sleep(100); continue; // try again } response.Clear(); response.AddRange(output); while (output.Length > 0 && response.Count < 9) { port.Wait(Constants.openTimeout); output = port.ReadAll(); response.AddRange(output); } logger.DebugFormat("RX: {0}", Utilities.ByteArrayToString(response.ToArray())); int offset = 0; // determins the start location of the actual message returned for (int j = 0; j < response.Count; ++j) { if (response[j] == Constants.MessageStartByte) { offset = j; } } if (response.Count >= offset + 9 && response[offset] == Constants.MessageStartByte && response[offset + 1] == (byte)InsteonModemSerialCommand.GetImInfo && response[offset + 8] == Constants.MessageEndByte) { properties[PropertyKey.Address] = response[offset + 2] << 16 | response[offset + 3] << 8 | response[offset + 4]; properties[PropertyKey.DevCat] = response[offset + 5]; properties[PropertyKey.SubCat] = response[offset + 6]; properties[PropertyKey.FirmwareVersion] = response[offset + 7]; break; // found } } } finally { if (response.Count == 0) { throw new IOException("Failed to open port, timeout waiting for response from port."); } if (properties.Keys.Count == 0) { port.Close(); port = null; throw new IOException("Failed to open port, unable to negotiate with INSTEON controller."); } } logger.DebugFormat("Successfully negotiated with INSTEON controller on connection '{0}'...", connection); port.SetNotify(DataAvailable); return properties; }
/// <summary> /// Finds a printer using the specified serial connection. /// </summary> /// <returns> /// An enumerator for a coroutine. /// </returns> /// <param name='aSerialPort'> /// A serial port connection. /// </param> IEnumerator FindPrinter(ISerialPort aSerialPort) { m_foundPrinter = false; int timeout = kLoopTimeout; while (!aSerialPort.isConnected && timeout-- > 0) { string[] availablePorts = m_serialPort.AvailablePorts(); Text.Log(@"Found {0} available port{1}.", availablePorts.Length, Text.S(availablePorts.Length)); foreach (string aPortPath in availablePorts) { Text.Log(@"Trying to open {0}", aPortPath); bool success = false; try { success = aSerialPort.OpenPort(aPortPath, kBaudRate); Text.Log("Opened {0} at {1}.", aPortPath, kBaudRate); } catch (System.Exception e) { Text.Error(e); continue; } if (success) { // Unity reboots the Propeller on OSX but not on Windows. yield return(StartCoroutine(ResetCoroutine())); // We're in text mode upon startup, so try pinging. aSerialPort.Write("ping "); // Not blocking, so wait a bit. yield return(new UnityEngine.WaitForSeconds(1.0f)); //0.02f); string response = "(null)"; int numRead = aSerialPort.Read(8, out response); response = response.Trim(); Text.Log("Received {0} byte{1}: {2}", numRead, Text.S(numRead), response); if (response.Contains("pong")) { yield return(StartCoroutine(CheckVersion(aSerialPort))); m_foundPrinter = m_wasProgrammingSuccessful; if (m_foundPrinter) { Text.Log("Connected to " + aPortPath); aSerialPort.Write("data "); m_threadsActive = true; m_txThread = new Thread(TransmitData); m_txThread.Name = "Tx Thread"; m_txThread.Start(); m_rxThread = new Thread(ReceiveData); m_rxThread.Name = "Rx Thread"; m_rxThread.Start(); Dispatcher.Broadcast(kOnSerialConnectionEstablished); } yield break; } aSerialPort.Close(); yield return(null); } } yield return(new WaitForSeconds(1)); } if (timeout <= 0) { Text.Log(@"Couldn't find printer."); enabled = false; } }
void TransmitData() { byte[] txBuffer = new byte[Printer.kRxBufferSize]; int bytesAvailable = 0; TxLog("Starting tx loop."); while (m_threadsActive) { try { while (m_threadsActive && bytesAvailable < kMinRxBufferSpaceRequired) { // Ensure that the RX buffer updates. Thread.Sleep(kSecToMs * 2); // Update our bytes free before sending data. m_dispatchSemaphore.WaitOne(); bytesAvailable = m_lastBufferAvailable; m_lastBufferAvailable = 0; m_dispatchSemaphore.Release(); } TxLog("Bytes available: {0}.", bytesAvailable); while (m_threadsActive && m_dataBeingTransmitted.Count < 1) { bool swapped = false; m_packetSemaphore.WaitOne(); if (m_dataToTransmit.Count > 0) { TxLog("Acquired new tx buffer."); swapped = true; Queue <TxPacket> temp = m_dataToTransmit; m_dataToTransmit = m_dataBeingTransmitted; m_dataBeingTransmitted = temp; } m_packetSemaphore.Release(); // NOTE(kevin): This is where we'll spend most of our // time waiting for commands. 200ms is approx. the // speed of a double click. if (!swapped) { Thread.Sleep(200); } } int numTxBytes = 0; TxLog("Packets pending: {0}", m_dataBeingTransmitted.Count); while (m_threadsActive && m_dataBeingTransmitted.Count > 0 && bytesAvailable >= kMinRxBufferSpaceRequired) { TxPacket aPacket = m_dataBeingTransmitted.Dequeue(); // Figure out what we need to send. switch (aPacket.aCmd) { case GanglionCommand.Value: int aValue = aPacket.anArgument; if (aValue <= 127) { aValue += 128; txBuffer[numTxBytes++] = (byte)aValue; bytesAvailable--; } else if (aValue <= 0xFF) { txBuffer[numTxBytes++] = (byte)GanglionCommand.Value1; txBuffer[numTxBytes++] = (byte)(aValue & 0xFF); bytesAvailable -= 2; } else if (aValue <= 0xFFFF) { txBuffer[numTxBytes++] = (byte)GanglionCommand.Value2; txBuffer[numTxBytes++] = (byte)(aValue & 0xFF); txBuffer[numTxBytes++] = (byte)((aValue >> 8) & 0xFF); bytesAvailable -= 3; } else if (aValue <= 0xFFFFFF) { txBuffer[numTxBytes++] = (byte)GanglionCommand.Value3; txBuffer[numTxBytes++] = (byte)(aValue & 0xFF); txBuffer[numTxBytes++] = (byte)((aValue >> 8) & 0xFF); txBuffer[numTxBytes++] = (byte)((aValue >> 16) & 0xFF); bytesAvailable -= 4; } else { txBuffer[numTxBytes++] = (byte)GanglionCommand.Value4; txBuffer[numTxBytes++] = (byte)(aValue & 0xFF); txBuffer[numTxBytes++] = (byte)((aValue >> 8) & 0xFF); txBuffer[numTxBytes++] = (byte)((aValue >> 16) & 0xFF); txBuffer[numTxBytes++] = (byte)((aValue >> 24) & 0xFF); bytesAvailable -= 5; } break; default: if (aPacket.aCmd == GanglionCommand.Error) { TxLog("ERROR: Sending GanglionCommand.Error."); } txBuffer[numTxBytes++] = (byte)aPacket.aCmd; bytesAvailable--; break; } } TxLog("Bytes to send: {0}", numTxBytes); if (numTxBytes > 0) { int bytesSent = m_serialPort.Write(txBuffer, numTxBytes); if (bytesSent >= 0) { TxLog("Bytes sent: {0}.\n", bytesSent); } else { TxLog("Write error: {0}.\n", m_serialPort.error); } } } catch (System.Threading.ThreadAbortException) { break; } catch (System.Exception e) { TxLog(e.ToString()); } } TxLog("Closing."); }