From c6ff98c139634c92992dec28d85460747b0f2d05 Mon Sep 17 00:00:00 2001 From: Samuele Locatelli Date: Tue, 21 Jul 2020 17:44:43 +0200 Subject: [PATCH] Fix endianness 4 UserSoftKeys --- CMS_CORE_Library/S7Net/Nc_S7Net.cs | 11 +++++++++-- CMS_CORE_Library/Utils/Nc_Utils.cs | 24 ++++++++++++++++++++++++ 2 files changed, 33 insertions(+), 2 deletions(-) diff --git a/CMS_CORE_Library/S7Net/Nc_S7Net.cs b/CMS_CORE_Library/S7Net/Nc_S7Net.cs index 8d769d4..ab0c08f 100644 --- a/CMS_CORE_Library/S7Net/Nc_S7Net.cs +++ b/CMS_CORE_Library/S7Net/Nc_S7Net.cs @@ -822,8 +822,15 @@ namespace CMS_CORE_Library.S7Net if (libraryError.IsError()) return libraryError; + + // need byte swap! + List fixValues = new List(); + foreach(var item in readValues) + { + fixValues.Add(SwapBytes(item)); + } // Convert ints into an array of bools - bool[] bits = IntToBits(readValues.ToArray()); + bool[] bits = IntToBits(fixValues.ToArray()); // Convert array into structured data for (ushort i = 0; i < bits.Count() / 2; i++) @@ -845,7 +852,7 @@ namespace CMS_CORE_Library.S7Net if (id > USER_SOFTKEYS_NUMBER) return INCORRECT_PARAMETERS_ERROR; - // Write strobe into memory --> check if bitArray + // Write strobe into memory --> false because is bitArray CmsError libraryError = PLC_WStrobe(false, USER_SOFT_KEYS_ACK, USER_SOFT_KEYS_CLICKED, id); if (libraryError.IsError()) return libraryError; diff --git a/CMS_CORE_Library/Utils/Nc_Utils.cs b/CMS_CORE_Library/Utils/Nc_Utils.cs index dc56657..3515087 100644 --- a/CMS_CORE_Library/Utils/Nc_Utils.cs +++ b/CMS_CORE_Library/Utils/Nc_Utils.cs @@ -171,6 +171,30 @@ namespace CMS_CORE_Library.Utils { return IntToBits(new int[] { val }); } + /// + /// Swap byte in 32bit DWord (uint/uint) + /// + /// + /// + internal static uint SwapBytes(uint x) + { + // swap adjacent 16-bit blocks + x = (x >> 16) | (x << 16); + // swap adjacent 8-bit blocks + return ((x & 0xFF00FF00) >> 8) | ((x & 0x00FF00FF) << 8); + } + /// + /// Swap byte in 32bit DWord (int/int) + /// + /// + /// + internal static int SwapBytes(int x) + { + byte[] bytes = BitConverter.GetBytes(x); + Array.Reverse(bytes); + int result = BitConverter.ToInt32(bytes, 0); + return result; + } // Convert array of integers in an array of bools internal static bool[] IntToBits(int[] val)