public static void SendUdpWrite(byte command1, byte command2, byte[] payload, byte flag = 17, byte group = 0, IPEndPoint ep = null, bool groupSend = false) { if (payload is null) { throw new ArgumentNullException(nameof(payload)); } // If we don't specify an endpoint...talk to self ep ??= new IPEndPoint(IPAddress.Parse("0.0.0.0"), 8888); using var stream = new MemoryStream(); using var response = new BinaryWriter(stream); // Magic header response.Write((byte)0xFC); // Payload length response.Write((byte)(payload.Length + 5)); // Group number response.Write(group); // Flag, should be 0x10 for subscription, 17 for everything else response.Write(flag); // Upper command response.Write(command1); // Lower command response.Write(command2); // Payload foreach (var b in payload) { response.Write(b); } var byteSend = stream.ToArray(); // CRC response.Write(MsgUtils.CalculateCrc(byteSend)); var byteString = BitConverter.ToString(stream.ToArray()); var bytesString = byteString.Split("-"); var cmd = bytesString[4] + bytesString[5]; cmd = MsgUtils.Commands[cmd] ?? cmd; if (flag == 0x30 | groupSend) { SendUdpBroadcast(stream.ToArray()); //if (cmd != "SUBSCRIBE" && cmd != "COLOR_DATA") LogUtil.Write($"localhost -> 255.255.255.255::{cmd} {flag}-{group}"); } else { SendUdpUnicast(stream.ToArray(), ep); //if (cmd != "SUBSCRIBE" && cmd != "COLOR_DATA") LogUtil.Write($"localhost -> {ep.Address}::{cmd} {flag}-{group}"); } }
private void WriteDifferenceLine(object expected, object actual, Tolerance tolerance) { // It only makes sense to display absolute/percent difference if (tolerance.Mode != ToleranceMode.Linear && tolerance.Mode != ToleranceMode.Percent) return; var differenceString = MsgUtils.FormatValue(Numerics.Difference(expected, actual, tolerance.Mode)); if (differenceString != double.NaN.ToString()) { Write(Pfx_Difference); Write(differenceString); if (tolerance.Mode != ToleranceMode.Linear) Write(" {0}", tolerance.Mode); WriteLine(); } }
/// <summary> /// Initializes a new instance of the <see cref="TestExecutionContext"/> class. /// </summary> public TestExecutionContext() { _priorContext = null; TestCaseTimeout = 0; UpstreamActions = new List <ITestAction>(); _currentCulture = CultureInfo.CurrentCulture; _currentUICulture = CultureInfo.CurrentUICulture; #if !PORTABLE && !NETSTANDARD1_6 _currentPrincipal = Thread.CurrentPrincipal; #endif CurrentValueFormatter = (val) => MsgUtils.DefaultValueFormatter(val); IsSingleThreaded = false; }
public DreamScreenMessage(byte[] bytesIn, string from) { IpAddress = from; var byteString = BitConverter.ToString(bytesIn); var bytesString = byteString.Split("-"); var magic = bytesString[0]; if (!MsgUtils.CheckCrc(bytesIn) || magic != "FC" || bytesString.Length < 7) { //throw new ArgumentException($"Invalid message format: {magic}"); IsValid = false; return; } Len = bytesIn[1]; Group = bytesIn[2]; Flags = bytesString[3]; C1 = bytesIn[4]; C2 = bytesIn[5]; var cmd = bytesString[4] + bytesString[5]; if (MsgUtils.Commands.ContainsKey(cmd)) { Command = MsgUtils.Commands[cmd]; if (Command == "MINIMUM_LUMINOSITY") { LogUtil.Write("BYTE STRING: " + byteString); } } else { LogUtil.Write($@"DSMessage: No matching key in dict for bytes: {cmd}."); } BaseDevice dreamDev = null; if (Len > 5) { payload = ExtractPayload(bytesIn); PayloadString = payload.Length != 0 ? BitConverter.ToString(payload).Replace("-", string.Empty, StringComparison.CurrentCulture) : ""; } if (Command == "DEVICE_DISCOVERY" && Flags == "60" && Len > 46) { int devType = payload[^ 1];
public static void SendUdpWrite(byte command1, byte command2, byte[] payload, byte flag = 17, byte group = 0, IPEndPoint ep = null) { if (payload is null) { throw new ArgumentNullException(nameof(payload)); } // If we don't specify an endpoint...talk to self if (ep == null) { ep = new IPEndPoint(IPAddress.Parse("0.0.0.0"), 8888); } using var stream = new MemoryStream(); using var response = new BinaryWriter(stream); // Magic header response.Write((byte)0xFC); // Payload length response.Write((byte)(payload.Length + 5)); // Group number response.Write(group); // Flag, should be 0x10 for subscription, 17 for everything else response.Write(flag); // Upper command response.Write(command1); // Lower command response.Write(command2); // Payload foreach (var b in payload) { response.Write(b); } var byteSend = stream.ToArray(); // CRC response.Write(MsgUtils.CalculateCrc(byteSend)); if (flag == 0x30) { SendUdpBroadcast(stream.ToArray()); } else { SendUdpUnicast(stream.ToArray(), ep); } }
/// <summary> /// Write the generic 'Expected' line for a given value /// and tolerance. /// </summary> /// <param name="expected">The expected value</param> /// <param name="tolerance">The tolerance within which the test was made</param> private void WriteExpectedLine(object expected, Tolerance tolerance) { Write(Pfx_Expected); Write(MsgUtils.FormatValue(expected)); if (_sameValDiffTypes) { Write(_expectedType); } if (tolerance != null && !tolerance.IsUnsetOrDefault) { Write(" +/- "); Write(MsgUtils.FormatValue(tolerance.Amount)); if (tolerance.Mode != ToleranceMode.Linear) Write(" {0}", tolerance.Mode); } WriteLine(); }
/// <summary> /// Method to write single line message with optional args, usually /// written to precede the general failure message, at a given /// indentation level. /// </summary> /// <param name="level">The indentation level of the message</param> /// <param name="message">The message to be written</param> /// <param name="args">Any arguments used in formatting the message</param> public override void WriteMessageLine(int level, string message, params object[] args) { if (message != null) { while (level-- >= 0) { Write(" "); } if (args != null && args.Length > 0) { message = string.Format(message, args); } WriteLine(MsgUtils.EscapeControlChars(message)); } }
/// <summary> /// Write the generic 'Expected' line for a given value /// and tolerance. /// </summary> /// <param name="expected">The expected value</param> /// <param name="tolerance">The tolerance within which the test was made</param> private void WriteExpectedLine(object expected, Tolerance tolerance) { Write(Pfx_Expected); Write(MsgUtils.FormatValue(expected)); if (tolerance != null && !tolerance.IsUnsetOrDefault) { Write(" +/- "); Write(MsgUtils.FormatValue(tolerance.Value)); if (tolerance.Mode != ToleranceMode.Linear) { Write(" {0}", tolerance.Mode); } } WriteLine(); }
public void TestConvertWhitespace() { Assert.AreEqual("\\n", MsgUtils.ConvertWhitespace("\n")); Assert.AreEqual("\\n\\n", MsgUtils.ConvertWhitespace("\n\n")); Assert.AreEqual("\\n\\n\\n", MsgUtils.ConvertWhitespace("\n\n\n")); Assert.AreEqual("\\r", MsgUtils.ConvertWhitespace("\r")); Assert.AreEqual("\\r\\r", MsgUtils.ConvertWhitespace("\r\r")); Assert.AreEqual("\\r\\r\\r", MsgUtils.ConvertWhitespace("\r\r\r")); Assert.AreEqual("\\r\\n", MsgUtils.ConvertWhitespace("\r\n")); Assert.AreEqual("\\n\\r", MsgUtils.ConvertWhitespace("\n\r")); Assert.AreEqual("This is a\\rtest message", MsgUtils.ConvertWhitespace("This is a\rtest message")); Assert.AreEqual("", MsgUtils.ConvertWhitespace("")); Assert.AreEqual(null, MsgUtils.ConvertWhitespace(null)); Assert.AreEqual("\\t", MsgUtils.ConvertWhitespace("\t")); Assert.AreEqual("\\t\\n", MsgUtils.ConvertWhitespace("\t\n")); Assert.AreEqual("\\\\r\\\\n", MsgUtils.ConvertWhitespace("\\r\\n")); }
public void SetAndRestoreValueFormatter() { var context = new TestExecutionContext(setupContext); var originalFormatter = context.CurrentValueFormatter; try { ValueFormatter f = val => "dummy"; context.AddFormatter(next => f); Assert.That(context.CurrentValueFormatter, Is.EqualTo(f)); context.EstablishExecutionEnvironment(); Assert.That(MsgUtils.FormatValue(123), Is.EqualTo("dummy")); } finally { setupContext.EstablishExecutionEnvironment(); } Assert.That(TestExecutionContext.CurrentContext.CurrentValueFormatter, Is.EqualTo(originalFormatter)); Assert.That(MsgUtils.FormatValue(123), Is.EqualTo("123")); }
/// <summary>Write any additional lines (following <c>Expected:</c> and <c>But was:</c>) for a failing constraint.</summary> /// <param name="writer">The <see cref="MessageWriter"/> to write the failure message to.</param> public override void WriteAdditionalLinesTo(MessageWriter writer) { if (_tallyResult.MissingItems.Count > 0) { int missingItemsCount = _tallyResult.MissingItems.Count; string missingStr = $"Missing ({missingItemsCount}): "; missingStr += MsgUtils.FormatCollection(_tallyResult.MissingItems); writer.WriteMessageLine(missingStr); } if (_tallyResult.ExtraItems.Count > 0) { int extraItemsCount = _tallyResult.ExtraItems.Count; string extraStr = $"Extra ({extraItemsCount}): "; extraStr += MsgUtils.FormatCollection(_tallyResult.ExtraItems); writer.WriteMessageLine(extraStr); } }
private void WriteDifferenceLine(object expected, object actual, Tolerance tolerance) { // It only makes sense to display absolute/percent difference if (tolerance.Mode != ToleranceMode.Linear && tolerance.Mode != ToleranceMode.Percent) { return; } string differenceString = tolerance.Amount is TimeSpan ? MsgUtils.FormatValue(DateTimes.Difference(expected, actual)) // TimeSpan tolerance applied in linear mode only : MsgUtils.FormatValue(Numerics.Difference(expected, actual, tolerance.Mode)); if (differenceString != double.NaN.ToString()) { Write(Pfx_Difference); Write(differenceString); if (tolerance.Mode != ToleranceMode.Linear) { Write(" {0}", tolerance.Mode); } WriteLine(); } }
private void OnReceive(IAsyncResult iar) { StateObj state = (StateObj)iar.AsyncState; //读取的消息总长度 int len = state.Client.EndReceive(iar); if (len < 4) { UITools.logError("invaild msg"); state.OnRecvError(state); return; } byte[] buff = state.RecvTempBuff; int msgRealLen = MsgUtils.DecodeMsgRealLen(buff, 0, 4); UITools.log("msg real length : " + msgRealLen); state.RecvLen = msgRealLen; // state.RecvBuff.addRange<byte>(buff, AppConst.MsgHeadLen, len - 4); state.RecvBuff.Write(buff, AppConst.MsgHeadLen, len - AppConst.MsgHeadLen); if (state.RecvLen - state.RecvBuff.Length > 0) { try { state.Client.BeginReceive(state.RecvTempBuff, 0, state.RecvTempBuff.Length, 0, new AsyncCallback(OnReceiveRestData), state); } catch (Exception) { state.OnRecvError(state); UITools.log("receive data timeout...."); } } else { state.OnReceive(state); } }
public override void DisplayStringDifferences(string expected, string actual, int mismatch, bool ignoreCase, bool clipping) { int maxDisplayLength = MaxLineLength - PrefixLength - 2; if (clipping) { MsgUtils.ClipExpectedAndActual(ref expected, ref actual, maxDisplayLength, mismatch); } expected = MsgUtils.EscapeControlChars(expected); actual = MsgUtils.EscapeControlChars(actual); mismatch = MsgUtils.FindMismatchPosition(expected, actual, 0, ignoreCase); Write(Pfx_Expected); WriteExpectedValue(expected); if (ignoreCase) { WriteModifier("ignoring case"); } WriteLine(); WriteActualLine(actual); if (mismatch >= 0) { WriteCaretLine(mismatch); } }
/// <summary> /// Initializes a new instance of the <see cref="LessThanOrEqualConstraint"/> class. /// </summary> /// <param name="expected">The expected value.</param> public LessThanOrEqualConstraint(object expected) : base(expected) { Description = "less than or equal to " + MsgUtils.FormatValue(expected); }
/// <summary> /// Writes the text for a collection value, /// starting at a particular point, to a max length /// </summary> /// <param name="collection">The collection containing elements to write.</param> /// <param name="start">The starting point of the elements to write</param> /// <param name="max">The maximum number of elements to write</param> public override void WriteCollectionElements(IEnumerable collection, long start, int max) { Write(MsgUtils.FormatCollection(collection, start, max)); }
/// <summary> /// Writes the text for a generalized value. /// </summary> /// <param name="val">The value.</param> public override void WriteValue(object val) { Write(MsgUtils.FormatValue(val)); }
public void TestClipString(string input, int max, int start, string result) { Assert.AreEqual(result, MsgUtils.ClipString(input, max, start)); }
/// <summary> /// Display Expected and Actual lines for given _values, including /// a tolerance value on the expected line. /// </summary> /// <param name="expected">The expected value</param> /// <param name="actual">The actual value causing the failure</param> /// <param name="tolerance">The tolerance within which the test was made</param> public override void DisplayDifferences(object expected, object actual, Tolerance tolerance) { if (expected != null && actual != null && expected.GetType() != actual.GetType() && MsgUtils.FormatValue(expected) == MsgUtils.FormatValue(actual)) { _sameValDiffTypes = true; ResolveTypeNameDifference(expected, actual, out _expectedType, out _actualType); } WriteExpectedLine(expected, tolerance); WriteActualLine(actual); }
public void EscapeControlCharsTest(string input, string expected) { Assert.AreEqual(expected, MsgUtils.EscapeControlChars(input)); }
public void EscapeNullCharInString() { Assert.That(MsgUtils.EscapeControlChars("\0"), Is.EqualTo("\\0")); }
public override int processMsg(string msg) { int cobId = MsgUtils.getCobIdInt(msg); int nodeId = MsgUtils.getNodeIdInt(msg); string data = MsgUtils.getDataString(msg); int retVal = 0; msgCount++; statusString = ""; if (nodeId == 0x2) { switch (cobId) { case 0x082: // MG Error { var error = decodeErrorStatus(data); statusString = "ERR: "; statusString += error.Item1; errorCount++; break; } case 0x182: // MG TXPDO1 { //FIXME //F72CC7030000820100000227100DUnknown //FC2CC7030000820100000227000DUnknown statusString = "MG TXPDO1"; break; } case 0x282: // MG TXPDO2 { //FIXME //F72CC7030000820200000827100000000000000DUnknown //FC2CC7030000820200000827000000000000000DUnknown statusString = "MG TXPDO2"; break; } case 0x402: // MG RXPDO2 { //FIXME //EF2CC703000002040000063F00000000000DUnknown //7B3EC703000002040000063F00504F23000DUnknown statusString = "MG RXPDO2"; break; } case 0x582: // MG SDO Response { var SDO = decodeSDO(data); if (SDO.Item2 == 0x3401) { temperature = SDO.Item3; statusString = "TMP MG: "; statusString += SDO.Item3.ToString(); break; } statusString = "SDOR MG: "; statusString += SDO.Item1; statusString += SDO.Item3.ToString(); break; } case 0x602: // MG SDO Request { var SDO = decodeSDO(data); statusString = "SDOT MG: "; statusString += SDO.Item1; statusString += SDO.Item3.ToString(); break; } case 0x382: // Mode + Position { position = Int32.Parse(MsgUtils.hexSwap(data.Substring(4, 6)), System.Globalization.NumberStyles.HexNumber);; statusString = "POS MG: "; statusString += position.ToString(); break; } case 0x482: // Mode + Velocity { velocity = Int32.Parse(MsgUtils.hexSwap(data.Substring(4, 8)), System.Globalization.NumberStyles.HexNumber);; statusString = "VEL MG: "; statusString += velocity.ToString(); break; } case 0x702: // Motor Gateway Heartbeat { heartbeatCount++; break; } default: { statusString = "Unknown"; break; } }//End switch lastCobId = cobId; }// End if(nodeId == 0x1) else { retVal = 2; } //"Non-MG Message Sent To MG Processor" return(retVal); }
/// <summary> /// Initializes a new instance of the <see cref="GreaterThanOrEqualConstraint"/> class. /// </summary> /// <param name="expected">The expected value.</param> public GreaterThanOrEqualConstraint(object expected) : base(expected) { Description = "greater than or equal to " + MsgUtils.FormatValue(expected); }
public void TestConvertWhitespace(string input, string expected) { Assert.AreEqual(expected, MsgUtils.ConvertWhitespace(input)); }
public void TestClipString(string input, int max, int start, string result) { System.Console.WriteLine("input= \"{0}\"", input); System.Console.WriteLine("result= \"{0}\"", result); Assert.That(MsgUtils.ClipString(input, max, start), Is.EqualTo(result)); }
/// <summary> /// Writes the text for a generalized value. /// </summary> /// <param name="val">The value.</param> private void WriteValue(object val) { Write(MsgUtils.FormatValue(val)); }
private void ProcessData(byte[] receivedBytes, IPEndPoint receivedIpEndPoint) { // Convert data to ASCII and print in console if (!MsgUtils.CheckCrc(receivedBytes)) { return; } string command = null; string flag = null; var from = receivedIpEndPoint.Address.ToString(); var replyPoint = new IPEndPoint(receivedIpEndPoint.Address, 8888); var payloadString = string.Empty; var payload = Array.Empty <byte>(); BaseDevice msgDevice = null; var writeState = false; var msg = new DreamScreenMessage(receivedBytes, from); if (msg.IsValid) { payload = msg.GetPayload(); payloadString = msg.PayloadString; command = msg.Command; msgDevice = msg.Device; string[] ignore = { "SUBSCRIBE", "READ_CONNECT_VERSION?", "COLOR_DATA", "DEVICE_DISCOVERY" }; if (!ignore.Contains(command)) { Console.WriteLine($@"{from} -> {JsonConvert.SerializeObject(msg)}."); } flag = msg.Flags; var groupMatch = msg.Group == dev.GroupNumber || msg.Group == 255; if ((flag == "11" || flag == "21") && groupMatch) { dev = GetDeviceData(); writeState = true; } } switch (command) { case "SUBSCRIBE": if (devMode == 1 || devMode == 2) { DreamSender.SendUdpWrite(0x01, 0x0C, new byte[] { 0x01 }, 0x10, group, replyPoint); } break; case "COLOR_DATA": if (devMode == 1 || devMode == 2) { var colorData = ByteUtils.SplitHex(payloadString, 6); // Swap this with payload var lightCount = 0; var colors = new string[12]; foreach (var colorValue in colorData) { colors[lightCount] = colorValue; if (lightCount > 11) { break; } lightCount++; } SendColors(colors); } break; case "DEVICE_DISCOVERY": if (flag == "30" && from != "0.0.0.0") { SendDeviceStatus(replyPoint); } else if (flag == "60") { if (msgDevice != null) { string dsIpCheck = DreamData.GetItem("dsIp"); if (dsIpCheck == "0.0.0.0" && msgDevice.Tag.Contains("DreamScreen", StringComparison.CurrentCulture)) { Console.WriteLine(@"No DS IP Set, setting."); DreamData.SetItem("dsIp", from); targetEndpoint = replyPoint; } if (_searching) { Devices.Add(msgDevice); } } } break; case "GROUP_NAME": var gName = Encoding.ASCII.GetString(payload); if (writeState) { dev.GroupName = gName; } break; case "GROUP_NUMBER": int gNum = payload[0]; if (writeState) { dev.GroupNumber = gNum; } break; case "NAME": var dName = Encoding.ASCII.GetString(payload); if (writeState) { dev.Name = dName; } break; case "BRIGHTNESS": brightness = payload[0]; if (writeState) { Console.WriteLine($@"Setting brightness to {brightness}."); dev.Brightness = payload[0]; UpdateBrightness(payload[0]); } break; case "SATURATION": if (writeState) { dev.Saturation = ByteUtils.ByteString(payload); } break; case "MODE": if (writeState) { dev.Mode = payload[0]; Console.WriteLine($@"Updating mode: {dev.Mode}."); UpdateMode(dev.Mode); } break; case "AMBIENT_MODE_TYPE": if (writeState) { dev.AmbientModeType = payload[0]; UpdateAmbientMode(dev.Mode); } break; case "AMBIENT_SCENE": if (writeState) { ambientShow = payload[0]; dev.AmbientShowType = ambientShow; UpdateAmbientShow(ambientShow); Console.WriteLine($@"Scene updated: {ambientShow}."); } break; case "AMBIENT_COLOR": if (writeState) { dev.AmbientColor = ByteUtils.ByteString(payload); UpdateAmbientColor(dev.AmbientColor); } break; } if (writeState) { DreamData.SetItem <BaseDevice>("myDevice", dev); } }
public string getNextMsg() { byte[] msg = new byte[16]; int bytesRead = inputFS.Read(msg, 0, 16); if (bytesRead < 16) { inputFS.Close(); blockStatsSW.Flush(); blockStatsSW.Close(); errorStatsSW.Flush(); errorStatsSW.Close(); rawMsgsSW.Flush(); rawMsgsSW.Close(); return(""); // Empty string indicates EOF } msgCount++; rawMsgsSW.Write(msgCount.ToString() + " " + BuildOldStyleMsg(msg) + "\n"); // Check to make sure message is valid // Check message format if (!(CheckFormat(msg))) { errorCounter++; if (!(ignoreFormatErrors)) { MessageBoxResult res = MessageBox.Show("Message does not match required format!\n" + "Select Yes to continue, No to ignore further errors, or Cancel to stop processing " + "messages.\n" + BitConverter.ToString(msg).Replace("-", "") + "\n" + this.errorDetail, "Parse Error", MessageBoxButton.YesNoCancel); if (res == MessageBoxResult.No) { ignoreFormatErrors = true; } if (res == MessageBoxResult.Cancel) { //cancelConversion = true; return(""); } } //return "FORMAT0000000000000000000D"; // Breaks Timestamp extraction //return "0000000000000000000000000D"; // Pick something better for error indication //Temp treating like an OK message } CheckBlock(msg); if (cancelConversion) { if (errorCounter > 0) { MessageBoxResult res = MessageBox.Show("There were errors encountered during processing. See error log for details.\nThe total number of errors found is " + errorCounter.ToString() + " errors.", "Parse Error", MessageBoxButton.OK); } return(""); } else // we have a good message, lets see if the timestamp is OK { string retVal = BuildOldStyleMsg(msg); int timestamp = MsgUtils.getTimestampInt(retVal); if (!bfirstTimestamp) { firstTimestamp = timestamp; bfirstTimestamp = true; } if (!(timestamp >= lastTimestamp)) { errorCounter++; string errorString = "\n\nError Count: " + errorCounter.ToString() + "\n Message Number: " + msgCount.ToString() + "\n This Timestamp: " + timestamp.ToString() + "\n High Timestamp: " + lastTimestamp.ToString() + "\n Difference: " + (timestamp - lastTimestamp).ToString() + "\n ID " + MsgUtils.getCobIdString(retVal); errorStatsSW.Write(errorString); if (!(ignoreTimestampErrors)) { MessageBoxResult res = MessageBox.Show("Timestamp Error: Current timestamp is earlier " + "than a previous timestamp!\nSelect Yes to continue, No to ignore further errors, or " + "Cancel to stop processing messages.\n" + errorString, "Parse Error", MessageBoxButton.YesNoCancel); if (res == MessageBoxResult.No) { ignoreTimestampErrors = true; } if (res == MessageBoxResult.Cancel) { //cancelConversion = true; retVal = ""; } } } if (timestamp >= lastTimestamp) { lastTimestamp = timestamp; } // Format message like the old format // Timestamp , cob ID, data bytes, data return(retVal); } }
/// <summary> /// Initializes a new instance of the <see cref="LessThanConstraint"/> class. /// </summary> /// <param name="expected">The expected value.</param> public LessThanConstraint(object expected) : base(expected) { Description = "less than " + MsgUtils.FormatValue(expected); }
public void EscapeControlCharsTest(string input, string expected) { Assert.That(MsgUtils.EscapeControlChars(input), Is.EqualTo(expected)); }