Initial commit

This commit is contained in:
Rowlander
2021-10-01 11:09:20 +02:00
commit fe54fceb1e
1301 changed files with 853973 additions and 0 deletions
+6
View File
@@ -0,0 +1,6 @@
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<startup>
<supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5" />
</startup>
</configuration>
+104
View File
@@ -0,0 +1,104 @@
<?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="4.0" DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<Import Project="$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props" Condition="Exists('$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props')" />
<PropertyGroup>
<Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>
<Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform>
<ProjectGuid>{4B7D6CF3-3C77-4A1F-A55E-4BD48C858330}</ProjectGuid>
<OutputType>Exe</OutputType>
<AppDesignerFolder>Properties</AppDesignerFolder>
<RootNamespace>CRC_CCITT</RootNamespace>
<AssemblyName>CRC_CCITT</AssemblyName>
<TargetFrameworkVersion>v4.5</TargetFrameworkVersion>
<FileAlignment>512</FileAlignment>
<SccProjectName>SAK</SccProjectName>
<SccLocalPath>SAK</SccLocalPath>
<SccAuxPath>SAK</SccAuxPath>
<SccProvider>SAK</SccProvider>
<PublishUrl>publish\</PublishUrl>
<Install>true</Install>
<InstallFrom>Disk</InstallFrom>
<UpdateEnabled>false</UpdateEnabled>
<UpdateMode>Foreground</UpdateMode>
<UpdateInterval>7</UpdateInterval>
<UpdateIntervalUnits>Days</UpdateIntervalUnits>
<UpdatePeriodically>false</UpdatePeriodically>
<UpdateRequired>false</UpdateRequired>
<MapFileExtensions>true</MapFileExtensions>
<ApplicationRevision>0</ApplicationRevision>
<ApplicationVersion>1.0.0.%2a</ApplicationVersion>
<IsWebBootstrapper>false</IsWebBootstrapper>
<UseApplicationTrust>false</UseApplicationTrust>
<BootstrapperEnabled>true</BootstrapperEnabled>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' ">
<PlatformTarget>AnyCPU</PlatformTarget>
<DebugSymbols>true</DebugSymbols>
<DebugType>full</DebugType>
<Optimize>false</Optimize>
<OutputPath>bin\Debug\</OutputPath>
<DefineConstants>DEBUG;TRACE</DefineConstants>
<ErrorReport>prompt</ErrorReport>
<WarningLevel>4</WarningLevel>
<DocumentationFile>d:\Temp\CRC_CCITT_Docu\\CRC_CCITT.XML</DocumentationFile>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' ">
<PlatformTarget>AnyCPU</PlatformTarget>
<DebugType>pdbonly</DebugType>
<Optimize>true</Optimize>
<OutputPath>bin\Release\</OutputPath>
<DefineConstants>TRACE</DefineConstants>
<ErrorReport>prompt</ErrorReport>
<WarningLevel>4</WarningLevel>
</PropertyGroup>
<PropertyGroup>
<ApplicationIcon>itemPicker.ico</ApplicationIcon>
</PropertyGroup>
<ItemGroup>
<Reference Include="System" />
<Reference Include="System.Core" />
<Reference Include="System.Xml.Linq" />
<Reference Include="System.Data.DataSetExtensions" />
<Reference Include="Microsoft.CSharp" />
<Reference Include="System.Data" />
<Reference Include="System.Xml" />
</ItemGroup>
<ItemGroup>
<Compile Include="crcGenerator.cs" />
<Compile Include="crcProgram.cs" />
<Compile Include="Properties\AssemblyInfo.cs" />
<Compile Include="s19FileHandler.cs" />
<Compile Include="txtFileHandler.cs" />
</ItemGroup>
<ItemGroup>
<None Include="App.config" />
</ItemGroup>
<ItemGroup>
<Content Include="itemPicker.ico" />
</ItemGroup>
<ItemGroup>
<BootstrapperPackage Include=".NETFramework,Version=v4.5">
<Visible>False</Visible>
<ProductName>Microsoft .NET Framework 4.5 %28x86 and x64%29</ProductName>
<Install>true</Install>
</BootstrapperPackage>
<BootstrapperPackage Include="Microsoft.Net.Client.3.5">
<Visible>False</Visible>
<ProductName>.NET Framework 3.5 SP1 Client Profile</ProductName>
<Install>false</Install>
</BootstrapperPackage>
<BootstrapperPackage Include="Microsoft.Net.Framework.3.5.SP1">
<Visible>False</Visible>
<ProductName>.NET Framework 3.5 SP1</ProductName>
<Install>false</Install>
</BootstrapperPackage>
</ItemGroup>
<Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" />
<!-- To modify your build process, add your task inside one of the targets below and uncomment it.
Other similar extension points exist, see Microsoft.Common.targets.
<Target Name="BeforeBuild">
</Target>
<Target Name="AfterBuild">
</Target>
-->
</Project>
+10
View File
@@ -0,0 +1,10 @@
""
{
"FILE_VERSION" = "9237"
"ENLISTMENT_CHOICE" = "NEVER"
"PROJECT_FILE_RELATIVE_PATH" = ""
"NUMBER_OF_EXCLUDED_FILES" = "0"
"ORIGINAL_PROJECT_FILE_PATH" = ""
"NUMBER_OF_NESTED_PROJECTS" = "0"
"SOURCE_CONTROL_SETTINGS_PROVIDER" = "PROVIDER"
}
+35
View File
@@ -0,0 +1,35 @@
Microsoft Visual Studio Solution File, Format Version 12.00
# Visual Studio 15
VisualStudioVersion = 15.0.28307.852
MinimumVisualStudioVersion = 10.0.40219.1
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "CRC_CCITT", "CRC_CCITT.csproj", "{4B7D6CF3-3C77-4A1F-A55E-4BD48C858330}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|Any CPU = Debug|Any CPU
Release|Any CPU = Release|Any CPU
EndGlobalSection
GlobalSection(ProjectConfigurationPlatforms) = postSolution
{4B7D6CF3-3C77-4A1F-A55E-4BD48C858330}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{4B7D6CF3-3C77-4A1F-A55E-4BD48C858330}.Debug|Any CPU.Build.0 = Debug|Any CPU
{4B7D6CF3-3C77-4A1F-A55E-4BD48C858330}.Release|Any CPU.ActiveCfg = Release|Any CPU
{4B7D6CF3-3C77-4A1F-A55E-4BD48C858330}.Release|Any CPU.Build.0 = Release|Any CPU
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE
EndGlobalSection
GlobalSection(ExtensibilityGlobals) = postSolution
SolutionGuid = {8E3A0A0D-3584-415E-BD14-31AE18DB6D98}
EndGlobalSection
GlobalSection(TeamFoundationVersionControl) = preSolution
SccNumberOfProjects = 1
SccEnterpriseProvider = {4CA58AB2-18FA-4F8D-95D4-32DDF27D184C}
SccTeamFoundationServer = http://10.1.0.164:8080/tfs/sensusprojectcollection
SccProjectUniqueName0 = CRC_CCITT.csproj
SccProjectName0 = .
SccAuxPath0 = http://10.1.0.164:8080/tfs/sensusprojectcollection
SccLocalPath0 = .
SccProvider0 = {4CA58AB2-18FA-4F8D-95D4-32DDF27D184C}
EndGlobalSection
EndGlobal
+10
View File
@@ -0,0 +1,10 @@
""
{
"FILE_VERSION" = "9237"
"ENLISTMENT_CHOICE" = "NEVER"
"PROJECT_FILE_RELATIVE_PATH" = ""
"NUMBER_OF_EXCLUDED_FILES" = "0"
"ORIGINAL_PROJECT_FILE_PATH" = ""
"NUMBER_OF_NESTED_PROJECTS" = "0"
"SOURCE_CONTROL_SETTINGS_PROVIDER" = "PROJECT"
}
+38
View File
@@ -0,0 +1,38 @@
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Resources;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("CRC_CCITT")]
[assembly: AssemblyDescription("Polynomal 0x1021; CRC16")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("SENSUS")]
[assembly: AssemblyProduct("CRC_CCITT")]
[assembly: AssemblyCopyright("Copyright © SENSUS 2016")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("a1e7c4e5-2f56-4ad6-8116-e615e1634655")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
[assembly: NeutralResourcesLanguageAttribute("en")]
+8
View File
@@ -0,0 +1,8 @@
<?xml version="1.0"?>
<doc>
<assembly>
<name>CRC_CCITT</name>
</assembly>
<members>
</members>
</doc>
Binary file not shown.
+6
View File
@@ -0,0 +1,6 @@
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<startup>
<supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5" />
</startup>
</configuration>
Binary file not shown.
Binary file not shown.
@@ -0,0 +1,6 @@
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<startup>
<supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5" />
</startup>
</configuration>
@@ -0,0 +1,11 @@
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<assembly xmlns="urn:schemas-microsoft-com:asm.v1" manifestVersion="1.0">
<assemblyIdentity version="1.0.0.0" name="MyApplication.app"/>
<trustInfo xmlns="urn:schemas-microsoft-com:asm.v2">
<security>
<requestedPrivileges xmlns="urn:schemas-microsoft-com:asm.v3">
<requestedExecutionLevel level="asInvoker" uiAccess="false"/>
</requestedPrivileges>
</security>
</trustInfo>
</assembly>
@@ -0,0 +1,66 @@
@REM *********************** Motorola-s19 - GOOD TEST CASES ****************************************************************************************************************************************************
@REM ======================= Motorola-s19 - suffuciant parameters and valid file - different input and output file =============================================================================================
@REM CRC_CCITT -file_in=test_in.s19 -file_out=test_crc.s19 -order=LSB_FIRST -size=WORD -crc_address=0x5C00 -start_address1=0x5C02 -length1=0x51FD -start_address2=0x010000 -length2=0x02FFFF
@REM ======================= Motorola-s19 - suffuciant parameters and valid file - identical input and output file =============================================================================================
@REM CRC_CCITT -file_in=test_in_out.s19 -order=LSB_FIRST -size=WORD -crc_address=0x5C00 -start_address1=0x5C02 -length1=0x51FD -start_address2=0x010000 -length2=0x02FFFF
@REM ======================= Motorola-s19 - suffuciant parameters and valid file - identical input and output file - single address range ======================================================================
@REM CRC_CCITT -file_in=test_in_out.s19 -order=LSB_FIRST -size=WORD -crc_address=0x5C00 -start_address1=0x5C02
@REM ======================= Motorola-s19 - suffuciant parameters and valid file - different input and output file - crc address outside of input file address range ==========================================
@REM CRC_CCITT -file_in=test_in.s19 -file_out=test_crc.s19 -order=LSB_FIRST -size=WORD -crc_address=0x5B00 -start_address1=0x5C02 -length1=0x51FD -start_address2=0x010000 -length2=0x02FFFF
@REM *********************** Motorola-s19 - ERRONEOUS TEST CASES ***********************************************************************************************************************************************
@REM ======================= Motorola-s19 - wrong file =========================================================================================================================================================
@REM CRC_CCITT -file_in=undefined.s19 -crc_address=0x5C00 -start_address1=0x5C02 -length1=0x51FD
@REM ======================= Motorola-s19 - insufficiant parameters ============================================================================================================================================
@REM CRC_CCITT -file_in=test_in.s19 -crc_address=0x5C00 -start_address1=0x5C02
@REM ======================= Motorola-s19 - address contains wrong sign ========================================================================================================================================
@REM CRC_CCITT -file_in=Wrong_Address_Sign.s19 -file_out=test_crc.s19 -order=LSB_FIRST -size=WORD -crc_address=0x5C00 -start_address1=0x5C02 -length1=0x51FD -start_address2=0x010000 -length2=0x02FFFF
@REM ======================= Motorola-s19 - data contains wrong sign ===========================================================================================================================================
@REM CRC_CCITT -file_in=Wrong_Data_Sign.s19 -file_out=test_crc.s19 -order=LSB_FIRST -size=WORD -crc_address=0x5C00 -start_address1=0x5C02 -length1=0x51FD -start_address2=0x010000 -length2=0x02FFFF
@REM ======================= Motorola-s19 - wrong length =======================================================================================================================================================
@REM CRC_CCITT -file_in=Wrong_Length.s19 -file_out=test_crc.s19 -order=LSB_FIRST -size=WORD -crc_address=0x5C00 -start_address1=0x5C02 -length1=0x51FD -start_address2=0x010000 -length2=0x02FFFF
@REM ======================= Motorola-s19 - wrong checksum =====================================================================================================================================================
@REM CRC_CCITT -file_in=Wrong_SRecord_Checksum.s19 -file_out=test_crc.s19 -order=LSB_FIRST -size=WORD -crc_address=0x5C00 -start_address1=0x5C02 -length1=0x51FD -start_address2=0x010000 -length2=0x02FFFF
@REM ======================= Motorola-s19 - wrong s19 record ===================================================================================================================================================
@REM CRC_CCITT -file_in=Wrong_SRecord_Id.s19 -file_out=test_crc.s19 -order=LSB_FIRST -size=WORD -crc_address=0x5C00 -start_address1=0x5C02 -length1=0x51FD -start_address2=0x010000 -length2=0x02FFFF
@REM *********************** TI-txt - GOOD TEST CASES **********************************************************************************************************************************************************
@REM ======================= TI-txt - suffuciant parameters and valid file - different input and output file ===================================================================================================
@REM CRC_CCITT -file_in=test_in.txt -file_out=test_crc.txt -order=LSB_FIRST -size=WORD -crc_address=0x5C00 -start_address1=0x5C02 -length1=0x51FD -start_address2=0x010000 -length2=0x02FFFF
@REM ======================= TI-txt - suffuciant parameters and valid file - identical input and output file ===================================================================================================
@REM CRC_CCITT -file_in=test_in_out.txt -order=LSB_FIRST -size=WORD -crc_address=0x5C00 -start_address1=0x5C02 -length1=0x51FD -start_address2=0x010000 -length2=0x02FFFF
@REM ======================= TI-txt - suffuciant parameters and valid file - different input and output file - crc address outside of input file address range ================================================
@REM CRC_CCITT -file_in=test_in.txt -file_out=test_crc.txt -order=LSB_FIRST -size=WORD -crc_address=0x5B00 -start_address1=0x5C02 -length1=0x51FD -start_address2=0x010000 -length2=0x02FFFF
@REM *********************** TI-txt - ERRONEOUS TEST CASES *****************************************************************************************************************************************************
@REM ======================= TI-txt - invalid input file - corrupted ===========================================================================================================================================
@REM CRC_CCITT -file_in=Corrupted_File.txt -file_out=test_crc.txt -order=LSB_FIRST -size=WORD -crc_address=0x5C00 -start_address1=0x5C02 -length1=0x51FD -start_address2=0x010000 -length2=0x02FFFF
@PAUSE
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
+387
View File
@@ -0,0 +1,387 @@
/*********************************************************************************************************************/
/*!@file crcGenerator.cs
* @brief Implementation of CRC algorithms.
*
*====================================================================================================================\n
* @copyright
*
* ___________________________________________________________________________________________________________________\n
* Copyright (c) 2016 SENSUS, GmbH.\n
* All Rights Reserved.\n
* \n
* Confidential property of\n
* SENSUS GmbH,\n
* Meineckestr. 10, 30880 LAATZEN, GERMANY\n
* \n
* Design by\n
* Hard- und Softwareentwicklung Thomas Wiedebusch,\n
* Ostermarsch 17c, 31191 ALGERMISSEN/UMMELN, GERMANY\n
* \n
*====================================================================================================================\n
* @intro
*
*____________________________________________________________________________________________________________________\n
* Functions:\n
* CRC16 LSB 0x1021,\n
* CRC16 MSB 0x1021.\n
*
*====================================================================================================================\n
* @version
*
*____________________________________________________________________________________________________________________\n
* V1.00 19-Feb-2016..23-Feb-2016 by Thomas Wiedebusch\n
* - Initial.
*
*
*====================================================================================================================\n
*/
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace CRC_CCITT
{
/*---------------------------------------------------------------------------------------------------------------*/
/*!@brief Prototype of delegate for memory set function.
* @author Thomas Wiedebusch
* @date 20-Feb-2016
* @param[in] memAddress_u32 address to fill
* @param[in] memData_u8 data for memory
*
*/
/*---------------------------------------------------------------------------------------------------------------*/
public delegate void crcGenrator_memSetFn_t(UInt32 memAddress_u32, Byte memData_u8);
/**/
/*---------------------------------------------------------------------------------------------------------------*/
/*!@brief Prototype of delegate for memory get function.
* @author Thomas Wiedebusch
* @date 20-Feb-2016
* @param[in] memAddress_u32 address to fill
* @return memData_u8
*
*/
/*---------------------------------------------------------------------------------------------------------------*/
public delegate Byte crcGenrator_memGetFn_t(UInt32 memAddress_u32);
/**/
/*---------------------------------------------------------------------------------------------------------------*/
/*!@brief crcGenerator class.
* @author Thomas Wiedebusch
* @date 19-Feb-2016..20-Feb-2016
*
*/
/*---------------------------------------------------------------------------------------------------------------*/
public class crcGenerator_t
{
//class variables
public const UInt32 maxMemBytes_cu32 = 0xFFFFFF; //maximum size of memory
Byte addressRangeLoops_u8 = 0; //no address range
Byte[] memory_u8a;
UInt16 crcValue_u16;
UInt32 startAddress1_u32;
UInt32 length1_u32;
UInt32 startAddress2_u32;
UInt32 length2_u32;
Byte bitSize_u8;
delegate void crc16Fn_t();
crc16Fn_t Crc16Fn_vdp; //internal reminder for CRC function
/*---------------------------------------------------------------------------------------------------------------*/
/*!@brief Constructor for CRC generation class:\n
* -initializes required address ranges,\n
* -initializes memory with 0xFF,\n
* -sets function pointer to required CRC function.
* @author Thomas Wiedebusch
* @date 19-Feb-2016..20-Feb-2016
* @param[in] startAddress1_u32 first address to compute
* @param[in] length1_u32 length of data of first segment
* @param[in] startAddress2_u32 second address to compute
* @param[in] length2_u32 length of data of second segment
* @param[in] seed_u16 initial seed value for computation
* @param[in] wordAccess_bol access data as word if set, else as byte
* @param[in] lsbFirst_bol access data LSB first if set, else MSB first
*
*/
/*---------------------------------------------------------------------------------------------------------------*/
public crcGenerator_t( UInt32 startAddress1In_u32, UInt32 length1In_u32, UInt32 startAddress2In_u32,
UInt32 length2In_u32, UInt16 seedIn_u16, bool wordAccessIn_bol, bool lsbFirstIn_bol)
{
crcValue_u16 = seedIn_u16;
startAddress1_u32 = startAddress1In_u32;
length1_u32 = length1In_u32;
startAddress2_u32 = startAddress2In_u32;
length2_u32 = length2In_u32;
//allocate memory for data
memory_u8a = new Byte[maxMemBytes_cu32];
//assign pointer to function
if (lsbFirstIn_bol)
{
Crc16Fn_vdp = new crc16Fn_t(Crc16Lsb_vd);
}
else
{
Crc16Fn_vdp = new crc16Fn_t(Crc16Msb_vd);
}
//calculate bit size to process
if (wordAccessIn_bol)//access word wise
{
bitSize_u8 = 16;
}
else//access byte wise
{
bitSize_u8 = 8;
}
//check first address range
if ((startAddress1_u32 > 0) && (length1_u32 > 0))
{
addressRangeLoops_u8++;
}
//check second address range
if ((startAddress2_u32 > 0) && (length2_u32 > 0))
{
addressRangeLoops_u8++;
}
//Init entire memory with 0xFF
InitMemory_vd();
}
/**/
/*---------------------------------------------------------------------------------------------------------------*/
/*!@brief Get delegate of memory set function.
* @author Thomas Wiedebusch
* @date 20-Feb-2016
* @return SetMemory_vd delegate
*
*/
/*---------------------------------------------------------------------------------------------------------------*/
public crcGenrator_memSetFn_t MemSetFn_vdp()
{
return SetMemory_vd;
}
/**/
/*---------------------------------------------------------------------------------------------------------------*/
/*!@brief Get delegate of memory get function.
* @author Thomas Wiedebusch
* @date 20-Feb-2016
* @return GetMemory_u8 delegate
*
*/
/*---------------------------------------------------------------------------------------------------------------*/
public crcGenrator_memGetFn_t MemGetFn_u8p()
{
return GetMemory_u8;
}
/**/
/*---------------------------------------------------------------------------------------------------------------*/
/*!@brief Initialize memory with 0xFF each cell.
* @author Thomas Wiedebusch
* @date 19-Feb-2016
*
*/
/*---------------------------------------------------------------------------------------------------------------*/
void InitMemory_vd()
{
for (UInt32 ctr_u32 = 0; ctr_u32 < maxMemBytes_cu32; ctr_u32++)
{
memory_u8a[ctr_u32] = 0xFF;
}
}
/**/
/*---------------------------------------------------------------------------------------------------------------*/
/*!@brief Builds the CRC16 LSB first.
* @author Thomas Wiedebusch
* @date 19-Feb-2016..23-Feb-2016
*
*/
/*---------------------------------------------------------------------------------------------------------------*/
void Crc16Lsb_vd()
{
UInt32 memAddress_u32;
UInt32 byteCtr_u32;
UInt32 byteSize_u32;
Byte bitCtr_u8;
Byte dataByte_u8;
UInt16 dataWord_u16;
//load first address range
memAddress_u32 = startAddress1_u32;
//byte size is one higher to accumulate the start and end address
byteSize_u32 = length1_u32 + 1;
//process entire memory
while( addressRangeLoops_u8-- > 0)
{
for( byteCtr_u32 = 0; byteCtr_u32 < byteSize_u32; byteCtr_u32 += (UInt32)( bitSize_u8/8) )
{
//read data lower byte
dataByte_u8 = memory_u8a[ memAddress_u32++ ];
//copy lower data byte to lower word because of LSB will be XORed
dataWord_u16 = (UInt16)((UInt16)dataByte_u8 & 0x00FF);
//assemble word if word access is required
if( 16 == bitSize_u8)
{
//read data byte higher byte
dataByte_u8 = memory_u8a[ memAddress_u32++ ];
//put higher byte to higher word
dataWord_u16 |= (UInt16)((((UInt16)dataByte_u8 << 8) & 0xFF00));
}
//process single byte or word
for( bitCtr_u8 = 0; bitCtr_u8 < bitSize_u8; bitCtr_u8++)
{
//test if CRC highest bit or data input lowest bit is XORed set to one
if( 0x8000 == ( (crcValue_u16 ^ ( dataWord_u16 << 15) ) & 0x8000) )//inverse shifted in LSB first
{
//shift CRC high bit out
crcValue_u16 <<= 1;
//apply generator polynomial
crcValue_u16 ^= 0x1021;
}
else//CRC highest bit and data input lowest bit is equal
{
crcValue_u16 <<= 1;
}
dataWord_u16 >>= 1; //LSB first shifted in
}//process single byte or word
}//byte counter
//load second address range
memAddress_u32 = startAddress2_u32;
//byte size is one higher to accumulate the start and end address
byteSize_u32 = length2_u32 + 1;
}//process entire memory while()
}
/**/
/*---------------------------------------------------------------------------------------------------------------*/
/*!@brief Builds the CRC16 MSB first.
* @author Thomas Wiedebusch
* @date 19-Feb-2016..23-Feb-2016
*
*/
/*---------------------------------------------------------------------------------------------------------------*/
void Crc16Msb_vd()
{
UInt32 memAddress_u32;
UInt32 byteCtr_u32;
UInt32 byteSize_u32;
Byte bitCtr_u8;
Byte dataByte_u8;
UInt16 dataWord_u16;
//load first address range
memAddress_u32 = startAddress1_u32;
//byte size is one higher to accumulate the start and end address
byteSize_u32 = length1_u32 + 1;
//process entire memory
while( addressRangeLoops_u8-- > 0)
{
for ( byteCtr_u32 = 0; byteCtr_u32 < byteSize_u32; byteCtr_u32 += (UInt32)( bitSize_u8 / 8))
{
//read data lower byte
dataByte_u8 = memory_u8a[ memAddress_u32++ ];
//copy lower data byte to higher word because of MSB will be XORed
dataWord_u16 = (UInt16)((((UInt16)dataByte_u8 << 8) & 0xFF00));
//assemble word if word access is required
if ( 16 == bitSize_u8)
{
//read data byte higher byte
dataByte_u8 = memory_u8a[ memAddress_u32++ ];
//move lower byte back to lower word
dataWord_u16 >>= 8;
//put higher byte to higher word
dataWord_u16 |= (UInt16)((((UInt16)dataByte_u8 << 8) & 0xFF00));
}
//process single byte or word
for (bitCtr_u8 = 0; bitCtr_u8 < bitSize_u8; bitCtr_u8++)
{
//test if CRC highest bit or data input highest bit is XORed set to one
if (0x8000 == ( ( crcValue_u16 ^ dataWord_u16) & 0x8000) )//shifted in MSB first
{
//shift CRC high bit out
crcValue_u16 <<= 1;
//apply generator polynomial
crcValue_u16 ^= 0x1021;
}
else//CRC highest bit and data input highest bit is equal
{
crcValue_u16 <<= 1;
}
dataWord_u16 <<= 1; //MSB first shifted in
}//process single byte or word
}//byte counter
//load second address range
memAddress_u32 = startAddress2_u32;
//byte size is one higher to accumulate the start and end address
byteSize_u32 = length2_u32 + 1;
}//process entire memory while()
}
/**/
/*---------------------------------------------------------------------------------------------------------------*/
/*!@brief Builds the CRC16 based on assigned function pointer.
* @author Thomas Wiedebusch
* @date 19-Feb-2016
* @return crcValue_u16 built CRC16 result
*
*/
/*---------------------------------------------------------------------------------------------------------------*/
public UInt16 CrcCalculate_u16()
{
Crc16Fn_vdp();
return crcValue_u16;
}
/**/
/*---------------------------------------------------------------------------------------------------------------*/
/*!@brief Set/Fill memory at address with data, check the address range.
* @author Thomas Wiedebusch
* @date 19-Feb-2016
* @param[in] address_u32 address to fill
* @param[in] data_u8 data for memory
*
*/
/*---------------------------------------------------------------------------------------------------------------*/
void SetMemory_vd(UInt32 address_u32, Byte data_u8)
{
if (address_u32 < maxMemBytes_cu32) //avoid access beyond the reserved range
{
memory_u8a[address_u32] = data_u8;
}
}
/**/
/*---------------------------------------------------------------------------------------------------------------*/
/*!@brief Get data of memory at address.
* @author Thomas Wiedebusch
* @date 19-Feb-2016
* @param[in] address_u32 address to read
* @return data_u8 at memory location
*
*/
/*---------------------------------------------------------------------------------------------------------------*/
Byte GetMemory_u8(UInt32 address_u32)
{
return memory_u8a[address_u32];
}
/**/
/*---------------------------------------------------------------------------------------------------------------*/
/*!@brief Get maximum value for memory address.
* @author Thomas Wiedebusch
* @date 21-Feb-2016
* @return maxMemBytes_cu32 maximum memory addresses
*
*/
/*---------------------------------------------------------------------------------------------------------------*/
public UInt32 GetMaxMemoryAddress_u8()
{
return maxMemBytes_cu32;
}
/**/
/*---------------------------------------------------------------------------------------------------------------*/
}//class crcGenerator
}//namespace CRC_CCITT
/*=====================================END OF FILE===================================================================*/
+570
View File
@@ -0,0 +1,570 @@
/*********************************************************************************************************************/
/*!@file crcProgram.cs
* @brief Main file for CRC_CCITT.
*
*====================================================================================================================\n
* @copyright
*
* ___________________________________________________________________________________________________________________\n
* Copyright (c) 2016 SENSUS, GmbH.\n
* All Rights Reserved.\n
* \n
* Confidential property of\n
* SENSUS GmbH,\n
* Meineckestr. 10, 30880 LAATZEN, GERMANY\n
* \n
* Design by\n
* Hard- und Softwareentwicklung Thomas Wiedebusch,\n
* Ostermarsch 17c, 31191 ALGERMISSEN/UMMELN, GERMANY\n
* \n
*====================================================================================================================\n
* @intro
*
*____________________________________________________________________________________________________________________\n
* crcProgram:\n
* - Initial CRC16 calculation for polynomial 0x1021,\n
* inputs: -file_in name of s19 | txt file,\n
* [-file_out name of s19 | txt file],\n
* -start_address1=0..0xFFFFFE\n
* -end_address1=0..0xFFFFFF | -length1=0..0xFFFFFF\n
* [-start_address2=0..0xFFFFFE]\n
* [-end_address2=0..0xFFFFFF | -length2=0..0xFFFFFE]\n
* [-crc_address=0..0xFFFFFF]\n
* [-seed=0..0xFFFF]\n
* [-order=MMSB_FIRST|LSB_FIRST]\n
*
*====================================================================================================================\n
* @version
*
*____________________________________________________________________________________________________________________\n
* V1.00 19-Feb-2016..26.Feb-2016 by Thomas Wiedebusch\n
* - Initial.
*
*
*====================================================================================================================\n
*/
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO;
namespace CRC_CCITT
{
class crcProgram_t
{
//class variables
public const String fileUndefined_cstr = "undefined";
const UInt16 searchIgnoreBytesOfString_cu16 = 3;
static String inputFile_strs = fileUndefined_cstr;
static String outputFile_strs = fileUndefined_cstr;
static UInt32 crcAddress_u32s = 0;
static UInt32 startAddress1_u32s = 0;
static UInt32 endAddress1_u32s = 0;
static UInt32 length1_u32s = 0;
//optional input parameters
static UInt32 startAddress2_u32s = 0; //second address range undefined
static UInt32 endAddress2_u32s = 0; //second address range undefined
static UInt32 length2_u32s = 0; //second address range undefined
static UInt16 seed_u16s = 0xFFFF; //default value
static bool wordAccess_bols = false; //default BYTE access
static bool lsbFirst_bols = false; //default MSB first
//internal variables
static UInt16 crcResult_u16s = 0;
static bool crcAddressDefined_bols = false; //assume missing arguments
static Byte argsNumber_u8s = 0;
/*---------------------------------------------------------------------------------------------------------------*/
/*!@brief Main program.
* @author Thomas Wiedebusch
* @date 19-Feb-2016..25-Feb-2016
* @param[in] args_st
* @return exit code
*
*/
/*---------------------------------------------------------------------------------------------------------------*/
static void Main(string[] args_str)
{
try
{
//required input parameters
argsNumber_u8s = (Byte)args_str.GetLength(0);
//check number of command line args and start of syntax for command line parameter input"-"
if ((argsNumber_u8s > 2) && ("-" == args_str[0].Substring(0, 1)))
{
//extract information given by command line input
ParseCommandLineArguments_vds(args_str);
//check and init input parameters
CheckAndLimitInput_vds();
}//check number of command line parameters and string "-" as start for parameter input
}//try
catch
{
}
//set the address ranges for output to console, therefore the arguments have to be extracted
BuildAddressRanges_vds();
//initial messages for input display to user after address build
DisplayStartMsg_vds();
//check for sufficient number of input parameters and defined file to process
if(((endAddress1_u32s > 0) && (length1_u32s > 0)) && (String.Compare(inputFile_strs, fileUndefined_cstr) != 0))
{
//check for physically file existence
if (File.Exists( inputFile_strs))
{
//confirm the file has been file found
DisplayFileInformationMsg_vds();
//start the file and CRC processing
if (Process_bols())
{
//output crc result to console
DisplayResultMsg_vds();
}
else
{
//file has unknown format
DispalyUnknownFileFormatErrorMsg_vd();
}
}
else
{
//input file can't be found, don't start processing
DisplayInFileNotFoundErrorMsg_vds();
}
}
else//if parameters are missing or help request
{
DisplayMissedParamErrorMsg_vds();
}//argumentsSufficient_bols
}//Main
/**/
/*---------------------------------------------------------------------------------------------------------------*/
/*!@brief Process file and CRC.
* @author Thomas Wiedebusch
* @date 21-Feb-2016..25-Feb-2016
* @return files valid
*
*/
/*---------------------------------------------------------------------------------------------------------------*/
static bool Process_bols()
{
bool returnValue_bol = false;
//initialize CRC generator
crcGenerator_t crcGenerator_cl = new crcGenerator_t(startAddress1_u32s, length1_u32s,
startAddress2_u32s, length2_u32s, seed_u16s, wordAccess_bols, lsbFirst_bols);
crcGenrator_memSetFn_t MemSetFn_vdp = crcGenerator_cl.MemSetFn_vdp();
crcGenrator_memGetFn_t MemGetFn_u8p = crcGenerator_cl.MemGetFn_u8p();
//initialize s19 file handler
s19FileHandler_t s19FileHandler_cl = new s19FileHandler_t(inputFile_strs, outputFile_strs, MemSetFn_vdp,
MemGetFn_u8p, crcAddress_u32s, crcAddressDefined_bols);
//initialize txt file handler
txtFileHandler_t txtFileHandler_cl = new txtFileHandler_t(inputFile_strs, outputFile_strs, MemSetFn_vdp,
MemGetFn_u8p, crcAddress_u32s, crcAddressDefined_bols);
//read file, extract and copy to memory, returns false on corrupted record
if (s19FileHandler_cl.ValidateInputFile_bol())
{
returnValue_bol = true;
//process crc
crcResult_u16s = crcGenerator_cl.CrcCalculate_u16();
//create the output file
s19FileHandler_cl.CreateOutputFile_vd(crcResult_u16s);
}
//read file, extract and copy to memory, returns false on corrupted record
else if (txtFileHandler_cl.ValidateInputFile_bol())
{
returnValue_bol = true;
//process crc
crcResult_u16s = crcGenerator_cl.CrcCalculate_u16();
//create the output file
txtFileHandler_cl.CreateOutputFile_vd(crcResult_u16s);
}
return returnValue_bol;
}
/**/
/*---------------------------------------------------------------------------------------------------------------*/
/*!@brief Safety module to avoid wrong input ranges:\n
* Takes input range from crcGenerator_t class.
* @author Thomas Wiedebusch
* @date 21-Feb-2016
*
*/
/*---------------------------------------------------------------------------------------------------------------*/
static void CheckAndLimitInput_vds()
{
//get the defined input range for addresses from crcGenerator class
UInt32 maxAddress_u32 = crcGenerator_t.maxMemBytes_cu32;
if (startAddress1_u32s > maxAddress_u32)
{
startAddress1_u32s = maxAddress_u32;
}
if (startAddress2_u32s > maxAddress_u32)
{
startAddress2_u32s = maxAddress_u32;
}
if (endAddress1_u32s > maxAddress_u32)
{
endAddress1_u32s = maxAddress_u32;
}
if (endAddress2_u32s > maxAddress_u32)
{
endAddress2_u32s = maxAddress_u32;
}
if (length1_u32s + startAddress1_u32s > maxAddress_u32)
{
length1_u32s = maxAddress_u32 - startAddress1_u32s;
}
if (length2_u32s + startAddress2_u32s > maxAddress_u32)
{
length2_u32s = maxAddress_u32 - startAddress2_u32s;
}
if (crcAddress_u32s > maxAddress_u32)
{
crcAddress_u32s = maxAddress_u32;
}
}
/**/
/*---------------------------------------------------------------------------------------------------------------*/
/*!@brief Build address ranges out of end addresses or lengths.
* @author Thomas Wiedebusch
* @date 21-Feb-2016..23-Feb-2016
*
*/
/*---------------------------------------------------------------------------------------------------------------*/
static void BuildAddressRanges_vds()
{
//check for start and end address
if (endAddress1_u32s < startAddress1_u32s)
{
endAddress1_u32s = startAddress1_u32s;
}
//check first address range
if( length1_u32s > 0)
{
endAddress1_u32s = startAddress1_u32s + length1_u32s;
}
else
{
length1_u32s = endAddress1_u32s - startAddress1_u32s;
}//first address range is defined
//check for start and end address
if (endAddress2_u32s < startAddress2_u32s)
{
endAddress2_u32s = startAddress2_u32s;
}
//check second address range
if (length2_u32s > 0)
{
endAddress2_u32s = startAddress2_u32s + length2_u32s;
}
else
{
length2_u32s = endAddress2_u32s - startAddress2_u32s;
}//second address range is defined
}
/**/
/*---------------------------------------------------------------------------------------------------------------*/
/*!@brief Parse command line arguments:\n
* -extracts the path and file information,\n
* -extracts and assigns the variables.
* @author Thomas Wiedebusch
* @date 19-Feb-2016..23-Feb-2016
* @param[in] args_st command line arguments
*
*/
/*---------------------------------------------------------------------------------------------------------------*/
static void ParseCommandLineArguments_vds(String[] args_str)
{
//assign numerical values to the variables or strings to strings
for (Byte ctr_u8 = 0; ctr_u8 < argsNumber_u8s; ctr_u8++)
{
try
{
//read args string
String argsString_str = args_str[ctr_u8];
//search for "="
UInt16 stringCtr_u16 = 0;
UInt16 stringLength_u16 = (UInt16)argsString_str.Length;
//avoid access on string size below size of ignored bytes, may be possible on additional wrong space
if (stringLength_u16 > searchIgnoreBytesOfString_cu16)
{
//remove at least the 3 digits to avoid search overrun
stringLength_u16 -= searchIgnoreBytesOfString_cu16;
while ((stringCtr_u16 != argsString_str.IndexOf("=", stringCtr_u16))
&& (stringCtr_u16 < stringLength_u16))
{
stringCtr_u16++;
}
//extract compare string
String compareString_str = argsString_str.Substring(1, stringCtr_u16 - 1);
String textString_str;
//deliver and convert string to variable
switch (compareString_str)
{
case "file_in":
//extract text and remove the "=" before the text
inputFile_strs = argsString_str.Substring(stringCtr_u16 + 1,
argsString_str.Length - stringCtr_u16 - 1);
break;
case "file_out":
//extract text and remove the "=" before the text
outputFile_strs = argsString_str.Substring(stringCtr_u16 + 1,
argsString_str.Length - stringCtr_u16 - 1);
break;
case "crc_address":
crcAddressDefined_bols = true;
crcAddress_u32s = ExtractUint32HexNumberFromString_u32s(argsString_str, stringCtr_u16);
;
break;
case "start_address1":
startAddress1_u32s = ExtractUint32HexNumberFromString_u32s(argsString_str, stringCtr_u16);
break;
case "end_address1":
endAddress1_u32s = ExtractUint32HexNumberFromString_u32s(argsString_str, stringCtr_u16);
break;
case "length1":
length1_u32s = ExtractUint32HexNumberFromString_u32s(argsString_str, stringCtr_u16);
break;
case "start_address2":
startAddress2_u32s = ExtractUint32HexNumberFromString_u32s(argsString_str, stringCtr_u16);
break;
case "end_address2":
endAddress2_u32s = ExtractUint32HexNumberFromString_u32s(argsString_str, stringCtr_u16);
break;
case "length2":
length2_u32s = ExtractUint32HexNumberFromString_u32s(argsString_str, stringCtr_u16);
break;
case "seed":
seed_u16s = (UInt16)ExtractUint32HexNumberFromString_u32s(argsString_str, stringCtr_u16);
break;
case "order":
//extract text and remove the "=" before the text
textString_str = argsString_str.Substring(stringCtr_u16 + 1,
argsString_str.Length - stringCtr_u16 - 1);
if (0 == String.Compare(textString_str, "LSB_FIRST"))
{
lsbFirst_bols = true;
}
break;
case "size":
//extract text and remove the "=" before the text
textString_str = argsString_str.Substring(stringCtr_u16 + 1,
argsString_str.Length - stringCtr_u16 - 1);
if (0 == String.Compare(textString_str, "WORD"))
{
wordAccess_bols = true;
}
break;
default:
break;
}//switch
}//string length minimum
}//try
catch
{
}
}//all arguments access
}
/**/
/*---------------------------------------------------------------------------------------------------------------*/
/*!@brief Converts input string of hex number to uint32.
* @author Thomas Wiedebusch
* @date 19-Feb-2016..23-Feb-2016
* @param[in] argsString_st input string
* @param[in] stringCtr_u16 string counter at last parameter identifier "="
* @return number_u32 extracted uint32
*
*/
/*---------------------------------------------------------------------------------------------------------------*/
static UInt32 ExtractUint32HexNumberFromString_u32s(String argsString_str, UInt16 stringCtr_u16)
{
UInt32 number_u32 = 0;
try
{
//extract variable and remove the "=0x" before the hexadecimal number
String variableString_str = argsString_str.Substring(stringCtr_u16 + searchIgnoreBytesOfString_cu16,
argsString_str.Length - stringCtr_u16 - searchIgnoreBytesOfString_cu16);
number_u32 = UInt32.Parse(variableString_str, System.Globalization.NumberStyles.HexNumber);
}//try
catch
{
}
return number_u32;
}
/**/
/*---------------------------------------------------------------------------------------------------------------*/
/*!@brief Display start message.
* @author Thomas Wiedebusch
* @date 19-Feb-2016..25-Feb-2016
*
*/
/*---------------------------------------------------------------------------------------------------------------*/
static void DisplayStartMsg_vds()
{
//output program information
Console.WriteLine("================================================================================");
Console.WriteLine(" CRC_CCITT (CRC16 Polynomial 0x1021) Builder!");
Console.WriteLine(" File input formats are Motorola-s19 and TI-txt files");
Console.WriteLine("");
Console.WriteLine(" Version V1.00");
Console.WriteLine("");
Console.WriteLine(" Copyright (c) 2016 SENSUS GmbH, Laatzen, Germany");
Console.WriteLine(" All rights reserved");
Console.WriteLine(" Written by Thomas Wiedebusch");
Console.WriteLine("================================================================================");
//Scanned address and size information
Console.WriteLine("Start address1: 0x{0:X}", startAddress1_u32s);
Console.WriteLine("Length1: 0x{0:X}", length1_u32s);
Console.WriteLine("End address1: 0x{0:X}", endAddress1_u32s);
if ((startAddress2_u32s > 0) && (length2_u32s > 0))
{
Console.WriteLine("Start address2: 0x{0:X}", startAddress2_u32s);
Console.WriteLine("Length2: 0x{0:X}", length2_u32s);
Console.WriteLine("End address2: 0x{0:X}", endAddress2_u32s);
}
//output seed value
Console.WriteLine("Seed: 0x{0:X4}", seed_u16s);
//check data format
if (wordAccess_bols)
{
Console.WriteLine("Access format: WORD");
}
else
{
Console.WriteLine("Access format: BYTE");
}
//check access order
if (lsbFirst_bols)
{
Console.WriteLine("Access order: LSB_FIRST");
}
else
{
Console.WriteLine("Access order: MSB_FIRST");
}
Console.WriteLine("");
}
/**/
/*---------------------------------------------------------------------------------------------------------------*/
/*!@brief Display insufficient parameter error message.
* @author Thomas Wiedebusch
* @date 19-Feb-2016..25-Feb-2016
*
*/
/*---------------------------------------------------------------------------------------------------------------*/
static void DisplayMissedParamErrorMsg_vds()
{
Console.WriteLine("================================================================================");
Console.WriteLine("PARAMETERS ARE MISSED OR WRONG FORMAT, CRC CALCULATION CAN'T BE EXECUTED!");
Console.WriteLine("================================================================================");
Console.WriteLine("");
Console.WriteLine("Required parameters for CRC16 calculation (order independent):");
Console.WriteLine("-file_in=file_name is the name of the input file as string, required");
Console.WriteLine("[-file_out=file_name] is the name of the output file as string, optional");
Console.WriteLine("[-crc_address=0x0..0xFFFFFF] required for file out, else only console display");
Console.WriteLine("-start_address1=0x0..0xFFFFFF required");
Console.WriteLine("-end_address1|length1=0x0..0xFFFFFF required");
Console.WriteLine("[-start_address2=0x0..0xFFFFFF] optional, default 0x0");
Console.WriteLine("[-end_address2|length1=0..0xFFFFFF] optional, default 0x0");
Console.WriteLine("[-seed=0x0..0xFFFF] optional, default 0xFFFF");
Console.WriteLine("[-size=BYTE|WORD] optional, default BYTE");
Console.WriteLine("[-order=MSB_FIRST|LSB_FIRST] optional, default MSB_FIRST");
Console.WriteLine("");
Console.WriteLine("================================================================================");
Console.WriteLine("");
}
/**/
/*---------------------------------------------------------------------------------------------------------------*/
/*!@brief Display result message.
* @author Thomas Wiedebusch
* @date 19-Feb-2016..25-Feb-2016
*
*/
/*---------------------------------------------------------------------------------------------------------------*/
static void DisplayResultMsg_vds()
{
if (crcAddressDefined_bols)
{
Console.WriteLine("CRC address: 0x{0:X}", crcAddress_u32s);
}
Console.WriteLine("Computed CRC16: 0x{0:X4}", crcResult_u16s);
Console.WriteLine("");
}
/**/
/*---------------------------------------------------------------------------------------------------------------*/
/*!@brief Display file information message.
* @author Thomas Wiedebusch
* @date 21-Feb-2016..24-Feb-2016
*
*/
/*---------------------------------------------------------------------------------------------------------------*/
static void DisplayFileInformationMsg_vds()
{
//In/output file information
Console.WriteLine("Input File: " + inputFile_strs);
//if the output file is not explicitly defined output file = input file
if (fileUndefined_cstr == outputFile_strs)
{
Console.WriteLine("Output File: " + inputFile_strs);
}
else
{
Console.WriteLine("Output File: " + outputFile_strs);
}
Console.WriteLine("");
}
/**/
/*---------------------------------------------------------------------------------------------------------------*/
/*!@brief Display input file not found.
* @author Thomas Wiedebusch
* @date 21-Feb-2016
*
*/
/*---------------------------------------------------------------------------------------------------------------*/
static void DisplayInFileNotFoundErrorMsg_vds()
{
Console.WriteLine("INPUT FILE \"" + inputFile_strs + "\" NOT FOUND!");
Console.WriteLine("");
}
/**/
/*---------------------------------------------------------------------------------------------------------------*/
/*!@brief Display file format is unknown.
* @author Thomas Wiedebusch
* @date 21-Feb-2016
*
*/
/*---------------------------------------------------------------------------------------------------------------*/
static void DispalyUnknownFileFormatErrorMsg_vd()
{
Console.WriteLine("UNEXPECTED FILE FORMAT!");
Console.WriteLine("Input file is corrupted or not a Motorola-s19 or TI-txt file!");
Console.WriteLine("");
}
/**/
/*---------------------------------------------------------------------------------------------------------------*/
}//class crcProgram
}//namespace CRC_CCITT
/*=====================================END OF FILE===================================================================*/
Binary file not shown.

After

Width:  |  Height:  |  Size: 9.9 KiB

+771
View File
@@ -0,0 +1,771 @@
/*********************************************************************************************************************/
/*!@file s19FileHandler.cs
* @brief Handle for Motorola-S19 files.
*
*====================================================================================================================\n
* @copyright
*
* ___________________________________________________________________________________________________________________\n
* Copyright (c) 2016 SENSUS, GmbH.\n
* All Rights Reserved.\n
* \n
* Confidential property of\n
* SENSUS GmbH,\n
* Meineckestr. 10, 30880 LAATZEN, GERMANY\n
* \n
* Design by\n
* Hard- und Softwareentwicklung Thomas Wiedebusch,\n
* Ostermarsch 17c, 31191 ALGERMISSEN/UMMELN, GERMANY\n
* \n
*====================================================================================================================\n
* @intro
*
*____________________________________________________________________________________________________________________\n
* Functions:\n
* Reading S19 files,\n
* Support of S0, S2, S5 and S8 records (24Bit addresses and 16Bit record counter),\n
* Building S5 record and place it at the end of the file,\n
* Replacing bytes and generating S2 record for CRC.\n
*
*====================================================================================================================\n
* @version
*
*____________________________________________________________________________________________________________________\n
* V1.00 19-Feb-2016..26-Feb-2016 by Thomas Wiedebusch\n
* - Initial.
*
*
*====================================================================================================================\n
*/
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO;
namespace CRC_CCITT
{
/*---------------------------------------------------------------------------------------------------------------*/
/*!@brief s19FileHandler class.
* @author Thomas Wiedebusch
* @date 19-Feb-2016..24-Feb-2016
*
*/
/*---------------------------------------------------------------------------------------------------------------*/
public class s19FileHandler_t
{
//class variables
String inputFile_str; //file name
String outputFile_str; //file name
String fileLine_str; //one line of the file
crcGenrator_memSetFn_t MemSetFn_vdp; //set data to address of working memory
crcGenrator_memGetFn_t MemGetFn_u8p; //get data from working memory
bool s8RecordFoundInFile_bol = false; //S8 record detected
UInt32 s8RecordFileLine_u32 = 0; //S8 record line in file
bool crcRecordFoundInFile_bol = false; //S2 record with CRC address detected
UInt32 crcRecordFileLine_u32 = 0; //S2 record with CRC address line in file
bool placeCrcToFile_bol; //CRC output to file is required
UInt32 crcAddress_u32; //address for CRC
bool s5RecordFoundInFile_bol = false; //S5 record detected
UInt32 s5RecordFileLine_u32 = 0; //S5 record line in file
bool s5RecordPlacedInoutputFile_bol = false; //S5 record not applied to output file
//S19-Record string, protocol
const String fileHeader_cstr = "S0";
const String dataRecord24BitAddress_cstr = "S2";
const String dataRecordCounter16Bit_cstr = "S5";
const String startAddress24Bit_cstr = "S8";
const Byte s19RecordIdStrSize_cu8 = 2; //size of S19 identifier
const Byte s19RecordLengthStrSize_cu8 = 2; //size of S19 length
const Byte s0RecordAddressStrSize_cu8 = 4; //size of S0 address
const Byte s2RecordAddressStrSize_cu8 = 6; //size of S2 address
const Byte s8RecordAddressStrSize_cu8 = 6; //size of S8 address
const Byte s19RecordDataCrcStrSize_cu8 = 4; //size of S19 CRC16 data
const Byte s19RecordDataStrSize_cu8 = 2; //size of S19 data
const Byte s5RecordCountStrSize_cu8 = 4; //size of S5 counter
const Byte s19RecordCheckStrSize_cu8 = 2; //size of S19 checksum
//S19-Record extracted
String s19RecordId_str; //record identifier containing the "S" and a number
Byte s19RecordLength_u8; //length for data and check
UInt32 s19RecordAddress_u32; //data address for CRC generator module
const Byte maxS19RecordData_cu8 = 32; //number of maximum data bytes in one record
Byte[] s19RecordData_u8a =
new Byte[maxS19RecordData_cu8]; //data fields for dispatch to CRC generator
Byte s19RecordRecChecksum_u8; //checksum read for length, address and data
//calculations
Byte s19RecordCalcChecksum_u8; //rebuild checksum based on file data
UInt16 s2RecordCounter_u16 = 0; //S2 record counter
UInt32 fileLineCtr_u32 = 0; //actual accessed file line
const Byte addressFieldNotUsed_cu8 = 0; //address not used (S5-Record) for checksum calculation
const Byte addressField16BitSize_cu8 = 2; //16 bit address size (S0-Record) for checksum calculation
const Byte addressField24BitSize_cu8 = 3; //24 bit address size (S2, S8-Records) for checksum calculation
/*---------------------------------------------------------------------------------------------------------------*/
/*!@brief Constructor for S19 class:\n
* -initializes file,\n
* -this constructor will only be called if the input file has been found,\n
* -sets delegates to memory set and get function being able to dispatch read data.\n
* @author Thomas Wiedebusch
* @date 19-Feb-2016..21-Feb-2016
* @param[in] inputFileIn_str file name for input file
* @param[in] outputFileIn_str file name for output file, can be identical with input file
* @param[in] MemSetInFn_vdp set function to dispatch data to memory
* @param[in] MemGetInFn_vdp get function to read data from memory
*
*/
/*---------------------------------------------------------------------------------------------------------------*/
public s19FileHandler_t(String inputFileIn_str, String outputFileIn_str, crcGenrator_memSetFn_t MemSetInFn_vdp,
crcGenrator_memGetFn_t MemGetInFn_u8p, UInt32 crcAddressIn_u32, bool placeCrcToFileIn_bol)
{
inputFile_str = inputFileIn_str;
outputFile_str = outputFileIn_str;
MemSetFn_vdp = MemSetInFn_vdp;
MemGetFn_u8p = MemGetInFn_u8p;
placeCrcToFile_bol = placeCrcToFileIn_bol;
crcAddress_u32 = crcAddressIn_u32;
}
/**/
/*---------------------------------------------------------------------------------------------------------------*/
/*!@brief Read input file and store to output file:\n
* -reads every line, format has been checked,\n
* -replaces CRC if required,\n
* -creates S5 record before the end of file S8 record.
* @author Thomas Wiedebusch
* @date 23-Feb-2016..24-Feb-2016
* @param[in] crcResult_u16 result of CRC calculation
*
*/
/*---------------------------------------------------------------------------------------------------------------*/
public void CreateOutputFile_vd(UInt16 crcResult_u16)
{
//the file line counter will be used to reference the input of already detected records
fileLineCtr_u32 = 0;
//mark that s5 record hasn't be accessed
s5RecordPlacedInoutputFile_bol = false;
try
{
//check if file exits
if (File.Exists(inputFile_str))
{
//opens file for read
StreamReader inputFile_st = new StreamReader(inputFile_str);
if (File.Exists(outputFile_str))
{
//erase it
File.Delete(outputFile_str);
}
//open it for write access
StreamWriter outputFile_st = new StreamWriter(outputFile_str, true);
//read single line until and output it to the output file
do
{
//read one line of the input file
fileLine_str = inputFile_st.ReadLine();
//output of CRC to file is required
if (placeCrcToFile_bol)
{
//replace CRC data or build a new entry containing CRC data only
BuildS19CrcRecord_vd(crcResult_u16, outputFile_st);
}//output of CRC to file is required
//check for S5 record generation, replace current S5 record or insert before S8 record
if (!s5RecordPlacedInoutputFile_bol)
{
if ((s5RecordFoundInFile_bol && (s5RecordFileLine_u32 == fileLineCtr_u32))
|| (s8RecordFoundInFile_bol && (s8RecordFileLine_u32 == fileLineCtr_u32)))
{
BuildS5Record_vd(outputFile_st);
}//replace S5 or insert before S8 record
}//S5 not generated
//write all lines to output file
outputFile_st.WriteLine( fileLine_str);
//change file line of input file
fileLineCtr_u32++;
} while (!inputFile_st.EndOfStream);
//place S5 record at file end if not already found
if (!s5RecordPlacedInoutputFile_bol)
{
//places S5 directly at file end position
BuildS5Record_vd(outputFile_st);
}
//release files
inputFile_st.Close();
outputFile_st.Close();
//if the output file is equal to the input file, erase input file and rename temporary output file
if (crcProgram_t.fileUndefined_cstr == outputFile_str)
{
File.Delete(inputFile_str);
if (File.Exists(outputFile_str))
{
//rename output to input file name, output file will be deleted
File.Move(outputFile_str, inputFile_str);
}
}
}//input file exists
}//try
catch
{
}
}
/**/
/*---------------------------------------------------------------------------------------------------------------*/
/*!@brief Build S5 record:\n
* -places it directly to output file if S8 record detected,\n
* -replaces it if old S5 record detected.
* @author Thomas Wiedebusch
* @date 24-Feb-2016
* @param[in] outputFile_st output file stream object
*
*/
/*---------------------------------------------------------------------------------------------------------------*/
void BuildS5Record_vd(StreamWriter outputFile_st)
{
//build the S5 record
s19RecordId_str = dataRecordCounter16Bit_cstr;
//build a new record just containing the S5 without address
s19RecordLength_u8 = s5RecordCountStrSize_cu8 / 2 + s19RecordCheckStrSize_cu8 / 2;
//set counter value
s19RecordData_u8a[0] = (Byte)((s2RecordCounter_u16 >> 8) & 0xFF);
s19RecordData_u8a[1] = (Byte)(s2RecordCounter_u16 & 0xFF);
//if S8 record found in file, build a new record and place it directly
if (s8RecordFoundInFile_bol && (s8RecordFileLine_u32 == fileLineCtr_u32))
{
outputFile_st.WriteLine(BuildS19Record_str(addressFieldNotUsed_cu8));
s5RecordPlacedInoutputFile_bol = true;
}
//replace file line string if s5 record
else if (s5RecordFoundInFile_bol && (s5RecordFileLine_u32 == fileLineCtr_u32))
{
//create s5-Record string for file output
fileLine_str = BuildS19Record_str(addressFieldNotUsed_cu8);
s5RecordPlacedInoutputFile_bol = true;
}
//Nor S8 neither S5 record detected in input file, output S5 directly
else
{
outputFile_st.WriteLine(BuildS19Record_str(addressFieldNotUsed_cu8));
s5RecordPlacedInoutputFile_bol = true;
}
}
/**/
/*---------------------------------------------------------------------------------------------------------------*/
/*!@brief Build CRC record:\n
* -places it directly to output file if new record required,\n
* -replaces data in existing S2 record at CRC address and overwrites actual fileLine_str.
* @author Thomas Wiedebusch
* @date 24-Feb-2016..26-Feb-2016
* @param[in] crcResult_u16 result of CRC calculation
* @param[in] outputFile_st output file stream object
*
*/
/*---------------------------------------------------------------------------------------------------------------*/
void BuildS19CrcRecord_vd(UInt16 crcResult_u16, StreamWriter outputFile_st)
{
s19RecordId_str = dataRecord24BitAddress_cstr;
//if CRC record address is NOT found in file, build a new record and place it directly behind the S0
if (!crcRecordFoundInFile_bol)
{
//output only on file line counter equals 1
if (1 == fileLineCtr_u32)
{
//build a new record just containing the CRC at specified address
s19RecordLength_u8 = s2RecordAddressStrSize_cu8 / 2 + s19RecordDataCrcStrSize_cu8 / 2
+ s19RecordCheckStrSize_cu8 / 2;
s19RecordAddress_u32 = crcAddress_u32;
//set CRC16 value
s19RecordData_u8a[0] = (Byte)(crcResult_u16 & 0xFF);
s19RecordData_u8a[1] = (Byte)((crcResult_u16 >> 8) & 0xFF);
//create s2-Record string for file output and write this additional line to file
outputFile_st.WriteLine(BuildS19Record_str(addressField24BitSize_cu8));
//remove CRC to file request
placeCrcToFile_bol = false;
}//file line counter == 1
}//CRC record is NOT in input file, a new one has been placed to output file
//replace CRC record, this has previously being identified by its file line counter in input file
else if (fileLineCtr_u32 == crcRecordFileLine_u32)
{
//first the length, data and address is being filled, ignore return value
ExtractAndCheckS2Record_bol();
//search address of CRC in S2-Record
UInt32 searchAddress_u32 = s19RecordAddress_u32;
Byte ctr_u8 = 0;
while ((crcAddress_u32 < searchAddress_u32) && (ctr_u8 < maxS19RecordData_cu8))
{
searchAddress_u32++;
ctr_u8++;
}
//replace cells with CRC16 value
s19RecordData_u8a[ctr_u8++] = (Byte)(crcResult_u16 & 0xFF);
s19RecordData_u8a[ctr_u8] = (Byte)((crcResult_u16 >> 8) & 0xFF);
//create s2-Record string for file output
fileLine_str = BuildS19Record_str(addressField24BitSize_cu8);
//remove CRC to file request
placeCrcToFile_bol = false;
}//replace CRC record
}
/**/
/*---------------------------------------------------------------------------------------------------------------*/
/*!@brief Assembling a S19-Record from:\n
* -s19RecordId_str,\n
* -s19RecordLength_u8,\n
* -s19RecordAddress_u32,\n
* -s19RecordData_u8a,\n
* -s19RecordCalcChecksum_u8.
* @author Thomas Wiedebusch
* @date 24-Feb-2016
* @param[in] s19AddressByteLength_u8 length of address field (0, 2, 3 byte)
* @return s19Record_str entirely assembled S19-Record
*
*/
/*---------------------------------------------------------------------------------------------------------------*/
String BuildS19Record_str(Byte s19AddressByteLength_u8)
{
String s19Record_str = s19RecordId_str;
//place the length
s19Record_str += s19RecordLength_u8.ToString("X2");
//for 16 bit or 24 bit address fields
if (addressField24BitSize_cu8 == s19AddressByteLength_u8)
{
s19Record_str += s19RecordAddress_u32.ToString("X6");
}
else if(addressField16BitSize_cu8 == s19AddressByteLength_u8)
{
s19Record_str += s19RecordAddress_u32.ToString("X4");
}
//place data bytes
Byte dataSize_u8 = (Byte)(s19RecordLength_u8 - s19RecordCheckStrSize_cu8 / 2 - s19AddressByteLength_u8);
for (Byte dataCtr_u8 = 0; dataCtr_u8 < dataSize_u8; dataCtr_u8++)
{
s19Record_str += s19RecordData_u8a[dataCtr_u8].ToString("X2");
}
//build the checksum
BuildS19RecordChecksum_vd(s19AddressByteLength_u8);
//place the calculated checksum
s19Record_str += s19RecordCalcChecksum_u8.ToString("X2");
return s19Record_str;
}
/**/
/*---------------------------------------------------------------------------------------------------------------*/
/*!@brief Read file and dispatch the S2-Records to the CRC generator:\n
* -reads every line and checks format.
* @author Thomas Wiedebusch
* @date 23-Feb-2016..25-Feb-2016
* @return file format valid
*
*/
/*---------------------------------------------------------------------------------------------------------------*/
public bool ValidateInputFile_bol()
{
bool returnValue_bol = false;
fileLineCtr_u32 = 0;
try
{
//check if file exits
if (File.Exists(inputFile_str))
{
//resets s2 record counter
s2RecordCounter_u16 = 0;
//opens file for read
StreamReader inputFile_st = new StreamReader(inputFile_str);
//read single line until file end or validation failed
do
{
fileLine_str = inputFile_st.ReadLine();
//decode the file line
returnValue_bol = ProcessInputFileLine_bol();
//change file line counter after check and line counter reminder for the records
fileLineCtr_u32++;
} while (returnValue_bol && !inputFile_st.EndOfStream);
//release file
inputFile_st.Close();
}
}//try
catch
{
}
return returnValue_bol;
}
/**/
/*---------------------------------------------------------------------------------------------------------------*/
/*!@brief Builds the S19 Record checksum, the S19 fields have to be prepared in advance:\n
* -Byte wise accumulation as word from length until last data byte,\n
* -ones complement of accumulation result,\n
* -masked out lower byte and typecast lower byte to byte,\n
* -s19RecordLength_u8 (length of address + data + checksum)\n
* -s19RecordAddress_u32,\n
* -s19RecordData_u8a[],\n
* -result is always being placed to s19RecordCalcChecksum_u8 (length + address + data).
* @author Thomas Wiedebusch
* @date 24-Feb-2016
* @param[in] s19AddressByteLength_u8 length of address field (0, 2, 3 byte)
*
*/
/*---------------------------------------------------------------------------------------------------------------*/
void BuildS19RecordChecksum_vd(Byte s19AddressByteLength_u8)
{
UInt16 accu_u16 = (UInt16)s19RecordLength_u8;
//for 16 bit or 24 bit address fields
if (s19AddressByteLength_u8 > addressFieldNotUsed_cu8)
{
accu_u16 += (UInt16)((s19RecordAddress_u32 >> 8) & 0x00FF);
accu_u16 += (UInt16)(s19RecordAddress_u32 & 0x00FF);
//for 24 bit address filed
if (s19AddressByteLength_u8 > addressField16BitSize_cu8)
{
accu_u16 += (UInt16)((s19RecordAddress_u32 >> 16) & 0x00FF);
}
}
Byte dataSize_u8 = (Byte)(s19RecordLength_u8 - s19RecordCheckStrSize_cu8 / 2 - s19AddressByteLength_u8);
for (Byte ctr_u8 = 0; ctr_u8 < dataSize_u8; ctr_u8++)
{
accu_u16 += (UInt16)s19RecordData_u8a[ctr_u8];
}
s19RecordCalcChecksum_u8 = (Byte)(~accu_u16 & 0x00FF);
}
/**/
/*---------------------------------------------------------------------------------------------------------------*/
/*!@brief Extract the information given by the read line from file:\n
* -extracts the record identifier S0, S2, S5 or S8,\n
* -dispatches S2 records to CRC generator memory,\n
* -branches to the extract subroutines for the record types,\n
* -sets record counters and reminders.
* @author Thomas Wiedebusch
* @date 22-Feb-2016..25-Feb-2016
* @return s19 file validated
*
*/
/*---------------------------------------------------------------------------------------------------------------*/
bool ProcessInputFileLine_bol()
{
bool returnValue_bol = false;
try
{
//copy identifier
s19RecordId_str = fileLine_str.Substring(0, s19RecordIdStrSize_cu8);
switch (s19RecordId_str)
{
case fileHeader_cstr:
returnValue_bol = ExtractAndCheckS0Record_bol();
break;
case dataRecord24BitAddress_cstr:
if (ExtractAndCheckS2Record_bol())
{
returnValue_bol = true;
//s2 record counter
s2RecordCounter_u16++;
//dispatch content to CRC generator
Byte dataSize_u8 = (Byte)(s19RecordLength_u8 - s19RecordCheckStrSize_cu8 / 2
- s2RecordAddressStrSize_cu8 / 2);
for (Byte ctr_u8 = 0; ctr_u8 < dataSize_u8; ctr_u8++)
{
MemSetFn_vdp(s19RecordAddress_u32, s19RecordData_u8a[ctr_u8]);
//check for CRC address in S2 record
if (crcAddress_u32 == s19RecordAddress_u32)
{
//remind S2 with CRC content
crcRecordFoundInFile_bol = true;
crcRecordFileLine_u32 = fileLineCtr_u32;
}//CRC address found
//setup next address after CRC check
s19RecordAddress_u32++;
}//data copied
}
break;
case dataRecordCounter16Bit_cstr:
if (ExtractAndCheckS5Record_bol())
{
returnValue_bol = true;
//remind S8 content
s5RecordFoundInFile_bol = true;
s5RecordFileLine_u32 = fileLineCtr_u32;
}
break;
case startAddress24Bit_cstr:
if (ExtractAndCheckS8Record_bol())
{
returnValue_bol = true;
//remind S8 content
s8RecordFoundInFile_bol = true;
s8RecordFileLine_u32 = fileLineCtr_u32;
}
break;
default:
break;
}//switch
}//try
catch
{
}
return returnValue_bol;
}
/**/
/*---------------------------------------------------------------------------------------------------------------*/
/*!@brief Extract the information given by the read line from file:\n
* -copies data to hexadecimal data buffer,\
* -builds the checksum and validates it.
* @author Thomas Wiedebusch
* @date 22-Feb-2016..24-Feb-2016
* @return s19 file validated
*
*/
/*---------------------------------------------------------------------------------------------------------------*/
bool ExtractAndCheckS0Record_bol()
{
bool returnValue_bol = false;
Byte stringPositionCtr_u8 = s19RecordIdStrSize_cu8;
try
{
//extract the length
String var_str = fileLine_str.Substring(stringPositionCtr_u8, s19RecordLengthStrSize_cu8);
s19RecordLength_u8 = Byte.Parse(var_str, System.Globalization.NumberStyles.HexNumber);
//limit length to avoid access of behind the border
if (s19RecordLength_u8 > maxS19RecordData_cu8 + s0RecordAddressStrSize_cu8 / 2 + s19RecordCheckStrSize_cu8 / 2)
{
s19RecordLength_u8 = maxS19RecordData_cu8 + s0RecordAddressStrSize_cu8 / 2 + s19RecordCheckStrSize_cu8 / 2;
}
//extract the address and accumulate it, it should be 0 for S0 record
stringPositionCtr_u8 += s19RecordLengthStrSize_cu8;
var_str = fileLine_str.Substring(stringPositionCtr_u8, s0RecordAddressStrSize_cu8);
s19RecordAddress_u32 = UInt32.Parse(var_str, System.Globalization.NumberStyles.HexNumber);
//extract and accumulate data
stringPositionCtr_u8 += s0RecordAddressStrSize_cu8;
for (Byte ctr_u8 = 0; ctr_u8 < s19RecordLength_u8 - s19RecordCheckStrSize_cu8 / 2
- s0RecordAddressStrSize_cu8 / 2; ctr_u8++)
{
var_str = fileLine_str.Substring(stringPositionCtr_u8, s19RecordDataStrSize_cu8);
s19RecordData_u8a[ctr_u8] = Byte.Parse(var_str, System.Globalization.NumberStyles.HexNumber);
stringPositionCtr_u8 += s19RecordDataStrSize_cu8;
}
//read the checksum
var_str = fileLine_str.Substring(stringPositionCtr_u8, s19RecordCheckStrSize_cu8);
s19RecordRecChecksum_u8 = Byte.Parse(var_str, System.Globalization.NumberStyles.HexNumber);
//build new checksum
BuildS19RecordChecksum_vd(addressField16BitSize_cu8);
//compare the calculated with the received checksum
if (s19RecordCalcChecksum_u8 == s19RecordRecChecksum_u8)
{
returnValue_bol = true;
}
}//try
catch
{
}
return returnValue_bol;
}
/**/
/*---------------------------------------------------------------------------------------------------------------*/
/*!@brief Extract the information given by the read line from file:\n
* -copies data to hexadecimal data buffer,\
* -builds the checksum and validates it.
* @author Thomas Wiedebusch
* @date 22-Feb-2016..24-Feb-2016
* @return s19 file validated
*
*/
/*---------------------------------------------------------------------------------------------------------------*/
bool ExtractAndCheckS8Record_bol()
{
bool returnValue_bol = false;
Byte stringPositionCtr_u8 = s19RecordIdStrSize_cu8;
try
{
//extract the length
String var_str = fileLine_str.Substring(stringPositionCtr_u8, s19RecordLengthStrSize_cu8);
s19RecordLength_u8 = Byte.Parse(var_str, System.Globalization.NumberStyles.HexNumber);
//limit length to avoid access of behind the border
if (s19RecordLength_u8 > s8RecordAddressStrSize_cu8 / 2 + s19RecordCheckStrSize_cu8 / 2)
{
s19RecordLength_u8 = s8RecordAddressStrSize_cu8 / 2 + s19RecordCheckStrSize_cu8 / 2;
}
//extract the address and accumulate it
stringPositionCtr_u8 += s19RecordLengthStrSize_cu8;
var_str = fileLine_str.Substring(stringPositionCtr_u8, s8RecordAddressStrSize_cu8);
s19RecordAddress_u32 = UInt32.Parse(var_str, System.Globalization.NumberStyles.HexNumber);
//read the checksum
stringPositionCtr_u8 += s8RecordAddressStrSize_cu8;
var_str = fileLine_str.Substring(stringPositionCtr_u8, s19RecordCheckStrSize_cu8);
s19RecordRecChecksum_u8 = Byte.Parse(var_str, System.Globalization.NumberStyles.HexNumber);
//build new checksum
BuildS19RecordChecksum_vd(addressField24BitSize_cu8);
//compare the calculated with the received checksum
if (s19RecordCalcChecksum_u8 == s19RecordRecChecksum_u8)
{
returnValue_bol = true;
}
}//try
catch
{
}
return returnValue_bol;
}
/**/
/*---------------------------------------------------------------------------------------------------------------*/
/*!@brief Extract the information given by the read line from file:\n
* -builds the base address,\n
* -copies data to hexadecimal data buffer,\n
* -builds the checksum and validates it.
* @author Thomas Wiedebusch
* @date 22-Feb-2016..24-Feb-2016
* @return s19 file validated
*
*/
/*---------------------------------------------------------------------------------------------------------------*/
bool ExtractAndCheckS2Record_bol()
{
bool returnValue_bol = false;
Byte stringPositionCtr_u8 = s19RecordIdStrSize_cu8;
try
{
//extract the length
String var_str = fileLine_str.Substring(stringPositionCtr_u8, s19RecordLengthStrSize_cu8);
s19RecordLength_u8 = Byte.Parse(var_str, System.Globalization.NumberStyles.HexNumber);
//limit length to avoid access of behind the border
if (s19RecordLength_u8 > maxS19RecordData_cu8 + s2RecordAddressStrSize_cu8 / 2 + s19RecordCheckStrSize_cu8 / 2)
{
s19RecordLength_u8 = maxS19RecordData_cu8 + s2RecordAddressStrSize_cu8 / 2 + s19RecordCheckStrSize_cu8 / 2;
}
//extract the address and accumulate it
stringPositionCtr_u8 += s19RecordLengthStrSize_cu8;
var_str = fileLine_str.Substring(stringPositionCtr_u8, s2RecordAddressStrSize_cu8);
s19RecordAddress_u32 = UInt32.Parse(var_str, System.Globalization.NumberStyles.HexNumber);
//extract and accumulate data
stringPositionCtr_u8 += s2RecordAddressStrSize_cu8;
Byte dataSize_u8 = (Byte)(s19RecordLength_u8 - s19RecordCheckStrSize_cu8 / 2 - s2RecordAddressStrSize_cu8 / 2);
for (Byte ctr_u8 = 0; ctr_u8 < dataSize_u8; ctr_u8++)
{
var_str = fileLine_str.Substring(stringPositionCtr_u8, s19RecordDataStrSize_cu8);
s19RecordData_u8a[ctr_u8] = Byte.Parse(var_str, System.Globalization.NumberStyles.HexNumber);
stringPositionCtr_u8 += s19RecordDataStrSize_cu8;
}
//read the checksum
var_str = fileLine_str.Substring(stringPositionCtr_u8, s19RecordCheckStrSize_cu8);
s19RecordRecChecksum_u8 = Byte.Parse(var_str, System.Globalization.NumberStyles.HexNumber);
//build new checksum
BuildS19RecordChecksum_vd(addressField24BitSize_cu8);
//compare the calculated with the received checksum
if (s19RecordCalcChecksum_u8 == s19RecordRecChecksum_u8)
{
returnValue_bol = true;
}//checksum okay
}//try
catch
{
}
return returnValue_bol;
}
/**/
/*---------------------------------------------------------------------------------------------------------------*/
/*!@brief Extract the information given by the read line from file:\n
* -copies data to hexadecimal data buffer,\
* -builds the checksum and validates it.
* @author Thomas Wiedebusch
* @date 22-Feb-2016..24-Feb-2014
* @return s19 file validated
*
*/
/*---------------------------------------------------------------------------------------------------------------*/
bool ExtractAndCheckS5Record_bol()
{
bool returnValue_bol = false;
Byte stringPositionCtr_u8 = s19RecordIdStrSize_cu8;
try
{
//extract the length which should always be 3
String var_str = fileLine_str.Substring(stringPositionCtr_u8, s19RecordLengthStrSize_cu8);
s19RecordLength_u8 = Byte.Parse(var_str, System.Globalization.NumberStyles.HexNumber);
//limit length to avoid access of behind the border
if (s19RecordLength_u8 > s5RecordCountStrSize_cu8 / 2 + s19RecordCheckStrSize_cu8 / 2)
{
s19RecordLength_u8 = s5RecordCountStrSize_cu8 / 2 + s19RecordCheckStrSize_cu8 / 2;
}
//extract and accumulate the counts
stringPositionCtr_u8 += s19RecordLengthStrSize_cu8;
var_str = fileLine_str.Substring(stringPositionCtr_u8, s5RecordCountStrSize_cu8);
UInt16 s2RecordCtr_u16 = UInt16.Parse(var_str, System.Globalization.NumberStyles.HexNumber);
//read the checksum
stringPositionCtr_u8 += s5RecordCountStrSize_cu8;
var_str = fileLine_str.Substring(stringPositionCtr_u8, s19RecordCheckStrSize_cu8);
s19RecordRecChecksum_u8 = Byte.Parse(var_str, System.Globalization.NumberStyles.HexNumber);
//build new checksum
BuildS19RecordChecksum_vd(addressFieldNotUsed_cu8);
//compare the calculated with the received checksum
if (s19RecordCalcChecksum_u8 == s19RecordRecChecksum_u8)
{
returnValue_bol = true;
}
}//try
catch
{
}
return returnValue_bol;
}
/**/
/*---------------------------------------------------------------------------------------------------------------*/
}//class s19FileHandler
}//namespace CRC_CCITT
/*=====================================END OF FILE===================================================================*/
+398
View File
@@ -0,0 +1,398 @@
/*********************************************************************************************************************/
/*!@file txtFileHandler.cs
* @brief Handle for Texas Instruments-txt files.
*
*====================================================================================================================\n
* @copyright
*
* ___________________________________________________________________________________________________________________\n
* Copyright (c) 2016 SENSUS, GmbH.\n
* All Rights Reserved.\n
* \n
* Confidential property of\n
* SENSUS GmbH,\n
* Meineckestr. 10, 30880 LAATZEN, GERMANY\n
* \n
* Design by\n
* Hard- und Softwareentwicklung Thomas Wiedebusch,\n
* Ostermarsch 17c, 31191 ALGERMISSEN/UMMELN, GERMANY\n
* \n
*====================================================================================================================\n
* @intro
*
*____________________________________________________________________________________________________________________\n
* Functions:\n
* Reading txt files,\n
* Replacing bytes with CRC.\n
*
*====================================================================================================================\n
* @version
*
*____________________________________________________________________________________________________________________\n
* V1.00 25-Feb-2016..27-Feb-2016 by Thomas Wiedebusch\n
* - Initial.
*
*
*====================================================================================================================\n
*/
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO;
namespace CRC_CCITT
{
/*---------------------------------------------------------------------------------------------------------------*/
/*!@brief txtFileHandler class.
* @author Thomas Wiedebusch
* @date 25-Feb-2016
*
*/
/*---------------------------------------------------------------------------------------------------------------*/
class txtFileHandler_t
{
//class variables
String inputFile_str; //file name
String outputFile_str; //file name
String fileLine_str; //one line of the file
crcGenrator_memSetFn_t MemSetFn_vdp; //set data to address of working memory
crcGenrator_memGetFn_t MemGetFn_u8p; //get data from working memory
UInt32 crcFileLineBaseAddress_u32 = 0; //CRC file line address reminder set during input file processing
UInt32 crcFileLine_u32 = 0; //CRC address line in file reminder set during input file processing
bool crcFileLineFound_bol = false; //CRC address in file found reminder
UInt32 memAddressCtr_u32 = 0; //CRC memory address counter
bool placeCrcToFile_bol; //CRC output to file is required
UInt32 crcAddress_u32; //CRC address given as parameter at startup
//txt file markers
const Char addressMarker_cchr = '@'; //base address marker
const Char endOfFileMarker_cchr = 'q'; //end of file marker
const Byte maxDataOfFileLine_cu8 = 16; //maximum data at one file line
const Byte fileLineDataCellIncrement_cu8 = 3; //3 digits increment for one data byte e.g. A5_
//calculations
UInt32 fileLineCtr_u32 = 0; //actual accessed file line
bool memoryAddressSetup_bol = false; //initial memory address has been set
/*---------------------------------------------------------------------------------------------------------------*/
/*!@brief Constructor for txt file handler class:\n
* -initializes file,\n
* -this constructor will only be called if the input file has been found,\n
* -sets delegates to memory set and get function being able to dispatch read data.\n
* @author Thomas Wiedebusch
* @date 25-Feb-2016
* @param[in] inputFileIn_str file name for input file
* @param[in] outputFileIn_str file name for output file, can be identical with input file
* @param[in] MemSetInFn_vdp set function to dispatch data to memory
* @param[in] MemGetInFn_vdp get function to read data from memory
*
*/
/*---------------------------------------------------------------------------------------------------------------*/
public txtFileHandler_t(String inputFileIn_str, String outputFileIn_str, crcGenrator_memSetFn_t MemSetInFn_vdp,
crcGenrator_memGetFn_t MemGetInFn_u8p, UInt32 crcAddressIn_u32, bool placeCrcToFileIn_bol)
{
inputFile_str = inputFileIn_str;
outputFile_str = outputFileIn_str;
MemSetFn_vdp = MemSetInFn_vdp;
MemGetFn_u8p = MemGetInFn_u8p;
placeCrcToFile_bol = placeCrcToFileIn_bol;
crcAddress_u32 = crcAddressIn_u32;
}
/**/
/*---------------------------------------------------------------------------------------------------------------*/
/*!@brief Read file and dispatch the data to the CRC generator:\n
* -reads every line and checks format.
* @author Thomas Wiedebusch
* @date 25-Feb-2016
* @return file format valid
*
*/
/*---------------------------------------------------------------------------------------------------------------*/
public bool ValidateInputFile_bol()
{
bool returnValue_bol = false;
fileLineCtr_u32 = 0;
try
{
//check if file exits
if (File.Exists(inputFile_str))
{
//opens file for read
StreamReader inputFile_st = new StreamReader(inputFile_str);
//read single line until file end or validation failed
do
{
fileLine_str = inputFile_st.ReadLine();
//decode the file line
returnValue_bol = ProcessInputFileLine_bol();
//change file line counter after check and line counter reminder for the records
fileLineCtr_u32++;
} while (returnValue_bol && !inputFile_st.EndOfStream);
//release file
inputFile_st.Close();
}
}//try
catch
{
}
return returnValue_bol;
}
/**/
/*---------------------------------------------------------------------------------------------------------------*/
/*!@brief Extract the information given by the read line from file:\n
* -builds base address from '@' input,\n
* -extracts bytes and dispatches these to CRC generator memory,\n
* -searches for CRC address and reminds file line for this,\n
* -validates file with file end marker 'q'.
* @author Thomas Wiedebusch
* @date 25-Feb-2016..26-Feb-2016
* @return txt file valid
*
*/
/*---------------------------------------------------------------------------------------------------------------*/
bool ProcessInputFileLine_bol()
{
bool returnValue_bol = false;
try
{
//read first byte of line
Char lineStart_chr = fileLine_str[0];
switch (lineStart_chr)
{
case addressMarker_cchr:
//extract new base address
String mem_str = fileLine_str.Substring(1, fileLine_str.Length - 1);
memAddressCtr_u32 = UInt32.Parse( mem_str, System.Globalization.NumberStyles.HexNumber);
//check memory address range
if( crcGenerator_t.maxMemBytes_cu32 > memAddressCtr_u32)
{
memoryAddressSetup_bol = true;
returnValue_bol = true;
}
break;
case endOfFileMarker_cchr:
//if end of file marker read on first line then the file is invalid
if (0 != fileLineCtr_u32)
{
returnValue_bol = true;
}
break;
default:
//if data read on first line then the file is invalid
if ((0 != fileLineCtr_u32) && (memoryAddressSetup_bol))
{
Byte data_u8;
Byte fileLineDataCtr_u8 = 0;
String data_str;
//remind the base address of this file line to save it for CRC replacement
UInt32 fileLineBaseAddress_u32 = memAddressCtr_u32;
//search file line
for (Byte ctr_u8 = 0; ctr_u8 < maxDataOfFileLine_cu8; ctr_u8++)
{
//inner loop limitation to actual file line length
while (fileLine_str.Length > fileLineDataCtr_u8)
{
//remind file line for CRC output
if (crcAddress_u32 == memAddressCtr_u32)
{
//remind the file entry
crcFileLine_u32 = fileLineCtr_u32;
//remind the base address for the file line for CRC replacement
crcFileLineBaseAddress_u32 = fileLineBaseAddress_u32;
//mark that entry has been found
crcFileLineFound_bol = true;
}
//extract data
data_str = fileLine_str.Substring(fileLineDataCtr_u8, fileLineDataCellIncrement_cu8);
data_u8 = Byte.Parse(data_str, System.Globalization.NumberStyles.HexNumber);
//dispatch data to CRC generator
MemSetFn_vdp(memAddressCtr_u32, data_u8);
memAddressCtr_u32++;
fileLineDataCtr_u8 += fileLineDataCellIncrement_cu8;
}//file line length
}//data counter
returnValue_bol = true;
}
break;
}//switch
}//try
catch
{
}
return returnValue_bol;
}
/**/
/*---------------------------------------------------------------------------------------------------------------*/
/*!@brief Read input file and store it to output file:\n
* -reads every line, format has been checked,\n
* -replaces CRC if required.
* @author Thomas Wiedebusch
* @date 25-Feb-2016..26-Feb-2016
* @param[in] crcResult_u16 result of CRC calculation
*
*/
/*---------------------------------------------------------------------------------------------------------------*/
public void CreateOutputFile_vd(UInt16 crcResult_u16)
{
//the file line counter will be used to reference the input of already detected records
fileLineCtr_u32 = 0;
try
{
//check if file exits
if (File.Exists(inputFile_str))
{
//opens file for read
StreamReader inputFile_st = new StreamReader(inputFile_str);
if (File.Exists(outputFile_str))
{
//erase it
File.Delete(outputFile_str);
}
//open it for write access
StreamWriter outputFile_st = new StreamWriter(outputFile_str, true);
//read single line until and output it to the output file
do
{
//read one line of the input file
fileLine_str = inputFile_st.ReadLine();
//output of CRC to file is required
if (placeCrcToFile_bol)
{
//if CRC address is not in file generate a new address with CRC only at the beginning
if (!crcFileLineFound_bol)
{
//build a new file entry for CRC which is not inside the file address range
BuildAndWriteNewCrc_vd(crcResult_u16, outputFile_st);
//remove CRC to file request
placeCrcToFile_bol = false;
}
//search for file entry to replace CRC
else if (crcFileLine_u32 == fileLineCtr_u32)
{
//the base address for this file line has been set in advance during file scan
ReplaceCrcData_vd(crcResult_u16);
//remove CRC to file request
placeCrcToFile_bol = false;
}
}//output of CRC to file is required
//write all lines to output file
outputFile_st.WriteLine(fileLine_str);
//change file line of input file
fileLineCtr_u32++;
} while (!inputFile_st.EndOfStream);
//release files
inputFile_st.Close();
outputFile_st.Close();
//if the output file is equal to the input file, erase input file and rename temporary output file
if (crcProgram_t.fileUndefined_cstr == outputFile_str)
{
File.Delete(inputFile_str);
if (File.Exists(outputFile_str))
{
//rename output to input file name, output file will be deleted
File.Move(outputFile_str, inputFile_str);
}
}
}//input file exists
}//try
catch
{
}
}
/**/
/*---------------------------------------------------------------------------------------------------------------*/
/*!@brief Replaces the CRC data if CRC address is inside the file address range:\n
* -search for CRC address,\n
* -replace CRC data in fileLine_str.
* @author Thomas Wiedebusch
* @date 26-Feb-2016..27-Feb-2016
* @param[in] crcResult_u16 result of CRC calculation
*
*/
/*---------------------------------------------------------------------------------------------------------------*/
void ReplaceCrcData_vd(UInt16 crcResult_u16)
{
//build the CRC sub string for replacement
Byte dataLsb_u8 = (Byte)(crcResult_u16 & 0x00FF);
Byte dataMsb_u8 = (Byte)((crcResult_u16 >> 8) & 0x00FF);
String crcSubStringOutput_str = dataLsb_u8.ToString("X2") + " " + dataMsb_u8.ToString("X2") + " ";
//search for address entry in file
memAddressCtr_u32 = crcFileLineBaseAddress_u32;
UInt32 beforeCrcAddress_u32 = crcFileLineBaseAddress_u32;
Byte ctr_u8 = 0;
while (memAddressCtr_u32 < crcAddress_u32)
{
ctr_u8 += fileLineDataCellIncrement_cu8;
memAddressCtr_u32++;
}
//extract string before CRC address from fileLine_str
String beforeCrcAddress_str = "";
if (beforeCrcAddress_u32 < crcAddress_u32)
{
beforeCrcAddress_str = fileLine_str.Substring(0, ctr_u8);
}
//extract string after CRC address from fileLine_str
String afterCrcAddress_str = "";
if (fileLine_str.Length > ctr_u8 + 2 * fileLineDataCellIncrement_cu8)
{
afterCrcAddress_str = fileLine_str.Substring(ctr_u8 + 2 * fileLineDataCellIncrement_cu8,
fileLine_str.Length - (ctr_u8 + 2 * fileLineDataCellIncrement_cu8));
}
//replace fileLine_str with substring at ctr position
fileLine_str = beforeCrcAddress_str + crcSubStringOutput_str + afterCrcAddress_str;
}
/**/
/*---------------------------------------------------------------------------------------------------------------*/
/*!@brief Builds and writes a new CRC entry if CRC address is outside the file address range:\n
* -assemble and write CRC address,\n
* -assemble and write CRC data.
* @author Thomas Wiedebusch
* @date 26-Feb-2016
* @param[in] crcResult_u16 result of CRC calculation
* @param[in] outputFile_st output file stream object
*
*/
/*---------------------------------------------------------------------------------------------------------------*/
void BuildAndWriteNewCrc_vd(UInt16 crcResult_u16, StreamWriter outputFile_st)
{
//build the NEW address for CRC
String crcOutput_str = addressMarker_cchr.ToString();
crcOutput_str += crcAddress_u32.ToString("X");
//write address to file
outputFile_st.WriteLine(crcOutput_str);
//build the CRC file line (line contains CRC only)
Byte dataLsb_u8, dataMsb_u8;
dataLsb_u8 = (Byte)(crcResult_u16 & 0x00FF);
dataMsb_u8 = (Byte)((crcResult_u16 >> 8) & 0x00FF);
crcOutput_str = dataLsb_u8.ToString("X2") + " " + dataMsb_u8.ToString("X2");
//write CRC data to file
outputFile_st.WriteLine(crcOutput_str);
}
/**/
/*---------------------------------------------------------------------------------------------------------------*/
}//class txtFileHandler
}//namespace CRC_CCITT
/*=====================================END OF FILE===================================================================*/