public VicarDevice(OperatingMode mode, params string[] devicePaths) { Mode = mode; _receivedMessages = new List<VicarMessage>(); _urbs = new Dictionary<uint, Urb>(); _Init(devicePaths); }
public Core(OperatingMode aMode, string aEmail, string aPassword) { Initialization(); Mode = aMode; Email = aEmail; Password = aPassword; }
public ActionResult OperatingModeDelete(int?id) { if (id == null) { return(new HttpStatusCodeResult(HttpStatusCode.BadRequest)); } OperatingMode operatingMode = db.OperatingModes.Find(id); if (operatingMode == null) { return(HttpNotFound()); } return(View(operatingMode)); }
/** * Class constructor. Instantiates a new {@code DataReader} object for the * given connection interface using the given XBee operating mode and XBee * device. * * @param connectionInterface Connection interface to read data from. * @param mode XBee operating mode. * @param xbeeDevice Reference to the XBee device containing this * {@code DataReader} object. * * @throws ArgumentNullException if {@code connectionInterface == null} or * {@code mode == null}. * * @see IConnectionInterface * @see com.digi.xbee.api.XBeeDevice * @see com.digi.xbee.api.models.OperatingMode */ public DataReader(IConnectionInterface connectionInterface, OperatingMode mode, XBeeDevice xbeeDevice) { if (connectionInterface == null) throw new ArgumentNullException("Connection interface cannot be null."); if (mode == null) throw new ArgumentNullException("Operating mode cannot be null."); this.connectionInterface = connectionInterface; this.mode = mode; this.xbeeDevice = xbeeDevice; this.logger = LogManager.GetLogger<DataReader>(); parser = new XBeePacketParser(); xbeePacketsQueue = new XBeePacketsQueue(); }
public void SetOperationMode(OperatingMode mode) { if (Mode == mode) { return; } _i2cDevice.Write(REGISTERS.OPR_MODE); var current = _i2cDevice.Read(); current &= 0b_1111_0000; //Clear last 4 bits; current |= (byte)mode; _i2cDevice.Write(new ReadOnlySpan <byte>(new byte[] { REGISTERS.OPR_MODE, current })); }
/** * Reads one byte from the input stream. * * <p>This operation checks several things like the working mode in order * to consider escaped bytes.</p> * * @param inputStream Input stream to read bytes from. * @param mode XBee device working mode. * * @return The read byte. * * @throws InvalidPacketException if there is not enough data in the stream or * if there is an error verifying the checksum. * @throws IOException if the first byte cannot be read for any reason other than end of file, or * if the input stream has been closed, or * if some other I/O error occurs. */ private int ReadByte(Stream inputStream, OperatingMode mode) /*throws InvalidPacketException, IOException*/ { Contract.Requires <ArgumentNullException>(inputStream != null, "Input stream cannot be null."); Contract.Requires <ArgumentException>(inputStream.CanRead); int timeout = 300; int b = ReadByteFrom(inputStream, timeout); if (b == -1) { throw new InvalidPacketException("Error parsing packet: Incomplete packet."); } /* Process the byte for API1. */ if (mode == OperatingMode.API) { return(b); } /* Process the byte for API2. */ // Check if the byte is special. if (!SpecialByte.ESCAPE_BYTE.IsSpecialByte((byte)b)) { return(b); } // Check if the byte is ESCAPE. if (b == SpecialByte.ESCAPE_BYTE.GetValue()) { // Read next byte and escape it. b = ReadByteFrom(inputStream, timeout); if (b == -1) { throw new InvalidPacketException("Error parsing packet: Incomplete packet."); } b ^= 0x20; } else { // If the byte is not a escape there is a special byte not escaped. throw new InvalidPacketException("Special byte not escaped: 0x" + HexUtils.ByteToHexString((byte)(b & 0xFF)) + "."); } return(b); }
public void From_To_Byte( RxB1Ctrl.Filter filterHit, bool receivedRemoteTransferRequest, OperatingMode receiveBufferOperatingMode, byte expectedByte) { var rxB1Ctrl = new RxB1Ctrl(filterHit, receivedRemoteTransferRequest, receiveBufferOperatingMode); Assert.Equal(filterHit, rxB1Ctrl.FilterHit); Assert.Equal(receivedRemoteTransferRequest, rxB1Ctrl.ReceivedRemoteTransferRequest); Assert.Equal(receiveBufferOperatingMode, rxB1Ctrl.ReceiveBufferOperatingMode); Assert.Equal(expectedByte, rxB1Ctrl.ToByte()); Assert.Equal(expectedByte, new RxB1Ctrl(expectedByte).ToByte()); }
public void AddOperatingMode_OperatingModeAddGoal_AddGoalReturned() { OperatingMode execute = OperatingMode.AddGoal; OperatingMode actual = default; try { db.AddUser("1", "1", OperatingMode.NON); actual = db.ChangeOperatingMode(1, OperatingMode.AddGoal); } finally { db.ClearTable("Users"); } }
public override void Empty() { base.Empty(); Operating = OperatingMode.Unknown; Fix = FixMode.Unknown; PositionDilutionOfPrecision = 0.0D; HorizontalDilutionOfPrecision = 0.0D; VerticalDilutionOfPrecision = 0.0D; for (int index = 0; index < Satellites.Length; index++) { Satellites[index] = 0; } }
public void GetFrequencyRange(OperatingMode mode, out short minFreq, out short maxFreq) { minFreq = maxFreq = 0; if (mode == OperatingMode.AdaptiveMobile) { minFreq = MobileMinFrequency; maxFreq = MobileMaxFrequency; } else if (mode == OperatingMode.AdaptivePortal) { minFreq = PortalMinFrequency; maxFreq = PortalMaxFrequency; } }
public MainForm() { InitializeComponent(); LoadingForm loadingForm = new LoadingForm(); loadingForm.ShowDialog(); Mode = loadingForm.Mode; if (Mode == OperatingMode.OnlineNormal || Mode == OperatingMode.OnlineAdvanced) { Email = loadingForm.Email; Password = loadingForm.Password; LoadDownloadedPlugins(loadingForm.DownloadedPlugins); } try { mCore = new Core(Mode, Email, Password); mCore.SpeechRecognizedCoreEvent += new Core.SpeechRecognizedCoreEventHandler(mCore_SpeechRecognizedCoreEvent); } catch (InvalidOperationException ex) { RadMessageBox.Show("You have to connect the microphone before executing the program!", "Error"); this.Close(); } this.MaximumSize = this.Size; this.MinimumSize = this.Size; gridViewPlugins.AllowAutoSizeColumns = true; gridViewPlugins.AutoSizeColumnsMode = Telerik.WinControls.UI.GridViewAutoSizeColumnsMode.Fill; gridViewPlugins.AllowAutoSizeColumns = true; gridViewPlugins.AutoSizeColumnsMode = Telerik.WinControls.UI.GridViewAutoSizeColumnsMode.Fill; gridViewPlugins.CommandCellClick += new CommandCellClickEventHandler(gridViewPlugins_CommandCellClick); labelStatusInStatusStrip.Text = ""; labelStatusInStatusStrip.TextChanged += new EventHandler(labelStatusInStatusStrip_TextChanged); notifyIcon = new NotifyIcon(); notifyIcon.Visible = true; labelStatusInStatusTripTimer.Tick += new EventHandler(labelStatusInStatusTripTimer_Tick); this.Show(); }
public bool SetStaticPulseFrequency(OperatingMode mode, uint freq, bool confirm) { if (/*terminated?*/ _cancelEvent.WaitOne(0)) { return(false); } CommandDefinition.CommandFormat command = ConstructCommand(CommandEnum.StaticPulseFreq, BooleanValue.True, ActionEnum.Set, (byte)mode); BitConverter.GetBytes(freq).CopyTo(command.Payload, 0); CommandDefinition.CommandFormat?response = SendCommand(command, confirm); if (confirm && (!ConfirmSetActionResponse(response, CommandEnum.StaticPulseFreq, (byte)mode) || freq != BitConverter.ToInt32(response.Value.Payload, 0))) { return(false); } return(true); }
public bool SetAdaptiveModeTriggerRatio(OperatingMode mode, float ratio, bool confirm) { if (/*terminated?*/ _cancelEvent.WaitOne(0)) { return(false); } CommandDefinition.CommandFormat command = ConstructCommand(CommandEnum.AdaptiveModeToTrigRatio, BooleanValue.True, ActionEnum.Set, (byte)mode); BitConverter.GetBytes(ratio).CopyTo(command.Payload, 0); CommandDefinition.CommandFormat?response = SendCommand(command, confirm); if (confirm && (!ConfirmSetActionResponse(response, CommandEnum.AdaptiveModeToTrigRatio, (byte)mode) || ratio != BitConverter.ToSingle(response.Value.Payload, 0))) { return(false); } return(true); }
/** * Parses the bytes from the given array depending on the provided operating * mode and returns the API packet. * * <p>The operating mode must be {@link OperatingMode#API} or * {@link OperatingMode#API_ESCAPE}.</p> * * @param packetByteArray Byte array with the complete frame, starting from * the header and ending in the checksum. * @param mode XBee device operating mode. * * @return Parsed packet from the given byte array. * * @throws InvalidPacketException if there is not enough data in the array or * if there is an error verifying the checksum or * if the payload is invalid for the specified frame type. * @throws ArgumentException if {@code mode != OperatingMode.API } and * if {@code mode != OperatingMode.API_ESCAPE}. * @throws ArgumentNullException if {@code packetByteArray == null} or * if {@code mode == null}. * * @see XBeePacket * @see com.digi.xbee.api.models.OperatingMode#API * @see com.digi.xbee.api.models.OperatingMode#API_ESCAPE */ public XBeePacket ParsePacket(byte[] packetByteArray, OperatingMode mode) { Contract.Requires <ArgumentNullException>(packetByteArray != null, "Packet byte array cannot be null."); Contract.Requires <ArgumentNullException>(mode != null, "Operating mode cannot be null."); Contract.Requires <ArgumentException>(mode == OperatingMode.API || mode == OperatingMode.API_ESCAPE, "Operating mode must be API or API Escaped."); Contract.Requires <InvalidOperationException>(packetByteArray.Length >= 4, "Error parsing packet: Incomplete packet."); // Check the header of the frame. if ((packetByteArray[0] & 0xFF) != SpecialByte.HEADER_BYTE.GetValue()) { throw new InvalidPacketException("Invalid start delimiter (expected 0x" + HexUtils.ByteToHexString((byte)SpecialByte.HEADER_BYTE.GetValue()) + ")."); } return(ParsePacket(new MemoryStream(packetByteArray, 1, packetByteArray.Length - 1), mode)); }
/// <summary> /// Parses the bytes from the given <paramref name="inputStream"/> depending on the provided /// <paramref name="mode"/> and returns the API packet. /// </summary> /// <remarks>The operating mode must be <see cref="OperatingMode.API"/> or /// <see cref="OperatingMode.API_ESCAPE"/>.</remarks> /// <param name="inputStream">Input stream to read bytes from.</param> /// <param name="mode">XBee device operating mode.</param> /// <returns>Parsed packet from the input stream.</returns> /// <exception cref="ArgumentException">If <paramref name="mode"/> is invalid /// or if the <paramref name="inputStream"/> cannot be read.</exception> /// <exception cref="ArgumentNullException">If <paramref name="inputStream"/> is <c>null</c>.</exception> /// <exception cref="InvalidPacketException">If there is not enough data in the stream or if there /// is an error verifying the checksum or if the payload is invalid for the specified frame type.</exception> public XBeePacket ParsePacket(Stream inputStream, OperatingMode mode) { if (inputStream == null) { throw new ArgumentNullException("Input stream cannot be null."); } if (!inputStream.CanRead) { throw new ArgumentException("Could not read from the input stream."); } if (mode != OperatingMode.API && mode != OperatingMode.API_ESCAPE) { throw new ArgumentException("Operating mode must be API or API Escaped."); } try { // Read packet size. int hSize = ReadByte(inputStream, mode); int lSize = ReadByte(inputStream, mode); int Length = hSize << 8 | lSize; // Read the payload. byte[] payload = ReadBytes(inputStream, mode, Length); // Calculate the expected checksum. XBeeChecksum checksum = new XBeeChecksum(); checksum.Add(payload); byte expectedChecksum = (byte)(checksum.Generate() & 0xFF); // Read checksum from the input stream. byte readChecksum = (byte)(ReadByte(inputStream, mode) & 0xFF); // Verify the checksum of the read bytes. if (readChecksum != expectedChecksum) { throw new InvalidPacketException("Invalid checksum (expected 0x" + HexUtils.ByteToHexString(expectedChecksum) + ")."); } return(ParsePayload(payload)); } catch (IOException e) { throw new InvalidPacketException("Error parsing packet: " + e.Message, e); } }
private void CheckModeChange() { OperatingMode currentOperatingMode = CarInformation.Instance().GetOperatingMode(); if (currentOperatingMode != _currentOperatingModePrevFrame) { if (CarInformation.Instance().GetOperatingMode() == OperatingMode.CameraMode) { frame = _uiCamTexPlaneBig.GetComponent <MeshRenderer>(); } else { frame = _uiCamTexPlaneSmall.GetComponent <MeshRenderer>(); } } _currentOperatingModePrevFrame = currentOperatingMode; }
public string Examine(Vector3 worldPos = default) { string stateDescription = powerState == PowerState.Off ? "unpowered." : IsTurnedOn == false ? "turned off." : OperatingMode == Mode.Siphoning && IsExpandedRange ? "manically siphoning!" : $"{OperatingMode.ToString().ToLower()}."; if (isWelded) { return(IsOperating ? $"It is tenaciously welded shut, but you can still hear the induction motor {stateDescription}" : $"It is teanciously welded shut and is dead silent. It seems to be {stateDescription}"); } return($"It seems to be {stateDescription}"); }
private void Update() { if (Input.GetKeyDown(KeyCode.F1) && OperatingMode != OperatingMode.KeyBoard) { OperatingMode = OperatingMode.KeyBoard; MessageBox.Show("OP Mode = KeyBoard"); } else if (Input.GetKeyDown(KeyCode.F2) && OperatingMode != OperatingMode.Arduino) { OperatingMode = OperatingMode.Arduino; MessageBox.Show("OP Mode = Arduino"); } else if (Input.GetKeyDown(KeyCode.F3) && OperatingMode != OperatingMode.AI) { OperatingMode = OperatingMode.AI; MessageBox.Show("OP Mode = AI"); } }
void Start() { _uiCamTexPlaneBig = ManagerObjects.Instance().GetObject(EnumObjects.UICamPlaneBig); _uiCamTexPlaneSmall = ManagerObjects.Instance().GetObject(EnumObjects.UICamPlaneSmall); _currentOperatingModePrevFrame = CarInformation.Instance().GetOperatingMode(); Connect(); if (CarInformation.Instance().GetOperatingMode() == OperatingMode.CameraMode) { frame = _uiCamTexPlaneBig.GetComponent <MeshRenderer>(); } else { frame = _uiCamTexPlaneSmall.GetComponent <MeshRenderer>(); } }
/** * Class constructor. Instantiates a new {@code DataReader} object for the * given connection interface using the given XBee operating mode and XBee * device. * * @param connectionInterface Connection interface to read data from. * @param mode XBee operating mode. * @param xbeeDevice Reference to the XBee device containing this * {@code DataReader} object. * * @throws ArgumentNullException if {@code connectionInterface == null} or * {@code mode == null}. * * @see IConnectionInterface * @see com.digi.xbee.api.XBeeDevice * @see com.digi.xbee.api.models.OperatingMode */ public DataReader(IConnectionInterface connectionInterface, OperatingMode mode, XBeeDevice xbeeDevice) { if (connectionInterface == null) { throw new ArgumentNullException("Connection interface cannot be null."); } if (mode == null) { throw new ArgumentNullException("Operating mode cannot be null."); } this.connectionInterface = connectionInterface; this.mode = mode; this.xbeeDevice = xbeeDevice; this.logger = LogManager.GetLogger <DataReader>(); parser = new XBeePacketParser(); xbeePacketsQueue = new XBeePacketsQueue(); }
private void SpeedModePanel_Update() { OperatingMode mode = DetectorsAccess.Apcs.AdaptiveSpeedMode; OperatingModePortalAdaptivePNL.Background = Brushes.Transparent; OperatingModeMobileAdaptivePNL.Background = Brushes.Transparent; if (mode == OperatingMode.AdaptiveMobile) { OperatingModeMobileAdaptivePNL.Background = Brushes.LightGreen; } else if (mode == OperatingMode.AdaptivePortal) { OperatingModePortalAdaptivePNL.Background = Brushes.LightGreen; } if ((mode == OperatingMode.AdaptiveMobile) || (mode == OperatingMode.AdaptivePortal)) { SpeedFeedbackFrequencyTBX.Text = DetectorsAccess.Apcs.AdaptiveSpeed.ToString(); } }
/// <summary> /// Reads the given amount of bytes from the input stream. /// </summary> /// <remarks>This operation checks several things like the working mode in order to consider /// escaped bytes.</remarks> /// <param name="inputStream">The Input stream to read bytes from.</param> /// <param name="mode">The XBee device working mode.</param> /// <param name="numBytes">The number of bytes to read.</param> /// <returns>The read byte array.</returns> /// <exception cref="ArgumentException">If input stream cannot be read.</exception> /// <exception cref="ArgumentNullException">If <paramref name="inputStream"/> is <c>null</c>.</exception> private byte[] ReadBytes(Stream inputStream, OperatingMode mode, int numBytes) { if (inputStream == null) { throw new ArgumentNullException("Input stream cannot be null."); } if (!inputStream.CanRead) { throw new ArgumentException("Could not read from the input stream."); } byte[] data = new byte[numBytes]; for (int i = 0; i < numBytes; i++) { data[i] = (byte)ReadByte(inputStream, mode); } return(data); }
public bool GetStaticPulseFrequency(OperatingMode?selectedMode, out OperatingMode?mode, out int?freq, bool confirm) { mode = null; freq = null; if (/*terminated?*/ _cancelEvent.WaitOne(0)) { return(false); } CommandDefinition.CommandFormat command = ConstructCommand(CommandEnum.StaticPulseFreq, BooleanValue.False, ActionEnum.Get, (byte)selectedMode); CommandDefinition.CommandFormat?response = SendCommand(command, confirm); if (response != null && response.Value.CommandAck.Command == CommandEnum.StaticPulseFreq && response.Value.Action.Action == ActionEnum.Response) { mode = (OperatingMode)OperatingMode.ToObject(typeof(OperatingMode), response.Value.Action.SubAction); freq = BitConverter.ToInt32(response.Value.Payload, 0); return(true); } else { return(false); } }
public bool GetAdaptiveModeTriggerRatio(OperatingMode?selectedMode, out OperatingMode?mode, out float?ratio, bool confirm) { mode = null; ratio = null; if (/*terminated?*/ _cancelEvent.WaitOne(0)) { return(false); } CommandDefinition.CommandFormat command = ConstructCommand(CommandEnum.AdaptiveModeToTrigRatio, BooleanValue.False, ActionEnum.Get, (byte)selectedMode); CommandDefinition.CommandFormat?response = SendCommand(command, confirm); if (response != null && response.Value.CommandAck.Command == CommandEnum.AdaptiveModeToTrigRatio && response.Value.Action.Action == ActionEnum.Response) { mode = (OperatingMode)OperatingMode.ToObject(typeof(OperatingMode), response.Value.Action.SubAction); ratio = BitConverter.ToSingle(response.Value.Payload, 0); return(true); } else { return(false); } }
public bool GetAdaptiveSpeedFeedbackConfiguration(out AdaptiveSpeedFeedbackConfig?config, out float?freq, bool confirm) { config = null; freq = null; if (/*terminated?*/ _cancelEvent.WaitOne(0)) { return(false); } CommandDefinition.CommandFormat command = ConstructCommand(CommandEnum.AdaptiveSpeedFeedbackConfig, BooleanValue.False, ActionEnum.Get, 0); CommandDefinition.CommandFormat?response = SendCommand(command, confirm); if (response != null && response.Value.CommandAck.Command == CommandEnum.AdaptiveSpeedFeedbackConfig && response.Value.Action.Action == ActionEnum.Response) { config = (AdaptiveSpeedFeedbackConfig)OperatingMode.ToObject(typeof(AdaptiveSpeedFeedbackConfig), response.Value.Action.SubAction); freq = BitConverter.ToSingle(response.Value.Payload, 0); return(true); } else { return(false); } }
public bool GetOperatingMode(out OperatingMode?mode, out short?minFreq, out short?maxFreq, bool confirm) { mode = null; minFreq = null; maxFreq = null; if (/*terminated?*/ _cancelEvent.WaitOne(0)) { return(false); } CommandDefinition.CommandFormat command = ConstructCommand(CommandEnum.OperatingMode, BooleanValue.False, ActionEnum.Get, 0); CommandDefinition.CommandFormat?response = SendCommand(command, confirm); if (response != null && response.Value.CommandAck.Command == CommandEnum.OperatingMode && response.Value.Action.Action == ActionEnum.Response) { mode = (OperatingMode)OperatingMode.ToObject(typeof(OperatingMode), response.Value.Action.SubAction); minFreq = BitConverter.ToInt16(response.Value.Payload, 0); maxFreq = BitConverter.ToInt16(response.Value.Payload, 2); return(true); } else { return(false); } }
public HMC5883L(II2cBus i2CBus, byte address = 0x1E, SamplesToAverage samplesToAverage = SamplesToAverage.One, DataOutputRate dataOutputRate = DataOutputRate._15Hz, MeasurementMode measurementMode = MeasurementMode.Normal, GainConfiguration gainConfiguration = GainConfiguration._1_30, OperatingMode operatingMode = OperatingMode.SingleMeasurement ) { Mode = operatingMode; Gain = gainConfiguration; _device = new I2cPeripheral(i2CBus, address); // Config - Register A byte configRegisterAData = 0b0000_0000; configRegisterAData |= (byte)samplesToAverage; configRegisterAData |= (byte)dataOutputRate; configRegisterAData |= (byte)measurementMode; _device.WriteRegister(CRA, configRegisterAData); Console.WriteLine($"CRA: {Convert.ToString(configRegisterAData, 2).PadLeft(8, '0')}"); // Config - Register A byte configRegisterBData = 0b0000_0000; configRegisterBData |= (byte)gainConfiguration; _device.WriteRegister(CRB, configRegisterBData); Console.WriteLine($"CRB: {Convert.ToString(configRegisterBData, 2).PadLeft(8, '0')}"); // Select Mode byte modeRegisterData = 0b00000000; modeRegisterData |= (byte)operatingMode; _device.WriteRegister(MR, modeRegisterData); Console.WriteLine($"MR: {Convert.ToString(modeRegisterData, 2).PadLeft(8, '0')}"); }
public XBeePacket ParsePacket(SerialPort serialPort, OperatingMode mode) { Contract.Requires <ArgumentNullException>(serialPort != null, "Input stream cannot be null."); Contract.Requires <ArgumentException>(serialPort.IsOpen); Contract.Requires <ArgumentException>(mode == OperatingMode.API || mode == OperatingMode.API_ESCAPE, "Operating mode must be API or API Escaped."); try { // Read packet size. int hSize = ReadByte(serialPort, mode); int lSize = ReadByte(serialPort, mode); int Length = hSize << 8 | lSize; // Read the payload. byte[] payload = ReadBytes(serialPort, mode, Length); // Calculate the expected checksum. XBeeChecksum checksum = new XBeeChecksum(); checksum.Add(payload); byte expectedChecksum = (byte)(checksum.Generate() & 0xFF); // Read checksum from the input stream. byte readChecksum = (byte)(ReadByte(serialPort, mode) & 0xFF); // Verify the checksum of the read bytes. if (readChecksum != expectedChecksum) { throw new InvalidPacketException("Invalid checksum (expected 0x" + HexUtils.ByteToHexString(expectedChecksum) + ")."); } return(ParsePayload(payload)); } catch (IOException e) { throw new InvalidPacketException("Error parsing packet: " + e.Message, e); } }
/// <summary> /// Parses the given byte array and returns an XBee packet. /// </summary> /// <remarks>The string can contain white spaces.</remarks> /// <param name="packet">The byte array to parse.</param> /// <param name="mode">The operating mode to parse the packet (<see cref="OperatingMode.API"/> or /// <see cref="OperatingMode.API_ESCAPE"/>).</param> /// <returns>The generated XBee Packet.</returns> /// <exception cref="ArgumentException">If <c><paramref name="mode"/> != <see cref="OperatingMode.API"/></c> /// and if <c><paramref name="mode"/> != <see cref="OperatingMode.API_ESCAPE"/></c> /// or if the length of <paramref name="packet"/> is 0 /// or if the <paramref name="packet"/> does not have the correct start delimiter.</exception> /// <exception cref="ArgumentNullException">If <c><paramref name="packet"/> == null</c>.</exception> /// <seealso cref="OperatingMode.API"/> /// <seealso cref="OperatingMode.API_ESCAPE"/> public static XBeePacket ParsePacket(byte[] packet, OperatingMode mode) { if (packet == null) { throw new ArgumentNullException("Packet byte array cannot be null."); } if (mode != OperatingMode.API && mode != OperatingMode.API_ESCAPE) { throw new ArgumentException("Operating mode must be API or API Escaped."); } if (packet.Length == 0) { throw new ArgumentException("Packet Length should be greater than 0."); } if (packet.Length != 1 && packet[0] != (byte)SpecialByte.HEADER_BYTE) { throw new ArgumentException("Invalid start delimiter."); } XBeePacketParser parser = new XBeePacketParser(); XBeePacket xbeePacket = parser.ParsePacket(new MemoryStream(packet, 1, packet.Length - 1), mode); return(xbeePacket); }
/// <summary> /// Parses the bytes from the given array depending on the provided operating mode and /// returns the API packet. /// </summary> /// <remarks>The operating mode must be <see cref="OperatingMode.API"/> or /// <see cref="OperatingMode.API_ESCAPE"/></remarks> /// <param name="packetByteArray">Byte array with the complete frame, starting from the /// header and ending in the checksum.</param> /// <param name="mode">XBee device operating mode.</param> /// <returns>Parsed packet from the given byte array.</returns> /// <exception cref="InvalidPacketException">If there is not enough data in the array /// or if there is an error verifying the checksum /// or if the payload is invalid for the specified frame type.</exception> /// <exception cref="ArgumentException">If <c><paramref name="mode"/> != <see cref="OperatingMode.API"/></c> /// and if <c><paramref name="mode"/> != <see cref="OperatingMode.API_ESCAPE"/></c></exception> /// <exception cref="ArgumentNullException">If <c><paramref name="packetByteArray"/> == null</c>.</exception> /// <seealso cref="XBeePacket"/> /// <seealso cref="OperatingMode.API"/> /// <seealso cref="OperatingMode.API_ESCAPE"/> public XBeePacket ParsePacket(byte[] packetByteArray, OperatingMode mode) { if (packetByteArray == null) { throw new ArgumentNullException("Packet byte array cannot be null."); } if (mode != OperatingMode.API && mode != OperatingMode.API_ESCAPE) { throw new ArgumentException("Operating mode must be API or API Escaped."); } if (packetByteArray.Length < 4) { throw new InvalidPacketException("Error parsing packet: Incomplete packet."); } // Check the header of the frame. if ((packetByteArray[0] & 0xFF) != SpecialByte.HEADER_BYTE.GetValue()) { throw new InvalidPacketException("Invalid start delimiter (expected 0x" + HexUtils.ByteToHexString(SpecialByte.HEADER_BYTE.GetValue()) + ")."); } return(ParsePacket(new MemoryStream(packetByteArray, 1, packetByteArray.Length - 1), mode)); }
/// <summary> /// Gets the operating mode ID. /// </summary> /// <param name="source"></param> /// <returns>Operating mode ID.</returns> public static int GetID(this OperatingMode source) { return((int)source); }
public void EnableDhcp(OperatingMode mode, bool enable) { if (mode == OperatingMode.Unknown) throw new ArgumentException("Invalid value","mode"); EnsureInitialized(); lock (_oplock) { int arg = -1; switch (mode) { case OperatingMode.Station: arg = 1; break; case OperatingMode.AccessPoint: arg = 0; break; case OperatingMode.Both: arg = 2; break; } _esp.SendAndExpect(SetDhcpMode + arg + ',' + (enable ? '1' : '0'), OK); } }
/** * Parses the bytes from the given array depending on the provided operating * mode and returns the API packet. * * <p>The operating mode must be {@link OperatingMode#API} or * {@link OperatingMode#API_ESCAPE}.</p> * * @param packetByteArray Byte array with the complete frame, starting from * the header and ending in the checksum. * @param mode XBee device operating mode. * * @return Parsed packet from the given byte array. * * @throws InvalidPacketException if there is not enough data in the array or * if there is an error verifying the checksum or * if the payload is invalid for the specified frame type. * @throws ArgumentException if {@code mode != OperatingMode.API } and * if {@code mode != OperatingMode.API_ESCAPE}. * @throws ArgumentNullException if {@code packetByteArray == null} or * if {@code mode == null}. * * @see XBeePacket * @see com.digi.xbee.api.models.OperatingMode#API * @see com.digi.xbee.api.models.OperatingMode#API_ESCAPE */ public XBeePacket ParsePacket(byte[] packetByteArray, OperatingMode mode) { Contract.Requires<ArgumentNullException>(packetByteArray != null, "Packet byte array cannot be null."); Contract.Requires<ArgumentNullException>(mode != null, "Operating mode cannot be null."); Contract.Requires<ArgumentException>(mode == OperatingMode.API || mode == OperatingMode.API_ESCAPE, "Operating mode must be API or API Escaped."); Contract.Requires<InvalidOperationException>(packetByteArray.Length >= 4, "Error parsing packet: Incomplete packet."); // Check the header of the frame. if ((packetByteArray[0] & 0xFF) != SpecialByte.HEADER_BYTE.GetValue()) throw new InvalidPacketException("Invalid start delimiter (expected 0x" + HexUtils.ByteToHexString((byte)SpecialByte.HEADER_BYTE.GetValue()) + ")."); return ParsePacket(new MemoryStream(packetByteArray, 1, packetByteArray.Length - 1), mode); }
public void SetFrequencyRange(OperatingMode mode, short minFreq, short maxFreq) { if (mode == OperatingMode.AdaptiveMobile) { MobileMinFrequency = minFreq; MobileMaxFrequency = maxFreq; } else if (mode == OperatingMode.AdaptivePortal) { PortalMinFrequency = minFreq; PortalMaxFrequency = maxFreq; } }
public void SendOperatingModeResponse(OperatingMode mode, short minimum, short maximum) { byte[] frqMax = BitConverter.GetBytes(maximum); byte[] frqMin = BitConverter.GetBytes(minimum); byte[] data = new byte[frqMin.Length + frqMax.Length]; frqMax.CopyTo(data, frqMin.Length); frqMin.CopyTo(data, 0); CommandDefinition.CommandFormat packet = ReplyCreate(CommandEnum.OperatingMode, BooleanValue.True, ActionEnum.Response, (byte)mode, data); ReplySend(packet); }
/// <summary> /// Function for PacketListener to loop in /// </summary> private void Run() { try { stop = false; while (!stop) { byte[] rawPacket = TryReadPacket(xbeeDevice.OpMode); if (rawPacket != null) { // If the protocol is 802.15.4, check if the packet is valid. If not, skip it if (xbeeDevice.Protocol == XBeeProtocol.Byte.RAW_802_15_4 && !CheckPacket802_15_4(rawPacket)) { continue; } // Build the packet XBeeAPIPacket readPacket; try { readPacket = (XBeeAPIPacket)Factory.BuildFrame(rawPacket, xbeeDevice.OpMode); } catch (InvalidPacketException e) { Log.Error(String.Format("Error processing packet {0} : {1}", Utils.BytesToHexString(rawPacket, true), e.Message)); continue; } Log.Debug(String.Format(XBeeDevice.LOG_PATTERN, xbeeDevice.ComPort.PortName, "RECEIVED", OperatingMode.Get(xbeeDevice.OpMode), Utils.BytesToHexString(rawPacket, true))); // Add the packet to the queue AddPacketQueue(readPacket); // If the packet has information about a remote device, extract it and update the remote device RemoteXBeeDevice remote = TryAddRemoteDevice(readPacket); // Execute callbacks to process API packets OnPacketReceivedAPI(readPacket); ExecuteUserCallbacks(readPacket, remote); } } } catch (Exception e) { if (!stop) { Log.Error(e); Console.Write(e.StackTrace); } } finally { if (!stop) { stop = true; if (comPort.IsOpen) { comPort.Close(); } } } }
/// <summary/> public bool SetOperatingMode(OperatingMode mode, ushort frequencyMinimum, ushort frequencyMaximum, bool confirm) { bool status = false; try { CommandDefinition.CommandFormat command = CommandMake(CommandEnum.OperatingMode, BooleanValue.True, ActionEnum.Set, (byte)mode); BitConverter.GetBytes(frequencyMinimum).CopyTo(command.Payload, 0); BitConverter.GetBytes(frequencyMaximum).CopyTo(command.Payload, 2); CommandDefinition.CommandFormat? reply = CommandSend(command, /*reply expected*/ true); if (/*ignore results?*/ !confirm) status = true; else { string text = CommandReplyValidate(reply, CommandEnum.OperatingMode, (byte)mode); if (/*fail?*/ !string.IsNullOrWhiteSpace(text)) throw new Exception(text); if (/*fail?*/ frequencyMinimum != BitConverter.ToInt16(reply.Value.Payload, 0)) throw new Exception("frequencyMinimum != " + frequencyMinimum.ToString()); else if (/*fail?*/ frequencyMaximum != BitConverter.ToInt16(reply.Value.Payload, 2)) throw new Exception("frequencyMaximum != " + frequencyMaximum.ToString()); status = true; } } catch (Exception ex) { Debug.Assert(!status); if (/*OK to log?*/ LogPauseExpired) try { Logger.LogError(Utilities.TextTidy(ex.ToString())); } catch { } } #if DEBUG try { Logger.LogInfo(MethodBase.GetCurrentMethod() + "(" + mode.ToString() + ", " + frequencyMinimum.ToString() + ", " + frequencyMaximum.ToString() + ", " + confirm.ToString() + ") returns " + status.ToString()); } catch { } #endif return status; }
/*throws InvalidPacketException, IOException*/ private int ReadByte(SerialPort serialPort, OperatingMode mode) { Contract.Requires<ArgumentNullException>(serialPort != null, "Input stream cannot be null."); Contract.Requires<ArgumentException>(serialPort.IsOpen); int timeout = 300; int b = ReadByteFrom(serialPort, timeout); if (b == -1) throw new InvalidPacketException("Error parsing packet: Incomplete packet."); /* Process the byte for API1. */ if (mode == OperatingMode.API) return b; /* Process the byte for API2. */ // Check if the byte is special. if (!SpecialByte.ESCAPE_BYTE.IsSpecialByte((byte)b)) return b; // Check if the byte is ESCAPE. if (b == SpecialByte.ESCAPE_BYTE.GetValue()) { // Read next byte and escape it. b = ReadByteFrom(serialPort, timeout); if (b == -1) throw new InvalidPacketException("Error parsing packet: Incomplete packet."); b ^= 0x20; } else // If the byte is not a escape there is a special byte not escaped. throw new InvalidPacketException("Special byte not escaped: 0x" + HexUtils.ByteToHexString((byte)(b & 0xFF)) + "."); return b; }
private void ResponseThreadMethod() { int length = Marshal.SizeOf(typeof(CommandDefinition.CommandFormat)); do { while (Connected) { try { byte[] response = new byte[length]; int dataRead = _networkStream.Read(response, 0, response.Length); if (dataRead > 0) { CommandDefinition.CommandFormat commandResponse = _commandResponse.Deserialize(response); if (commandResponse.CommandAck.Command == CommandEnum.SignOfLife) { SignOfLifeSequence = BitConverter.ToUInt32(commandResponse.Payload, 0); if (_signOfLifeTimer != null) _signOfLifeTimer.Change(_signOfLifeTimerDueTime, Timeout.Infinite); } else if (commandResponse.CommandAck.Command == CommandEnum.AdaptiveModeSpeed) { _adaptiveSpeed = BitConverter.ToSingle(commandResponse.Payload, 0); _speedMsgOpMode = (OperatingMode)commandResponse.Action.SubAction; SpeedMsgEvent.Set(); } else { _commandResponse = commandResponse; _responseEvent.Set(); if (ApcsUpdate != null) ApcsUpdate(commandResponse.CommandAck.Command, commandResponse.Action.Action, commandResponse.Action.SubAction, commandResponse.Payload); } } else throw new Exception("Data read from APCS has size 0. Restarting Connection."); } catch (Exception ex) { if (/*not terminated?*/ !_cancelEvent.WaitOne(0)) { Debug.Assert(Lgr != null); Lgr.LogError(ex); } if (_tcpClient != null && _tcpClient.Connected) { //CloseConnection(); _tcpClient = null; } } } } while (!_cancelEvent.WaitOne(ApcsDelay)); }
/*throws IOException, InvalidPacketException*/ /** * Reads the given amount of bytes from the input stream. * * <p>This operation checks several things like the working mode in order * to consider escaped bytes.</p> * * @param inputStream Input stream to read bytes from. * @param mode XBee device working mode. * @param numBytes Number of bytes to read. * * @return The read byte array. * * @throws IOException if the first byte cannot be read for any reason other than end of file, or * if the input stream has been closed, or * if some other I/O error occurs. * @throws InvalidPacketException if there is not enough data in the stream or * if there is an error verifying the checksum. */ private byte[] ReadBytes(Stream inputStream, OperatingMode mode, int numBytes) { Contract.Requires<ArgumentNullException>(inputStream != null, "Input stream cannot be null."); Contract.Requires<ArgumentException>(inputStream.CanRead); byte[] data = new byte[numBytes]; for (int i = 0; i < numBytes; i++) data[i] = (byte)ReadByte(inputStream, mode); return data; }
public void SendAdaptiveModeSpeed(float speed, OperatingMode mode) { byte[] data = BitConverter.GetBytes(speed); CommandDefinition.CommandFormat packet = ReplyCreate(CommandEnum.AdaptiveModeSpeed, BooleanValue.False, ActionEnum.UnsolicitedMsg, (byte)mode, data); ReplySend(packet); }
public void SendAdaptiveModeToTrigRatioResponse(OperatingMode mode, float ratio) { byte[] data = BitConverter.GetBytes(ratio); CommandDefinition.CommandFormat packet = ReplyCreate(CommandEnum.AdaptiveModeToTrigRatio, BooleanValue.True, ActionEnum.Response, (byte)mode, data); ReplySend(packet); }
/// <summary> /// Gets the operating mode name. /// </summary> /// <param name="source"></param> /// <returns>Operating mode name.</returns> public static string GetName(this OperatingMode source) { return(lookupTable[source]); }
/// <summary/> public bool GetStaticPulseFrequency(OperatingMode? selectedMode, out OperatingMode? operatingMode, out int? frequency, bool confirm) { bool status = false; try { CommandDefinition.CommandFormat command = CommandMake(CommandEnum.StaticPulseFreq, BooleanValue.False, ActionEnum.Get, (byte)selectedMode); CommandDefinition.CommandFormat? reply = CommandSend(command, /*reply expected*/ true); string text = CommandReplyValidate(reply, CommandEnum.StaticPulseFreq); if (/*fail?*/ !string.IsNullOrWhiteSpace(text)) throw new Exception(text); operatingMode = (OperatingMode)OperatingMode.ToObject(typeof(OperatingMode), reply.Value.Action.SubAction); frequency = BitConverter.ToInt32(reply.Value.Payload, 0); status = true; } catch (Exception ex) { frequency = null; operatingMode = null; status = false; if (/*OK to log?*/ LogPauseExpired) try { Logger.LogError(Utilities.TextTidy(ex.ToString())); } catch { } } return status; }
public static string ToDisplayString(this OperatingMode source) { return(lookupTable[source]); }
public void SetInputToOutputRatio(OperatingMode mode, float ratio) { if (mode == OperatingMode.AdaptiveMobile) MobileInOutRatio = ratio; else if (mode == OperatingMode.AdaptivePortal) PortalInOutRatio = ratio; }
public void SendStaticPulseFreqResponse(OperatingMode mode, int frequency) { byte[] data = BitConverter.GetBytes(frequency); CommandDefinition.CommandFormat packet = ReplyCreate(CommandEnum.StaticPulseFreq, BooleanValue.True, ActionEnum.Response, (byte)mode, data); ReplySend(packet); }
/*throws IOException, InvalidPacketException*/ private byte[] ReadBytes(SerialPort serialPort, OperatingMode mode, int numBytes) { Contract.Requires<ArgumentNullException>(serialPort != null, "Input stream cannot be null."); Contract.Requires<ArgumentException>(serialPort.IsOpen); byte[] data = new byte[numBytes]; for (int i = 0; i < numBytes; i++) data[i] = (byte)ReadByte(serialPort, mode); return data; }
/// <summary/> public bool SetAdaptiveModeTriggerRatio(OperatingMode mode, float ratio, bool confirm) { bool status = false; try { CommandDefinition.CommandFormat command = CommandMake(CommandEnum.AdaptiveModeToTrigRatio, BooleanValue.True, ActionEnum.Set, (byte)mode); BitConverter.GetBytes(ratio).CopyTo(command.Payload, 0); CommandDefinition.CommandFormat? reply = CommandSend(command, /*reply expected*/ true); if (/*ignore results?*/ !confirm) status = true; else { string text = CommandReplyValidate(reply, CommandEnum.AdaptiveModeToTrigRatio, (byte)mode); if (/*fail?*/ text != string.Empty) throw new Exception(text); if (/*fail?*/ ratio != BitConverter.ToSingle(reply.Value.Payload, 0)) throw new Exception("ratio != " + ratio.ToString()); //set result to false status = true; } } catch (Exception ex) { status = false; if (/*OK to log?*/ LogPauseExpired) try { Logger.LogError(Utilities.TextTidy(ex.ToString())); } catch { } } #if DEBUG try { Logger.LogInfo(MethodBase.GetCurrentMethod() + "(" + mode.ToString() + ", " + ratio.ToString() + ", " + confirm.ToString() + ") returns " + status.ToString()); } catch { } #endif return status; }
public VicarMessage SetOperatingMode(OperatingMode mode) { return _SendRequest((byte)'M', new byte[] { (byte)mode }, false); }
/// <summary/> public bool SetStaticPulseFrequency(OperatingMode mode, uint frequency) { bool status = false; string traceText = MethodBase.GetCurrentMethod().Name + "(" + mode.ToString() + ", " + frequency.ToString() + ")"; try { CommandDefinition.CommandFormat command = CommandMake(CommandEnum.StaticPulseFreq, BooleanValue.True, ActionEnum.Set, (byte)mode); BitConverter.GetBytes(frequency).CopyTo(command.Payload, 0); CommandDefinition.CommandFormat? reply = CommandSend(command, /*reply expected*/ true); string text = CommandReplyValidate(reply, CommandEnum.StaticPulseFreq, (byte)mode); if (/*fail?*/ text != string.Empty) throw new Exception(traceText + "; " + text); if (/*fail?*/ frequency != BitConverter.ToInt32(reply.Value.Payload, 0)) throw new Exception(traceText + "; " + "frequency != " + frequency.ToString()); status = true; } catch (Exception ex) { status = false; throw ex; } return status; }
/// <summary> /// Initializes the RecognitionEngine /// </summary> public Core(OperatingMode aMode) { Initialization(); Mode = aMode; }
public void SetOperatingMode(OperatingMode mode) { opMode = mode; }
/// <summary> /// Creates a new instance of the PulseCounter class. public PulseCounter(OperatingMode mode) { opMode = mode; }
public void GetInputToOutputRatio(OperatingMode mode, out float ratio) { ratio = 0.0f; if (mode == OperatingMode.AdaptiveMobile) ratio = MobileInOutRatio; else if (mode == OperatingMode.AdaptivePortal) ratio = PortalInOutRatio; }
/** * Parses the given byte array and returns a Generic XBee packet. * * @param packet The byte array to parse. * @param mode The operating mode to parse the packet (API 1 or API 2). * * @return The generated Generic XBee Packet. * * @throws ArgumentException if {@code mode != OperatingMode.API } and * if {@code mode != OperatingMode.API_ESCAPE} * or if {@code packet.Length == 0}. * @throws InvalidPacketException if the given byte array does not represent * a valid frame: invalid checksum, Length, * start delimiter, etc. * @throws ArgumentNullException if {@code packet == null}. * * @see com.digi.xbee.api.models.OperatingMode#API * @see com.digi.xbee.api.models.OperatingMode#API_ESCAPE */ public static XBeePacket ParsePacket(byte[] packet, OperatingMode mode) { Contract.Requires<ArgumentNullException>(packet != null, "Packet byte array cannot be null."); Contract.Requires<ArgumentException>(mode == OperatingMode.API || mode == OperatingMode.API_ESCAPE, "Operating mode must be API or API Escaped."); Contract.Requires<ArgumentException>(packet.Length != 0, "Packet Length should be greater than 0."); Contract.Requires<ArgumentException>(packet.Length == 1 || packet[0] == (byte)SpecialByte.HEADER_BYTE, "Invalid start delimiter."); XBeePacketParser parser = new XBeePacketParser(); XBeePacket xbeePacket = parser.ParsePacket(new MemoryStream(packet, 1, packet.Length - 1), mode); return xbeePacket; }
public XBeePacket ParsePacket(SerialPort serialPort, OperatingMode mode) { Contract.Requires<ArgumentNullException>(serialPort != null, "Input stream cannot be null."); Contract.Requires<ArgumentException>(serialPort.IsOpen); Contract.Requires<ArgumentException>(mode == OperatingMode.API || mode == OperatingMode.API_ESCAPE, "Operating mode must be API or API Escaped."); try { // Read packet size. int hSize = ReadByte(serialPort, mode); int lSize = ReadByte(serialPort, mode); int Length = hSize << 8 | lSize; // Read the payload. byte[] payload = ReadBytes(serialPort, mode, Length); // Calculate the expected checksum. XBeeChecksum checksum = new XBeeChecksum(); checksum.Add(payload); byte expectedChecksum = (byte)(checksum.Generate() & 0xFF); // Read checksum from the input stream. byte readChecksum = (byte)(ReadByte(serialPort, mode) & 0xFF); // Verify the checksum of the read bytes. if (readChecksum != expectedChecksum) throw new InvalidPacketException("Invalid checksum (expected 0x" + HexUtils.ByteToHexString(expectedChecksum) + ")."); return ParsePayload(payload); } catch (IOException e) { throw new InvalidPacketException("Error parsing packet: " + e.Message, e); } }
private void ProcessCommand(byte[] buff, int cb) { try { byte to = buff[2]; byte from = buff[3]; byte cmd = buff[4]; switch (cmd) { case 0x00: // Set frequency case 0x03: if (cb > 5) { long freq = ParseBcd(buff, 5, cb - 5); if (freq > 0 && freq < 10000000000) { m_Frequency = freq; m_CommandReadResetEvent.Set(); if (FrequencyChanged != null) FrequencyChanged(this, new EventArgs()); } } break; case 0x01: case 0x04: if (cb > 5) { OperatingMode mode; switch (buff[5]) { case 0x00: mode = OperatingMode.LSB; break; case 0x01: mode = OperatingMode.USB; break; case 0x03: case 0x07: mode = OperatingMode.CW; break; case 0x05: case 0x06: mode = OperatingMode.FM; break; case 0x04: mode = OperatingMode.Data; break; default: mode = OperatingMode.Unknown; break; } if (mode != OperatingMode.Unknown) { m_Mode = mode; } m_CommandReadResetEvent.Set(); if (FrequencyChanged != null) FrequencyChanged(this, new EventArgs()); } break; default: break; } } catch (System.IO.IOException) { throw; } catch { } }
/*throws InvalidPacketException*/ /** * Parses the given hexadecimal string and returns a Generic XBee packet. * * <p>The string can contain white spaces.</p> * * @param packet The hexadecimal string to parse. * @param mode The operating mode to parse the packet (API 1 or API 2). * * @return The generated Generic XBee Packet. * * @throws ArgumentException if {@code mode != OperatingMode.API } and * if {@code mode != OperatingMode.API_ESCAPE}. * @throws InvalidPacketException if the given string does not represent a * valid frame: invalid checksum, Length, * start delimiter, etc. * @throws ArgumentNullException if {@code packet == null}. * * @see com.digi.xbee.api.models.OperatingMode#API * @see com.digi.xbee.api.models.OperatingMode#API_ESCAPE */ public static XBeePacket ParsePacket(String packet, OperatingMode mode) { Contract.Requires<ArgumentNullException>(packet != null, "Packet cannot be null."); return ParsePacket(HexUtils.HexStringToByteArray(packet.Trim().Replace(" ", "")), mode); }