summaryrefslogtreecommitdiff
path: root/maximus/python/lib
diff options
context:
space:
mode:
authorronciere2007-12-11 15:33:06 +0000
committerronciere2007-12-11 15:33:06 +0000
commitc27b030c2669a1cc1abc048817aec09b1ba3e7c7 (patch)
treeec8959034391fab434f96d47fbcadda9b9eeb997 /maximus/python/lib
parent4234b17467bcf66f8b5fc41e07541e69be4e411b (diff)
Add Frame Control helpers with crc24 computing
git-svn-id: svn+ssh://pessac/svn/cesar/trunk@1125 017c9cb6-072f-447c-8318-d5b54f68fe89
Diffstat (limited to 'maximus/python/lib')
-rw-r--r--maximus/python/lib/Constants.py1
-rw-r--r--maximus/python/lib/crc24.py478
-rw-r--r--maximus/python/lib/crc24_algorithms.py225
-rw-r--r--maximus/python/lib/crc24_lexer.py240
-rw-r--r--maximus/python/lib/crc24_parser.py441
-rw-r--r--maximus/python/lib/crc24_symtable.py1232
-rw-r--r--maximus/python/lib/mmentryFields.py4
-rw-r--r--maximus/python/lib/pycrc24.py214
8 files changed, 2834 insertions, 1 deletions
diff --git a/maximus/python/lib/Constants.py b/maximus/python/lib/Constants.py
index b1b62b01b4..14b81ab5a6 100644
--- a/maximus/python/lib/Constants.py
+++ b/maximus/python/lib/Constants.py
@@ -1,6 +1,7 @@
# -*- coding:Utf-8 -*-
pow_2_64=18446744073709551616
+pow_2_63=9223372036854775808
MAX_TONE_MAPS = 7
diff --git a/maximus/python/lib/crc24.py b/maximus/python/lib/crc24.py
new file mode 100644
index 0000000000..ddc781788d
--- /dev/null
+++ b/maximus/python/lib/crc24.py
@@ -0,0 +1,478 @@
+# -*- coding: Latin-1 -*-
+
+# pycrc -- parametrisable CRC calculation utility and C source code generator
+#
+# Copyright (c) 2006-2007 Thomas Pircher <tehpeh@gmx.net>
+#
+# Permission is hereby granted, free of charge, to any person obtaining a copy
+# of this software and associated documentation files (the "Software"), to deal
+# in the Software without restriction, including without limitation the rights
+# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+# copies of the Software, and to permit persons to whom the Software is
+# furnished to do so, subject to the following conditions:
+#
+# The above copyright notice and this permission notice shall be included in
+# all copies or substantial portions of the Software.
+#
+# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+# THE SOFTWARE.
+
+
+"""
+Option parsing library for pycrc.
+use as follows:
+
+ from crc_opt import Options
+
+ opt = Options("0.6")
+ opt.parse(sys.argv)
+
+This file is part of pycrc.
+"""
+
+from optparse import OptionParser, Option, OptionValueError
+from copy import copy
+import string
+import sys
+
+
+# function check_hex
+###############################################################################
+def check_hex(option, opt, value):
+ """
+ Checks if a value is given in a decimal integer of hexadecimal reppresentation.
+ Returns the converted value or rises an exception on error.
+ """
+ try:
+ if value.lower().startswith("0x"):
+ return string.atoi(value, 16)
+ else:
+ return string.atoi(value)
+ except ValueError:
+ raise OptionValueError("option %s: invalid integer or hexadecimal value: %r" % (opt, value))
+
+# function check_bool
+###############################################################################
+def check_bool(option, opt, value):
+ """
+ Checks if a value is given as a boolean value (either 0 or 1 or "true" or "false")
+ Returns the converted value or rises an exception on error.
+ """
+ if value.isdigit():
+ return string.atoi(value, 10) != 0
+ elif value.lower() == "false":
+ return False
+ elif value.lower() == "true":
+ return True
+ else:
+ raise OptionValueError("option %s: invalid boolean value: %r" % (opt, value))
+
+
+# Class MyOption
+###############################################################################
+class MyOption(Option):
+ """
+ New option parsing class extends the Option class
+ """
+ TYPES = Option.TYPES + ("hex", "bool")
+ TYPE_CHECKER = copy(Option.TYPE_CHECKER)
+ TYPE_CHECKER["hex"] = check_hex
+ TYPE_CHECKER["bool"] = check_bool
+
+
+# function model_cb
+###############################################################################
+def model_cb(option, opt_str, value, parser):
+ """
+ This function sets up the single parameters if the 'model' option has been selected
+ by the user.
+ """
+ mod = value.lower();
+ if mod == "crc-5":
+ setattr(parser.values, "width", 5)
+ setattr(parser.values, "poly", 0x05L)
+ setattr(parser.values, "reflect_in", True)
+ setattr(parser.values, "xor_in", 0x1fL)
+ setattr(parser.values, "reflect_out", True)
+ setattr(parser.values, "xor_out", 0x1fL)
+ elif mod == "crc-8":
+ setattr(parser.values, "width", 8)
+ setattr(parser.values, "poly", 0x07L)
+ setattr(parser.values, "reflect_in", False)
+ setattr(parser.values, "xor_in", 0x0L)
+ setattr(parser.values, "reflect_out", False)
+ setattr(parser.values, "xor_out", 0x0L)
+ elif mod == "crc-15":
+ setattr(parser.values, "width", 15)
+ setattr(parser.values, "poly", 0x4599L)
+ setattr(parser.values, "reflect_in", False)
+ setattr(parser.values, "xor_in", 0x0L)
+ setattr(parser.values, "reflect_out", False)
+ setattr(parser.values, "xor_out", 0x0L)
+ elif mod == "crc-16":
+ setattr(parser.values, "width", 16)
+ setattr(parser.values, "poly", 0x8005L)
+ setattr(parser.values, "reflect_in", True)
+ setattr(parser.values, "xor_in", 0x0L)
+ setattr(parser.values, "reflect_out", True)
+ setattr(parser.values, "xor_out", 0x0L)
+ elif mod == "crc-16-usb":
+ setattr(parser.values, "width", 16)
+ setattr(parser.values, "poly", 0x8005L)
+ setattr(parser.values, "reflect_in", True)
+ setattr(parser.values, "xor_in", 0xffffL)
+ setattr(parser.values, "reflect_out", True)
+ setattr(parser.values, "xor_out", 0xffffL)
+ elif mod == "ccitt":
+ setattr(parser.values, "width", 16)
+ setattr(parser.values, "poly", 0x1021L)
+ setattr(parser.values, "reflect_in", False)
+ setattr(parser.values, "xor_in", 0xffffL)
+ setattr(parser.values, "reflect_out", False)
+ setattr(parser.values, "xor_out", 0x0L)
+ elif mod == "kermit":
+ setattr(parser.values, "width", 16)
+ setattr(parser.values, "poly", 0x1021L)
+ setattr(parser.values, "reflect_in", True)
+ setattr(parser.values, "xor_in", 0x0L)
+ setattr(parser.values, "reflect_out", True)
+ setattr(parser.values, "xor_out", 0x0L)
+ elif mod == "x-25":
+ setattr(parser.values, "width", 16)
+ setattr(parser.values, "poly", 0x1021L)
+ setattr(parser.values, "reflect_in", True)
+ setattr(parser.values, "xor_in", 0xffffL)
+ setattr(parser.values, "reflect_out", True)
+ setattr(parser.values, "xor_out", 0xffffL)
+ elif mod == "xmodem":
+ setattr(parser.values, "width", 16)
+ setattr(parser.values, "poly", 0x8408L)
+ setattr(parser.values, "reflect_in", True)
+ setattr(parser.values, "xor_in", 0x0L)
+ setattr(parser.values, "reflect_out", True)
+ setattr(parser.values, "xor_out", 0x0L)
+ elif mod == "zmodem":
+ setattr(parser.values, "width", 16)
+ setattr(parser.values, "poly", 0x1021L)
+ setattr(parser.values, "reflect_in", False)
+ setattr(parser.values, "xor_in", 0x0L)
+ setattr(parser.values, "reflect_out", False)
+ setattr(parser.values, "xor_out", 0x0L)
+ elif mod == "crc-24":
+ setattr(parser.values, "width", 24)
+ setattr(parser.values, "poly", 0x864cfbL)
+ setattr(parser.values, "reflect_in", False)
+ setattr(parser.values, "xor_in", 0xb704ceL)
+ setattr(parser.values, "reflect_out", False)
+ setattr(parser.values, "xor_out", 0x0L)
+ elif mod == "crc-32":
+ setattr(parser.values, "width", 32)
+ setattr(parser.values, "poly", 0x4c11db7L)
+ setattr(parser.values, "reflect_in", True)
+ setattr(parser.values, "xor_in", 0xffffffffL)
+ setattr(parser.values, "reflect_out", True)
+ setattr(parser.values, "xor_out", 0xffffffffL)
+ elif mod == "crc-32c":
+ setattr(parser.values, "width", 32)
+ setattr(parser.values, "poly", 0x1edc6f41L)
+ setattr(parser.values, "reflect_in", True)
+ setattr(parser.values, "xor_in", 0xffffffffL)
+ setattr(parser.values, "reflect_out", True)
+ setattr(parser.values, "xor_out", 0xffffffffL)
+ elif mod == "posix":
+ setattr(parser.values, "width", 32)
+ setattr(parser.values, "poly", 0x4c11db7L)
+ setattr(parser.values, "reflect_in", False)
+ setattr(parser.values, "xor_in", 0x0L)
+ setattr(parser.values, "reflect_out", False)
+ setattr(parser.values, "xor_out", 0xffffffffL)
+ elif mod == "jam":
+ setattr(parser.values, "width", 32)
+ setattr(parser.values, "poly", 0x4c11db7L)
+ setattr(parser.values, "reflect_in", True)
+ setattr(parser.values, "xor_in", 0xffffffffL)
+ setattr(parser.values, "reflect_out", True)
+ setattr(parser.values, "xor_out", 0x0L)
+ elif mod == "xfer":
+ setattr(parser.values, "width", 32)
+ setattr(parser.values, "poly", 0x000000afL)
+ setattr(parser.values, "reflect_in", False)
+ setattr(parser.values, "xor_in", 0x0L)
+ setattr(parser.values, "reflect_out", False)
+ setattr(parser.values, "xor_out", 0x0L)
+ elif mod == "crc-64":
+ setattr(parser.values, "width", 64)
+ setattr(parser.values, "poly", 0x000000000000001bL)
+ setattr(parser.values, "reflect_in", True)
+ setattr(parser.values, "xor_in", 0x0L)
+ setattr(parser.values, "reflect_out", True)
+ setattr(parser.values, "xor_out", 0x0L)
+ else:
+ raise OptionValueError("Error: unsupported model %s" % (value))
+ sys.exit(1)
+
+# Class Options
+###############################################################################
+class Options(object):
+ """
+ The options parsing and validationg class
+ """
+
+ """
+ Bitmap of the algorithms
+ """
+ Algo_None = 0x00
+ Algo_Bit_by_Bit = 0x01
+ Algo_Bit_by_Bit_Fast = 0x02
+ Algo_Table_Driven = 0x04
+
+ # Class constructor
+ ###############################################################################
+ def __init__(self, version):
+ self.ProgramName = "pycrc"
+ self.Version = version
+ self.VersionStr = "%s v%s" % (self.ProgramName, self.Version)
+ self.WebAddress = "http://www.tty1.net/pycrc/"
+ self.Width = None
+ self.Poly = None
+ self.ReflectIn = None
+ self.XorIn = None
+ self.ReflectOut = None
+ self.XorOut = None
+ self.TableIdxWidth = 8
+ self.TableWidth = 1 << self.TableIdxWidth
+ self.Verbose = False
+ self.CheckString = "123456789"
+
+ self.Algorithm = self.Algo_None
+ self.SymbolPrefix = "crc_"
+ self.OutputFile = None
+ self.Action = "check_string"
+ self.CStd = None
+
+
+ #CRC24 :
+ self.Width=24
+ self.Poly=0x864cfbL
+ self.ReflectIn=False
+ self.XorIn=0xb704ceL
+ self.ReflectOut=False
+ self.XorOut=0x0L
+ self.parse()
+
+
+
+
+ # function parse
+ ###############################################################################
+ def parse(self, argv = None):
+ """
+ Parses and validates the options given as arguments
+ """
+ usage = """\
+%prog [OPTIONS]
+
+To generate the checksum of a string:
+ %prog [model] --check-string "123456789"
+
+To generate the checksum of a file:
+ %prog [model] --check-file filename
+
+To generate the c-source and write it to filename:
+ %prog [model] --generate c -o filename
+
+The model can be defined by the --model switch or by specifying each of the
+following parameters:
+ --width --poly --reflect-in --xor-in --reflect-out --xor-out"""
+
+ parser = OptionParser(option_class=MyOption, usage=usage, version=self.VersionStr)
+ parser.add_option("-v", "--verbose",
+ action="store_true", dest="verbose", default=False,
+ help="print information about the model")
+ parser.add_option("--check-string",
+ action="store", type="string", dest="check_string",
+ help="calculate the checksum of the given string ('123456789' default)", metavar="STRING")
+ parser.add_option("--check-file",
+ action="store", type="string", dest="check_file",
+ help="calculate the checksum of the given file", metavar="FILE")
+ parser.add_option("--generate",
+ action="store", type="string", dest="generate", default=None,
+ help="choose which type of code to generate from {c, h, c-main, table}", metavar="CODE")
+ parser.add_option("--std",
+ action="store", type="string", dest="c_std", default="C99",
+ help="C standard style of the generated code from {C89, ANSI, C99}", metavar="STD")
+ parser.add_option("--algorithm",
+ action="store", type="string", dest="algorithm", default="all",
+ help="choose an algorithm from {bit-by-bit, bit-by-bit-fast, table-driven, all}", metavar="ALGO")
+ parser.add_option("--model",
+ action="callback", callback=model_cb, type="string", dest="model", default=None,
+ help="choose a parameter set from {crc-5, crc-8, crc-15, crc-16, crc-16-usb, ccitt, kermit, x-25, xmodem, zmodem, crc-24, crc-32, crc-32c, posix, jam, xfer, crc-64}", metavar="MODEL")
+ parser.add_option("--width",
+ action="store", type="hex", dest="width",
+ help="use WIDTH bits in the polynom", metavar="WIDTH")
+ parser.add_option("--poly",
+ action="store", type="hex", dest="poly",
+ help="use HEX as Polynom", metavar="HEX")
+ parser.add_option("--reflect-in",
+ action="store", type="bool", dest="reflect_in",
+ help="reflect input bytes", metavar="BOOL")
+ parser.add_option("--xor-in",
+ action="store", type="hex", dest="xor_in",
+ help="use HEX as initial value", metavar="HEX")
+ parser.add_option("--reflect-out",
+ action="store", type="bool", dest="reflect_out",
+ help="reflect output bytes", metavar="BOOL")
+ parser.add_option("--xor-out",
+ action="store", type="hex", dest="xor_out",
+ help="xor the final crc value with HEX", metavar="HEX")
+ parser.add_option("--table-idx-width",
+ action="store", type="int", dest="table_idx_width",
+ help="use WIDTH bits to index the crc table; WIDTH one of {1, 2, 4, 8}", metavar="WIDTH")
+ parser.add_option("--symbol-prefix",
+ action="store", type="string", dest="symbol_prefix",
+ help="when generating source code, use STRING as prefix to the generated symbols", metavar="STRING")
+ parser.add_option("-o", "--output",
+ action="store", type="string", dest="output_file",
+ help="write the generated code to file instead to stdout", metavar="FILE")
+
+ (options, args) = parser.parse_args()
+
+ undefined_params = []
+ if options.width != None:
+ self.Width = options.width
+ else:
+ undefined_params.append("--width")
+ if options.poly != None:
+ self.Poly = options.poly
+ else:
+ undefined_params.append("--poly")
+ if options.reflect_in != None:
+ self.ReflectIn = options.reflect_in
+ else:
+ undefined_params.append("--reflect-in")
+ if options.xor_in != None:
+ self.XorIn = options.xor_in
+ else:
+ undefined_params.append("--xor-in")
+ if options.reflect_out != None:
+ self.ReflectOut = options.reflect_out
+ else:
+ undefined_params.append("--reflect-out")
+ if options.xor_out != None:
+ self.XorOut = options.xor_out
+ else:
+ undefined_params.append("--xor-out")
+ if options.table_idx_width != None:
+ if options.table_idx_width == 1 or \
+ options.table_idx_width == 2 or \
+ options.table_idx_width == 4 or \
+ options.table_idx_width == 8:
+ self.TableIdxWidth = options.table_idx_width
+ self.TableWidth = 1 << options.table_idx_width
+ else:
+ sys.stderr.write("Error: unsupported table-idx-width %d\n" % options.table_idx_width)
+ sys.exit(1)
+
+ if self.Width != None:
+ if self.Width <= 0:
+ sys.stderr.write("Error: Width must be strictly positive\n")
+ sys.exit(1)
+ self.MSB_Mask = 0x1 << (self.Width - 1)
+ self.Mask = ((self.MSB_Mask - 1) << 1) | 1
+ if self.Poly != None:
+ self.Poly = self.Poly & self.Mask
+ if self.XorIn != None:
+ self.XorIn = self.XorIn & self.Mask
+ if self.XorOut != None:
+ self.XorOut = self.XorOut & self.Mask
+ else:
+ self.MSB_Mask = None
+ self.Mask = None
+
+ if self.Width == None or \
+ self.Poly == None or \
+ self.ReflectIn == None or \
+ self.XorIn == None or \
+ self.ReflectOut == None or \
+ self.XorOut == None:
+ self.UndefinedCrcParameters = True
+ else:
+ self.UndefinedCrcParameters = False
+
+ if options.algorithm != None:
+ alg = options.algorithm.lower()
+ if alg == "bit-by-bit" or alg == "all":
+ self.Algorithm |= self.Algo_Bit_by_Bit
+ if alg == "bit-by-bit-fast" or alg == "all":
+ self.Algorithm |= self.Algo_Bit_by_Bit_Fast
+ if alg == "table-driven" or alg == "all":
+ self.Algorithm |= self.Algo_Table_Driven
+ if self.Algorithm == 0:
+ sys.stderr.write("Error: unknown algorithm %s\n" % options.algorithm)
+ sys.exit(1)
+ if self.Width != None and (self.Width % 8) != 0:
+ if options.algorithm == "table-driven":
+ sys.stderr.write("Error: width parameter is not aligned to byte boundaries; algorithm %s not applicable\n" % options.algorithm)
+ sys.exit(1)
+ else:
+ self.Algorithm &= ~self.Algo_Table_Driven
+ if self.Width != None and self.Width < 8:
+ if options.algorithm == "table-driven":
+ sys.stderr.write("Error: width < 8, algorithm %s not applicable\n" % options.algorithm)
+ sys.exit(1)
+ else:
+ self.Algorithm &= ~(self.Algo_Table_Driven)
+
+ if options.c_std != None:
+ std = options.c_std.upper()
+ if std == "ANSI" or std == "C89":
+ self.CStd = "C89"
+ elif std == "C99":
+ self.CStd = std
+ else:
+ sys.stderr.write("Error: unknown C standard %s\n" % options.c_std)
+ sys.exit(1)
+ if options.symbol_prefix != None:
+ self.SymbolPrefix = options.symbol_prefix
+ if options.output_file != None:
+ self.OutputFile = options.output_file
+ op_count = 0
+ if options.check_string != None:
+ self.Action = "check_string"
+ self.CheckString = options.check_string
+ op_count += 1
+ if options.check_file != None:
+ self.Action = "check_file"
+ self.CheckFile = options.check_file
+ op_count += 1
+ if options.generate != None:
+ arg = options.generate.lower()
+ if arg != 'c' and arg != 'h' and arg != "c-main" and arg != "table":
+ sys.stderr.write("Error: unknown operation %s\n" % options.generate)
+ sys.exit(1)
+ self.Action = "generate_" + arg
+ op_count += 1
+ if self.Action == "generate_table":
+ if self.Algorithm & self.Algo_Table_Driven == 0:
+ sys.stderr.write("Error: the --generate table option is incompatible with the --algorithm option\n")
+ sys.exit(1)
+ self.Algorithm = self.Algo_Table_Driven
+ elif self.Algorithm != self.Algo_Bit_by_Bit and self.Algorithm != self.Algo_Bit_by_Bit_Fast and self.Algorithm != self.Algo_Table_Driven:
+ sys.stderr.write("Error: select an algorithm to be used in the generated file\n")
+ sys.exit(1)
+ if op_count == 0:
+ self.Action = "check_string"
+ if op_count > 1:
+ sys.stderr.write("Error: too many actions scecified\n")
+ sys.exit(1)
+
+ if self.UndefinedCrcParameters and (self.Action == "check_string" or self.Action == "check_file" or self.Action == "generate_table"):
+ sys.stderr.write("Error: undefined parameters: Add %s or use --model\n" % ", ".join(undefined_params))
+ sys.exit(1)
+ self.Verbose = options.verbose
+
diff --git a/maximus/python/lib/crc24_algorithms.py b/maximus/python/lib/crc24_algorithms.py
new file mode 100644
index 0000000000..4015b726d8
--- /dev/null
+++ b/maximus/python/lib/crc24_algorithms.py
@@ -0,0 +1,225 @@
+# -*- coding: Latin-1 -*-
+
+# pycrc -- parametrisable CRC calculation utility and C source code generator
+#
+# Copyright (c) 2006-2007 Thomas Pircher <tehpeh@gmx.net>
+#
+# Permission is hereby granted, free of charge, to any person obtaining a copy
+# of this software and associated documentation files (the "Software"), to deal
+# in the Software without restriction, including without limitation the rights
+# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+# copies of the Software, and to permit persons to whom the Software is
+# furnished to do so, subject to the following conditions:
+#
+# The above copyright notice and this permission notice shall be included in
+# all copies or substantial portions of the Software.
+#
+# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+# THE SOFTWARE.
+
+
+"""
+CRC routines for pycrc.
+If you want to study the Python implementation of the CRC routines, then you are
+looking at the right place.
+
+
+Examples
+========
+
+This is an example use of the different algorithms:
+
+>>> from crc_algorithms import Crc
+>>>
+>>> class Options(object):
+>>> Width = 16
+>>> Poly = 0x8005
+>>> ReflectIn = True
+>>> XorIn = 0x0000
+>>> ReflectOut = True
+>>> XorOut = 0x0000
+>>>
+>>> opt = Options()
+>>> crc = Crc(opt)
+>>> print "0x%x" % crc.bit_by_bit("123456789")
+>>> print "0x%x" % crc.bit_by_bit_fast("123456789")
+>>> print "0x%x" % crc.table_driven("123456789")
+
+This file is part of pycrc.
+"""
+
+# Class Crc
+###############################################################################
+class Crc(object):
+ """
+ A base class for CRC routines.
+ """
+
+ # constructor
+ ###############################################################################
+ def __init__(self, opt):
+ """The Crc constructor.
+
+ The opt parameter is an object containing the following members:
+ Width
+ Poly
+ ReflectIn
+ XorIn
+ ReflectOut
+ XorOut
+ """
+ self.Width = opt.Width
+ self.Poly = opt.Poly
+ self.ReflectIn = opt.ReflectIn
+ self.XorIn = opt.XorIn
+ self.ReflectOut = opt.ReflectOut
+ self.XorOut = opt.XorOut
+
+ self.MSB_Mask = 0x1 << (opt.Width - 1)
+ self.Mask = ((opt.MSB_Mask - 1) << 1) | 1
+ if opt.TableIdxWidth != None:
+ self.TableIdxWidth = opt.TableIdxWidth
+ self.TableWidth = 1 << opt.TableIdxWidth
+ else:
+ self.TableIdxWidth = 8
+ self.TableWidth = 1 << self.TableIdxWidth
+
+ # function reflect
+ ###############################################################################
+ def reflect(self, data, width):
+ """
+ reflects a data word, i.e. reverts the bit order
+ """
+ x = 0
+ for i in range(width):
+ x = x | (((data >> (width - i -1)) & 1) << i)
+ return x
+
+ # function handle_bit
+ ###############################################################################
+ def __handle_bit(self, register, new_bit):
+ """
+ This function is part of the bit_by_bit algorithm.
+ It function takes one bit from the augmented message as argument and returns the new crc value
+ """
+ register_msb = register & self.MSB_Mask
+ register = (register << 1) & self.Mask
+ if new_bit != 0:
+ register = register | 1
+ if register_msb != 0:
+ register = register ^ self.Poly
+ return register & self.Mask
+
+ # function bit_by_bit
+ ###############################################################################
+ def bit_by_bit(self, str):
+ """
+ Classic simple and slow CRC implementation.
+ This function iterates bit by bit over the augmented input message and returns the calculated CRC value at the end
+ """
+ register = self.XorIn
+ for j in range(self.Width):
+ bit = register & 1
+ if bit != 0:
+ register = ((register ^ self.Poly) >> 1) | self.MSB_Mask
+ else:
+ register = register >> 1
+ register &= self.Mask
+
+ for i in range(len(str)):
+ octet = ord(str[i])
+ if self.ReflectIn:
+ octet = self.reflect(octet, 8)
+ for j in range(8):
+ new_bit = octet & (0x80 >> j)
+ register = self.__handle_bit(register, new_bit)
+ for j in range(self.Width):
+ register = self.__handle_bit(register, 0)
+
+ if self.ReflectOut:
+ register = self.reflect(register, self.Width)
+ register = register ^ self.XorOut
+ return register
+
+ # function bit_by_bit_fast
+ ###############################################################################
+ def bit_by_bit_fast(self, str):
+ """
+ This is a slightly modified version of the bit_by_bit algorithm: it does not need to loop over the augmented bit,
+ i.e. the Width 0-bits wich are appended to the input message in the bit_by_bit algorithm.
+ """
+ register = self.XorIn
+
+ for i in range(len(str)):
+ octet = ord(str[i])
+ if self.ReflectIn:
+ octet = self.reflect(octet, 8)
+ for j in range(8):
+ bit = register & self.MSB_Mask
+ register <<= 1
+ if octet & (0x80 >> j):
+ bit ^= self.MSB_Mask
+ if bit:
+ register ^= self.Poly
+ register &= self.Mask
+ if self.ReflectOut:
+ register = self.reflect(register, self.Width)
+ register = register ^ self.XorOut
+ return register
+
+ # function gen_table
+ ###############################################################################
+ def gen_table(self):
+ """
+ This function generates the CRC table used for the table_driven CRC algorithm.
+ The Python version cannot handle tables of a different size rather than 8.
+ See the generated C code for tables with different sizes instead.
+ """
+ tbl = {}
+ for i in range(1 << self.TableIdxWidth):
+ register = i
+ if self.ReflectIn:
+ register = self.reflect(register, self.TableIdxWidth)
+ register = register << (self.Width - self.TableIdxWidth)
+ for j in range(self.TableIdxWidth):
+ if register & self.MSB_Mask != 0:
+ register = (register << 1) ^ self.Poly
+ else:
+ register = (register << 1)
+ if self.ReflectIn:
+ register = self.reflect(register, self.Width)
+ tbl[i] = register & self.Mask
+ return tbl
+
+ # function table_driven
+ ###############################################################################
+ def table_driven(self, str):
+ """
+ The Standard table_driven CRC algorithm.
+ """
+ tbl = self.gen_table()
+
+ if not self.ReflectIn:
+ register = self.XorIn
+ for i in range(len(str)):
+ octet = ord(str[i])
+ tblidx = ((register >> (self.Width - 8)) ^ octet) & 0xff
+ register = ((register << 8) ^ tbl[tblidx]) & self.Mask
+ else:
+ register = self.reflect(self.XorIn, self.Width)
+ for i in range(len(str)):
+ octet = ord(str[i])
+ tblidx = (register ^ octet) & 0xff
+ register = ((register >> 8) ^ tbl[tblidx]) & self.Mask
+ register = self.reflect(register, self.Width)
+
+ if self.ReflectOut:
+ register = self.reflect(register, self.Width)
+ register = register ^ self.XorOut
+ return register
+
diff --git a/maximus/python/lib/crc24_lexer.py b/maximus/python/lib/crc24_lexer.py
new file mode 100644
index 0000000000..54315ffe3e
--- /dev/null
+++ b/maximus/python/lib/crc24_lexer.py
@@ -0,0 +1,240 @@
+# -*- coding: Latin-1 -*-
+
+# pycrc -- parametrisable CRC calculation utility and C source code generator
+#
+# Copyright (c) 2006-2007 Thomas Pircher <tehpeh@gmx.net>
+#
+# Permission is hereby granted, free of charge, to any person obtaining a copy
+# of this software and associated documentation files (the "Software"), to deal
+# in the Software without restriction, including without limitation the rights
+# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+# copies of the Software, and to permit persons to whom the Software is
+# furnished to do so, subject to the following conditions:
+#
+# The above copyright notice and this permission notice shall be included in
+# all copies or substantial portions of the Software.
+#
+# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+# THE SOFTWARE.
+
+
+"""
+Lexical analyzer for pycrc.
+use as follows:
+
+ from crc_opt import Options
+ from crc_symtable import SymbolTable
+ from crc_lexer import LangLexer
+
+ lex = LangLexer()
+ lex.set_str(str)
+
+ tok = self.lex.peek()
+ print tok
+ print self.lex.text
+ self.lex.advance()
+
+This file is part of pycrc.
+"""
+
+from crc24_symtable import SymbolTable
+import sys
+import re
+
+
+# Class Lexer
+###############################################################################
+class Lexer(object):
+ """
+ A lexical analyser
+ """
+
+ tok_unknown = 0
+ tok_EOF = 1
+
+ # constructor
+ ###############################################################################
+ def __init__(self, str = ""):
+ self.set_str(str)
+
+ # set_str
+ ###############################################################################
+ def set_str(self, str):
+ self.str = str
+ self.text = ""
+ self.text_len = 0
+ self.tok = self.tok_unknown
+
+ # peek
+ ###############################################################################
+ def peek(self):
+ return self.tok_unknown
+
+ # advance
+ ###############################################################################
+ def advance(self, skip_nl = False):
+ skip_len = self.text_len
+ if skip_nl and (len(self.str) > skip_len) and (self.str[skip_len] == "\n"):
+ skip_len = skip_len + 1 # FIXME: check on Windoze if I can do simply a +1 to skip the line ending...
+ self.str = self.str[skip_len:]
+
+ # prepend
+ ###############################################################################
+ def prepend(self, str):
+ self.text = ""
+ self.text_len = 0
+ self.str = str + self.str
+
+
+# Class LangLexer
+###############################################################################
+class LangLexer(Lexer):
+ """
+ A lexical analyser
+ """
+
+ tok_text = 12
+ tok_control = 13
+ tok_block_start = 14
+ tok_block_end = 15
+
+ # constructor
+ ###############################################################################
+ def __init__(self, str = ""):
+ super(LangLexer, self).__init__(str)
+ self.re_control = re.compile("\{%([^%}]*)%\}")
+
+ # peek
+ ###############################################################################
+ def peek(self):
+ if len(self.str) == 0:
+ self.text = ""
+ return self.tok_EOF
+ m = self.re_control.search(self.str)
+ if m != None and m.start() == 0:
+ self.text = m.group(1)
+ self.text_len = m.end()
+ return self.tok_control
+
+ if m == None:
+ text_end = len(self.str)
+ else:
+ text_end = m.start()
+
+ i = self.str.find("{:")
+ if i >= 0:
+ if i == 0:
+ self.text = self.str[:2]
+ self.text_len = 2
+ return self.tok_block_start
+ if i < text_end:
+ text_end = i
+ i = self.str.find(":}")
+ if i >= 0:
+ if i == 0:
+ self.text = self.str[:2]
+ self.text_len = 2
+ return self.tok_block_end
+ if i < text_end:
+ text_end = i
+
+ self.text = self.str[:text_end]
+ self.text_len = text_end
+ return self.tok_text
+
+
+# Class ExpLexer
+###############################################################################
+class ExpLexer(Lexer):
+ """
+ A lexical analyser
+ """
+
+ tok_id = 12
+ tok_op = 13
+ tok_str = 14
+ tok_and = 15
+ tok_or = 16
+ tok_par_open = 17
+ tok_par_close = 18
+
+ # constructor
+ ###############################################################################
+ def __init__(self, str = ""):
+ super(ExpLexer, self).__init__(str)
+# self.re_id = re.compile("\{%([^%}]+)%\}")
+ self.re_id = re.compile("\\$([a-zA-Z][a-zA-Z0-9_-]*)")
+ self.re_op = re.compile("<=|<|==|!=|>=|>")
+# self.re_str = re.compile("\"([^\"]+)\"")
+# self.re_str = re.compile("([a-zA-Z0-9_-]+)|\"([a-zA-Z0-9_-]+)\"")
+ self.re_str = re.compile("\"?([a-zA-Z0-9_-]+)\"?")
+ self.re_is_int = re.compile("^[-+]?[0-9]+$")
+ self.re_is_hex = re.compile("^(0[xX])?[0-9a-fA-F]+$")
+
+ # peek
+ ###############################################################################
+ def peek(self):
+ self.str = self.str.strip()
+ if len(self.str) == 0:
+ self.text = ""
+ return self.tok_EOF
+
+ m = self.re_id.match(self.str)
+ if m != None:
+ self.text = m.group(1)
+ self.text_len = m.end()
+ return self.tok_id
+
+ m = self.re_op.match(self.str)
+ if m != None:
+ self.text = m.string[:m.end()]
+ self.text_len = m.end()
+ return self.tok_op
+
+ if self.str[:4] == "and ":
+ self.text = "and"
+ self.text_len = len(self.text)
+ return self.tok_and
+
+ if self.str[:3] == "or ":
+ self.text = "or"
+ self.text_len = len(self.text)
+ return self.tok_or
+
+ m = self.re_str.match(self.str)
+ if m != None:
+ self.text = m.group(1)
+ self.text_len = m.end()
+ return self.tok_str
+
+ if self.str[0] == "(" or self.str[0] == ")":
+ self.text = self.str[0]
+ self.text_len = len(self.text)
+ if self.str[0] == "(":
+ return self.tok_par_open
+ else:
+ return self.tok_par_close
+
+ self.text = ""
+ return self.tok_unknown
+
+ # is_int
+ ###############################################################################
+ def is_int(self, str):
+ try:
+ return self.re_is_int.search(str)
+ except TypeError:
+ return False
+
+ # is_hex
+ ###############################################################################
+ def is_hex(self, str):
+ try:
+ return self.re_is_hex.match(str)
+ except TypeError:
+ return False
diff --git a/maximus/python/lib/crc24_parser.py b/maximus/python/lib/crc24_parser.py
new file mode 100644
index 0000000000..45c0b92773
--- /dev/null
+++ b/maximus/python/lib/crc24_parser.py
@@ -0,0 +1,441 @@
+# -*- coding: Latin-1 -*-
+
+# pycrc -- parametrisable CRC calculation utility and C source code generator
+#
+# Copyright (c) 2006-2007 Thomas Pircher <tehpeh@gmx.net>
+#
+# Permission is hereby granted, free of charge, to any person obtaining a copy
+# of this software and associated documentation files (the "Software"), to deal
+# in the Software without restriction, including without limitation the rights
+# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+# copies of the Software, and to permit persons to whom the Software is
+# furnished to do so, subject to the following conditions:
+#
+# The above copyright notice and this permission notice shall be included in
+# all copies or substantial portions of the Software.
+#
+# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+# THE SOFTWARE.
+
+
+"""
+Macro Language parser for pycrc.
+use as follows:
+
+ from crc_opt import Options
+ from crc_parser import MacroParser
+
+ opt = Options("0.6")
+ opt.parse(sys.argv)
+ mp = MacroParser(opt)
+ if mp.parse(out):
+ print mp.out_str
+
+
+This file is part of pycrc.
+"""
+
+from crc24_symtable import SymbolTable
+from crc24_lexer import LangLexer, ExpLexer
+import sys
+
+
+# Class ParseError
+###############################################################################
+class ParseError(Exception):
+ """
+ The exception class for the parser
+ """
+
+ # __init__
+ ###############################################################################
+ def __init__(self, reason):
+ self.reason = reason
+
+ # __str__
+ ###############################################################################
+ def __str__(self):
+ return self.reason
+
+
+# Class MacroParser
+###############################################################################
+class MacroParser(object):
+ """
+ The macro language parser and code generator class
+ """
+ opt = None
+ sym = None
+ lex = LangLexer()
+ explex = ExpLexer()
+
+ mPrintMask = 1
+ mDoPrint = 2
+ mEvalElse = 4
+
+ # constructor
+ ###############################################################################
+ def __init__(self, opt):
+ self.opt = opt
+ self.sym = SymbolTable(opt)
+
+ # parse
+ #
+ # the used grammar (more or less correctly) in Wirth Syntax Notation:
+ #
+ # DATA = { LITERAL | CONTROL } .
+ # CONTROL = IF | "{%" LITERAL "%}" .
+ # IF = "{%" "if" EXPRESSION "%}" "{:" { DATA } ":}"
+ # { "{%" "elif" EXPRESSION "%}" "{:" { DATA } ":}" }
+ # [ "{%" "else" "%}" "{:" { DATA } ":}" ]
+ # .
+ # STRING = """" LITERAL """" .
+ # ID = "{%" LITERAL "%}" .
+ # LITERAL = letter { letter } .
+ #
+ # EXPRESSION = TERM { "or" TERM } .
+ # TERM = FACTOR { "and" FACTOR } .
+ # FACTOR = ( EXPRESSION ) | TERMINAL OP TERMINAL .
+ # TERMINAL = ID | STRING | LITERAL .
+ # OP = "==" | ">" | "<" | "<=" | "=>" | "!=" .
+ #
+ ###############################################################################
+ def parse(self, str):
+ """
+ parse a string
+ """
+ self.lex.set_str(str)
+ self.out_str = ""
+ self.if_stack = [ self.mPrintMask | self.mDoPrint ]
+ return self.__parse_data()
+
+ # __parse_data
+ ###############################################################################
+ def __parse_data(self):
+ """
+ parse data
+ """
+ tok = self.lex.peek()
+ while tok != self.lex.tok_EOF:
+ if tok == self.lex.tok_text:
+ if (self.if_stack[0] & self.mDoPrint) == self.mDoPrint:
+ self.out_str += self.lex.text
+ self.lex.advance(skip_nl = False)
+ elif tok == self.lex.tok_control:
+ if not self.__parse_control(self.lex.text):
+ return False
+ elif tok == self.lex.tok_block_end:
+ return True
+ else:
+ sys.stderr.write("Error: wrong token %s\n" % self.lex.text)
+ return False
+ tok = self.lex.peek()
+ return True
+
+ # __parse_control
+ ###############################################################################
+ def __parse_control(self, str):
+ """
+ parse a control structure
+ """
+ tok = self.lex.peek()
+ if tok == self.lex.tok_control:
+ if self.lex.text.startswith("if "):
+ if not self.__parse_if(self.lex.text) or \
+ not self.__parse_block_start() or \
+ not self.__parse_data() or \
+ not self.__parse_block_end():
+ return False
+ tok = self.lex.peek()
+ while self.lex.text.startswith("elif "):
+ if not self.__parse_elif(self.lex.text) or \
+ not self.__parse_block_start() or \
+ not self.__parse_data() or \
+ not self.__parse_block_end():
+ return False
+ tok = self.lex.peek()
+ if self.lex.text == "else":
+ if not self.__parse_else(self.lex.text) or \
+ not self.__parse_block_start() or \
+ not self.__parse_data() or \
+ not self.__parse_block_end():
+ return False
+ self.if_stack.pop(0)
+ return True
+ elif self.lex.text == "else" or self.lex.text.startswith("elif "):
+ sys.stderr.write("unmatched %s clause\n" % self.lex.text[:4])
+ return False
+ else:
+ if not self.__parse_literal(self.lex.text):
+ return False
+ return True
+ sys.stderr.write("unknown token in control\n")
+ return False
+
+ # __parse_if
+ ###############################################################################
+ def __parse_if(self, str):
+ """
+ parse a if operation
+ """
+ exp = str[3:].strip()
+ try:
+ condition = self.__parse_expression(exp)
+ except ParseError:
+ sys.stderr.write("parsing expression %s failed\n" % str)
+ return False
+
+ stack_state = self.if_stack[0]
+ if (stack_state & self.mDoPrint) == self.mDoPrint:
+ if condition:
+ stack_state = self.mPrintMask | self.mDoPrint
+ else:
+ stack_state = self.mPrintMask | self.mEvalElse
+ else:
+ stack_state = 0
+ self.if_stack.insert(0, stack_state)
+ self.lex.advance(skip_nl = True)
+ return True
+
+ # __parse_elif
+ ###############################################################################
+ def __parse_elif(self, str):
+ """
+ parse a elif operation
+ """
+ stack_state = self.if_stack[0]
+ if (stack_state & (self.mPrintMask | self.mEvalElse)) == (self.mPrintMask | self.mEvalElse):
+ exp = str[5:].strip()
+ try:
+ condition = self.__parse_expression(exp)
+ except ParseError:
+ sys.stderr.write("parsing expression %s failed\n" % str)
+ return False
+
+ if condition:
+ stack_state = self.mPrintMask | self.mDoPrint
+ else:
+ stack_state = self.mPrintMask | self.mEvalElse
+ else:
+ stack_state = 0
+
+ self.if_stack[0] = stack_state
+ self.lex.advance(skip_nl = True)
+ return True
+
+ # __parse_else
+ ###############################################################################
+ def __parse_else(self, str):
+ """
+ parse a if operation
+ """
+ stack_state = self.if_stack[0]
+ if (stack_state & (self.mPrintMask | self.mEvalElse)) == (self.mPrintMask | self.mEvalElse):
+ stack_state = self.mPrintMask | self.mDoPrint
+ else:
+ stack_state = 0
+ self.if_stack[0] = stack_state
+ self.lex.advance(skip_nl = True)
+ return True
+
+ # __parse_block_start
+ ###############################################################################
+ def __parse_block_start(self):
+ """
+ parse a begin of a control block
+ """
+ tok = self.lex.peek()
+ if tok != self.lex.tok_block_start:
+ sys.stderr.write("begin block expected, at %s\n" % self.lex.text)
+ return False
+ self.lex.advance(skip_nl = True)
+ return True
+
+ # __parse_block_end
+ ###############################################################################
+ def __parse_block_end(self):
+ """
+ parse a end of a control block
+ """
+ tok = self.lex.peek()
+ if tok != self.lex.tok_block_end:
+ sys.stderr.write("end block expected, at %s\n" % self.lex.text)
+ return False
+ self.lex.advance(skip_nl = True)
+ return True
+
+ # __parse_literal
+ ###############################################################################
+ def __parse_literal(self, str):
+ """
+ parse a literal
+ """
+ try:
+ data = self.sym.getTerminal(str)
+ except LookupError:
+ sys.stderr.write("Error: unknown terminal %s\n" % self.lex.text)
+ return False
+ self.lex.advance(skip_nl = False)
+ if (self.if_stack[0] & self.mDoPrint) == self.mDoPrint:
+ self.lex.prepend(data)
+ return True
+
+ # __parse_expression
+ ###############################################################################
+ def __parse_expression(self, str):
+ """
+ parse an expression
+ """
+ self.explex.set_str(str)
+ try:
+ ret = self.__parse_exp_exp()
+ except ParseError:
+ raise ParseError("Exp parsing failed")
+ if self.explex.peek() != self.explex.tok_EOF:
+ raise ParseError("extra characters after expression");
+ return ret
+
+ # __parse_exp_exp
+ ###############################################################################
+ def __parse_exp_exp(self):
+ """
+ parse an expression
+ """
+ ret = False
+
+ while True:
+ ret = self.__parse_exp_term() or ret
+
+ tok = self.explex.peek()
+ if tok == self.explex.tok_EOF:
+ return ret
+ if tok != self.explex.tok_or:
+ print "expecting 'or' and not '%s'" % self.explex.text
+ raise ParseError("Unexpected token")
+ self.explex.advance(skip_nl = False)
+
+ return False
+
+ # __parse_exp_term
+ ###############################################################################
+ def __parse_exp_term(self):
+ """
+ parse a term
+ """
+ ret = True
+
+ while True:
+ ret = self.__parse_exp_factor() and ret
+ tok = self.explex.peek()
+
+ if tok != self.explex.tok_and:
+ return ret
+ self.explex.advance(skip_nl = False)
+
+ return False
+
+ # __parse_exp_factor
+ ###############################################################################
+ def __parse_exp_factor(self):
+ """
+ parse a term
+ """
+ ret = True
+
+ tok = self.explex.peek()
+
+ if tok == self.explex.tok_par_open:
+ self.explex.advance(skip_nl = False)
+ ret = self.__parse_exp_exp()
+ tok = self.explex.peek()
+ if tok != self.explex.tok_par_close:
+ print "missing ')' before '%s'" % self.explex.text
+ raise ParseError("missing ')' before '%s'" % self.explex.text)
+ self.explex.advance(skip_nl = False)
+ self.explex.peek()
+ return ret
+
+ val1_str = self.explex.text
+ val1 = self.__parse_exp_terminal()
+ tok = self.explex.peek()
+ if tok != self.explex.tok_op:
+ print "operator expected and not '%s' before '%s'" % (self.explex.text, self.explex.str)
+ raise ParseError("operator expected and not '%s'" % self.explex.text)
+ op_text = self.explex.text
+ self.explex.advance(skip_nl = False)
+ self.explex.peek()
+ val2_str = self.explex.text
+ val2 = self.__parse_exp_terminal()
+ if val1 == None or val2 == None:
+ if op_text == "==":
+ if (val1 == None and val2 == "Undefined") or (val1 == "Undefined" and val2 == None):
+ return True
+ elif op_text == "!=":
+ if (val1 == None and val2 == "Undefined") or (val1 == "Undefined" and val2 == None):
+ return False
+ if val1 == None:
+ text = val1_str
+ else:
+ text = val2_str
+ print "undefined parameter '%s'" % text
+ raise ParseError("undefined parameter")
+
+ val1_num = val2_num = None
+ if val1 != None:
+ if self.explex.is_int(val1):
+ val1_num = int(val1)
+ if self.explex.is_hex(val1):
+ val1_num = int(val1, 16)
+ if val2 != None:
+ if self.explex.is_int(val2):
+ val2_num = int(val2)
+ if self.explex.is_hex(val2):
+ val2_num = int(val2, 16)
+
+ if val1_num != None and val2_num != None:
+ val1 = val1_num
+ val2 = val2_num
+
+ if op_text == "<":
+ return val1 < val2
+ if op_text == "<=":
+ return val1 <= val2
+ if op_text == "==":
+ return val1 == val2
+ if op_text == "!=":
+ return val1 != val2
+ if op_text == ">=":
+ return val1 >= val2
+ if op_text == ">":
+ return val1 > val2
+ else:
+ print "unknown operator '%s'" % op_text
+ raise ParseError("unknown operator")
+
+ # __parse_exp_terminal
+ ###############################################################################
+ def __parse_exp_terminal(self):
+ """
+ parse a terminal
+ """
+ tok = self.explex.peek()
+ if tok == self.explex.tok_id:
+ if self.explex.text == "Undefined":
+ ret = "Undefined"
+ else:
+ try:
+ ret = self.sym.getTerminal(self.explex.text)
+ except LookupError:
+ ret = None
+ elif tok == self.explex.tok_str:
+ ret = self.explex.text
+ else:
+ print "unexpected terminal '%s' before '%s'" % (self.explex.text, self.explex.str)
+ raise ParseError("unexpected terminal '%s'" % self.explex.text)
+ self.explex.advance(skip_nl = False)
+ return ret
diff --git a/maximus/python/lib/crc24_symtable.py b/maximus/python/lib/crc24_symtable.py
new file mode 100644
index 0000000000..966fecb7b3
--- /dev/null
+++ b/maximus/python/lib/crc24_symtable.py
@@ -0,0 +1,1232 @@
+# -*- coding: Latin-1 -*-
+
+# pycrc -- parametrisable CRC calculation utility and C source code generator
+#
+# Copyright (c) 2006-2007 Thomas Pircher <tehpeh@gmx.net>
+#
+# Permission is hereby granted, free of charge, to any person obtaining a copy
+# of this software and associated documentation files (the "Software"), to deal
+# in the Software without restriction, including without limitation the rights
+# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+# copies of the Software, and to permit persons to whom the Software is
+# furnished to do so, subject to the following conditions:
+#
+# The above copyright notice and this permission notice shall be included in
+# all copies or substantial portions of the Software.
+#
+# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+# THE SOFTWARE.
+
+
+"""
+Symbol table for pycrc
+use as follows:
+
+ from crc_opt import Options
+ from crc_symtable import SymbolTable
+
+ opt = Options("0.6")
+ sym = SymbolTable(opt)
+
+ str = " .... "
+ terminal = sym.getTerminal(str)
+
+This file is part of pycrc.
+"""
+
+from crc24_algorithms import Crc
+import time
+import os
+
+
+# Class SymbolTable
+###############################################################################
+class SymbolTable:
+ """
+ The symbol table class
+ """
+ opt = None
+ table = {}
+
+ # __init__
+ ###############################################################################
+ def __init__(self, opt):
+ """
+ The class constructor
+ """
+ self.opt = opt
+ self.table["datetime"] = time.asctime()
+ self.table["program_version"] = self.opt.VersionStr
+ self.table["program_url"] = self.opt.WebAddress
+ if self.opt.OutputFile == None:
+ self.table["filename"] = "stdout"
+ else:
+ self.table["filename"] = self.opt.OutputFile
+
+ if self.opt.OutputFile == None:
+ self.table["header_filename"] = "stdout.h"
+ elif self.opt.OutputFile[-2:] == ".c":
+ self.table["header_filename"] = self.opt.OutputFile[0:-1] + "h"
+ else:
+ self.table["header_filename"] = self.opt.OutputFile + ".h"
+
+ self.table["crc_width"] = self.__pretty_str(self.opt.Width)
+ self.table["crc_poly"] = self.__pretty_hex(self.opt.Poly, self.opt.Width)
+ self.table["crc_reflect_in"] = self.__pretty_bool(self.opt.ReflectIn)
+ self.table["crc_xor_in"] = self.__pretty_hex(self.opt.XorIn, self.opt.Width)
+ self.table["crc_reflect_out"] = self.__pretty_bool(self.opt.ReflectOut)
+ self.table["crc_xor_out"] = self.__pretty_hex(self.opt.XorOut, self.opt.Width)
+ self.table["crc_table_idx_width"] = str(self.opt.TableIdxWidth)
+ self.table["crc_table_width"] = str(1 << self.opt.TableIdxWidth)
+ self.table["crc_table_mask"] = self.__pretty_hex(self.opt.TableWidth - 1, 8)
+ self.table["crc_mask"] = self.__pretty_hex(self.opt.Mask, self.opt.Width)
+ self.table["crc_msb_mask"] = self.__pretty_hex(self.opt.MSB_Mask, self.opt.Width)
+
+ self.table["cfg_width"] = "{%if $crc_width != Undefined%}{:{%crc_width%}:}{%else%}{:cfg->width:}"
+ self.table["cfg_poly"] = "{%if $crc_poly != Undefined%}{:{%crc_poly%}:}{%else%}{:cfg->poly:}"
+ self.table["cfg_reflect_in"] = "{%if $crc_reflect_in != Undefined%}{:{%crc_reflect_in%}:}{%else%}{:cfg->reflect_in:}"
+ self.table["cfg_xor_in"] = "{%if $crc_xor_in != Undefined%}{:{%crc_xor_in%}:}{%else%}{:cfg->xor_in:}"
+ self.table["cfg_reflect_out"] = "{%if $crc_reflect_out != Undefined%}{:{%crc_reflect_out%}:}{%else%}{:cfg->reflect_out:}"
+ self.table["cfg_xor_out"] = "{%if $crc_xor_out != Undefined%}{:{%crc_xor_out%}:}{%else%}{:cfg->xor_out:}"
+ self.table["cfg_table_idx_width"] = "{%if $crc_table_idx_width != Undefined%}{:{%crc_table_idx_width%}:}{%else%}{:cfg->table_idx_width:}"
+ self.table["cfg_table_width"] = "{%if $crc_table_width != Undefined%}{:{%crc_table_width%}:}{%else%}{:cfg->table_width:}"
+ self.table["cfg_mask"] = "{%if $crc_mask != Undefined%}{:{%crc_mask%}:}{%else%}{:cfg->crc_mask:}"
+ self.table["cfg_msb_mask"] = "{%if $crc_msb_mask != Undefined%}{:{%crc_msb_mask%}:}{%else%}{:cfg->msb_mask:}"
+
+ self.table["undefined_parameters"] = self.__pretty_bool(self.opt.UndefinedCrcParameters)
+ self.table["use_cfg_t"] = self.__pretty_bool(self.opt.UndefinedCrcParameters)
+ self.table["c_std"] = self.opt.CStd
+ self.table["c_bool"] = "{%if $c_std == C89%}{:int:}{%else%}{:bool:}"
+ self.table["c_true"] = "{%if $c_std == C89%}{:1:}{%else%}{:true:}"
+ self.table["c_false"] = "{%if $c_std == C89%}{:0:}{%else%}{:false:}"
+
+ self.table["underlying_crc_t"] = self.__get_underlying_crc_t()
+
+ self.table["crc_t"] = self.opt.SymbolPrefix + "t"
+ self.table["cfg_t"] = self.opt.SymbolPrefix + "cfg_t"
+ self.table["crc_reflect_function"] = self.opt.SymbolPrefix + "reflect"
+ self.table["crc_table_gen_function"] = self.opt.SymbolPrefix + "table_gen"
+ self.table["crc_init_function"] = self.opt.SymbolPrefix + "init"
+ self.table["crc_update_function"] = self.opt.SymbolPrefix + "update"
+ self.table["crc_finalize_function"] = self.opt.SymbolPrefix + "finalize"
+
+
+ # getTerminal
+ ###############################################################################
+ def getTerminal(self, id):
+ """
+ return the expanded terminal, if it exists or None otherwise
+ """
+
+ if id != None:
+ if id == "":
+ return ""
+ if self.table.has_key(id):
+ return self.table[id]
+ key = self.__getTerminal(id)
+ if key != None:
+ self.table[id] = key
+ return key
+ raise LookupError
+
+ # __getTerminal
+ ###############################################################################
+ def __getTerminal(self, id):
+ """
+ return the expanded terminal, if it exists or None otherwise
+ """
+ if id == "constant_crc_init":
+ if self.__get_init_value() == None:
+ return self.__pretty_bool(False)
+ else:
+ return self.__pretty_bool(True)
+
+ elif id == "inline_crc_finalize":
+ if (self.opt.Algorithm == self.opt.Algo_Bit_by_Bit_Fast or self.opt.Algorithm == self.opt.Algo_Table_Driven) and \
+ (self.opt.Width != None and self.opt.ReflectIn != None and self.opt.ReflectOut != None and self.opt.XorOut != None):
+ return self.__pretty_bool(True)
+ else:
+ return self.__pretty_bool(False)
+
+ elif id == "simple_crc_finalize_def":
+ if self.opt.Algorithm != self.opt.Algo_Bit_by_Bit and (self.opt.Width != None and self.opt.ReflectIn != None and self.opt.ReflectOut != None and self.opt.XorOut != None) \
+ or self.opt.Algorithm == self.opt.Algo_Bit_by_Bit and \
+ (self.opt.Width != None and self.opt.ReflectOut != None and self.opt.XorOut != None and self.opt.Poly != None):
+ return self.__pretty_bool(True)
+ else:
+ return self.__pretty_bool(False)
+
+ elif id == "use_reflect_func":
+ if self.opt.ReflectOut == False and self.opt.ReflectIn == False:
+ return self.__pretty_bool(False)
+ else:
+ return self.__pretty_bool(True)
+
+ elif id == "static_reflect_func":
+ if self.opt.Algorithm == self.opt.Algo_Table_Driven:
+ return self.__pretty_bool(False)
+ elif self.opt.ReflectOut != None and self.opt.Algorithm == self.opt.Algo_Bit_by_Bit_Fast:
+ return self.__pretty_bool(False)
+ else:
+ return self.__pretty_bool(True)
+
+ elif id == "crc_algorithm":
+ if self.opt.Algorithm == self.opt.Algo_Bit_by_Bit:
+ return "bit-by-bit"
+ elif self.opt.Algorithm == self.opt.Algo_Bit_by_Bit_Fast:
+ return "bit-by-bit-fast"
+ elif self.opt.Algorithm == self.opt.Algo_Table_Driven:
+ return "table-driven"
+ else:
+ return "UNKNOWN"
+
+ elif id == "crc_table_init":
+ return self.__get_table_init()
+ elif id == "crc_table_core_algorithm_ni":
+ return self.__get_table_core_algorithm_ni()
+ elif id == "crc_table_core_algorithm_ri":
+ return self.__get_table_core_algorithm_ri()
+
+ elif id == "header_protection":
+ return self.__pretty_hdrprotection()
+
+ elif id == "crc_init_value":
+ ret = self.__get_init_value()
+ if ret == None:
+ return ""
+ else:
+ return ret
+
+ elif id == "crc_final_value":
+ return """\
+{%if $crc_algorithm == "table-driven"%}{:
+{%if $crc_reflect_in == $crc_reflect_out%}{:
+crc ^ {%crc_xor_out%}\
+:}{%else%}{:
+{%crc_reflect_function%}(crc, {%crc_width%}) ^ {%crc_xor_out%}\
+:}:}{%elif $crc_reflect_out == True%}{:
+{%crc_reflect_function%}(crc, {%crc_width%}) ^ {%crc_xor_out%}\
+:}{%else%}{:
+crc ^ {%crc_xor_out%}\
+:}\
+"""
+ elif id == "h_template":
+ return """\
+{%source_header%}
+#ifndef {%header_protection%}
+#define {%header_protection%}
+
+#include <stdint.h>
+#include <stdlib.h>
+{%if $undefined_parameters == True and $c_std != C89%}{:
+#include <stdbool.h>
+:}
+
+/**
+ * \\brief The definition of the used algorithm.
+ *****************************************************************************/
+{%if $crc_algorithm == "bit-by-bit"%}{:
+#define CRC_ALGO_BIT_BY_BIT 1
+:}{%elif $crc_algorithm == "bit-by-bit-fast"%}{:
+#define CRC_ALGO_BIT_BY_BIT_FAST 1
+:}{%elif $crc_algorithm == "table-driven"%}{:
+#define CRC_ALGO_TABLE_DRIVEN 1
+:}
+
+/**
+ * \\brief The type of the CRC values.
+ *
+ * This type must be big enough to contain at least {%cfg_width%} bits.
+ *****************************************************************************/
+typedef {%underlying_crc_t%} {%crc_t%};
+
+{%if $undefined_parameters == True%}{:
+/**
+ * \\brief The configuration type of the CRC algorithm.
+ *****************************************************************************/
+typedef struct {
+{%if $crc_width == Undefined%}{:
+ unsigned int width; /*!< The width of the polynom */
+:}
+{%if $crc_poly == Undefined%}{:
+ {%crc_t%} poly; /*!< The CRC polynom */
+:}
+{%if $crc_reflect_in == Undefined%}{:
+ {%c_bool%} reflect_in; /*!< Whether the input shall be reflected or not */
+:}
+{%if $crc_xor_in == Undefined%}{:
+ {%crc_t%} xor_in; /*!< The initial value of the algorithm */
+:}
+{%if $crc_reflect_out == Undefined%}{:
+ {%c_bool%} reflect_out; /*!< Wether the output shall be reflected or not */
+:}
+{%if $crc_xor_out == Undefined%}{:
+ {%crc_t%} xor_out; /*!< The value which shall be XOR-ed to the final CRC value */
+:}
+{%if $crc_width == Undefined%}{:
+
+ /* internal parameters */
+ {%crc_t%} msb_mask; /*!< a bitmask with the Most Significant Bit set to 1
+ initialise as 0x01 << (width - 1) */
+ {%crc_t%} crc_mask; /*!< a bitmask with all width bits set to 1
+ initialise as (cfg->msb_mask - 1) | cfg->msb_mask */
+:}
+} {%cfg_t%};
+
+:}
+{%if $use_reflect_func == True and $static_reflect_func != True%}{:
+{%crc_reflect_doc%}
+{%crc_reflect_function_def%};
+
+:}
+{%if $crc_algorithm == "table-driven" and $undefined_parameters == True%}{:
+{%crc_table_gen_doc%}
+{%crc_table_gen_function_def%};
+
+:}
+{%crc_init_doc%}
+{%if $constant_crc_init == False%}{:
+{%crc_init_function_def%};
+:}{%elif $c_std == C89%}{:
+#define {%crc_init_function%}() ({%crc_init_value%})
+:}{%else%}{:
+static inline {%crc_init_function_def%}{%%}
+{
+ return {%crc_init_value%};
+}
+:}
+
+{%crc_update_doc%}
+{%crc_update_function_def%};
+
+{%crc_finalize_doc%}
+{%if $inline_crc_finalize == True%}{:
+{%if $c_std == C89%}{:
+#define {%crc_finalize_function%}(crc) ({%crc_final_value%})
+:}{%else%}{:
+static inline {%crc_finalize_function_def%}{%%}
+{
+ return {%crc_final_value%};
+}
+:}
+:}{%else%}{:
+{%crc_finalize_function_def%};
+:}
+
+#endif /* {%header_protection%} */
+"""
+
+ elif id == "source_header":
+ return """\
+/**
+ * \\file {%filename%}
+ * Functions and types for CRC checks.
+ *
+ * Generated on {%datetime%},
+ * by {%program_version%}, {%program_url%}
+ * using the configuration:
+ * Width = {%crc_width%}
+ * Poly = {%crc_poly%}
+ * XorIn = {%crc_xor_in%}
+ * ReflectIn = {%crc_reflect_in%}
+ * XorOut = {%crc_xor_out%}
+ * ReflectOut = {%crc_reflect_out%}
+ * Algorithm = {%crc_algorithm%}
+ *****************************************************************************/\
+"""
+
+ elif id == "crc_reflect_doc":
+ return """\
+/**
+ * \\brief Reflect all bits of a \\a data word of \\a data_len bytes.
+ * \\param data The data word to be reflected.
+ * \\param data_len The width of \\a data expressed in number of bits.
+ * \\return The reflected data.
+ *****************************************************************************/\
+"""
+
+ elif id == "crc_reflect_function_def":
+ return """\
+long {%crc_reflect_function%}(long data, size_t data_len)\
+"""
+
+ elif id == "crc_reflect_function_body":
+ return """\
+{%if $crc_reflect_in == Undefined or $crc_reflect_in == True or $crc_reflect_out == Undefined or $crc_reflect_out == True%}{:
+{%crc_reflect_doc%}
+{%crc_reflect_function_def%}{%%}
+{
+ unsigned int i;
+ long ret;
+
+ ret = 0;
+ for (i = 0; i < data_len; i++)
+ {
+ if (data & 0x01) {
+ ret = (ret << 1) | 1;
+ } else {
+ ret = ret << 1;
+ }
+ data >>= 1;
+ }
+ return ret;
+}
+:}\
+"""
+
+ elif id == "crc_table_gen_doc":
+ return """\
+/**
+ * \\brief Populate the private static crc table.
+ * \\param cfg A pointer to a initialised {%cfg_t%} structure.
+ * \\return void
+ *****************************************************************************/\
+"""
+
+ elif id == "crc_table_gen_function_def":
+ return """\
+void {%crc_table_gen_function%}(const {%cfg_t%} *cfg)\
+"""
+
+ elif id == "crc_init_doc":
+ return """\
+/**
+ * \\brief Calculate the initial crc value.
+{%if $use_cfg_t == True%}{:
+ * \\param cfg A pointer to a initialised {%cfg_t%} structure.
+:}
+ * \\return The initial crc value.
+ *****************************************************************************/\
+"""
+
+ elif id == "crc_init_function_def":
+ return """\
+{%if $constant_crc_init == False%}{:
+{%crc_t%} {%crc_init_function%}(const {%cfg_t%} *cfg)\
+:}{%else%}{:
+{%crc_t%} {%crc_init_function%}(void)\
+:}\
+"""
+
+ elif id == "crc_update_doc":
+ return """\
+/**
+ * \\brief Update the crc value with new data.
+ * \\param crc The current crc value.
+{%if $use_cfg_t == True%}{:
+ * \\param cfg A pointer to a initialised {%cfg_t%} structure.
+:}
+ * \\param data Pointer to a buffer of \\a data_len bytes.
+ * \\param data_len Number of bytes in the \\a data buffer.
+ * \\return The updated crc value.
+ *****************************************************************************/\
+"""
+
+ elif id == "crc_update_function_def":
+ return """\
+{%if $undefined_parameters == True%}{:
+{%crc_t%} {%crc_update_function%}(const {%cfg_t%} *cfg, {%crc_t%} crc, const unsigned char *data, size_t data_len)\
+:}{%else%}{:
+{%crc_t%} {%crc_update_function%}({%crc_t%} crc, const unsigned char *data, size_t data_len)\
+:}\
+"""
+
+ elif id == "crc_finalize_doc":
+ return """\
+/**
+ * \\brief Calculate the final crc value.
+{%if $use_cfg_t == True%}{:
+ * \\param cfg A pointer to a initialised {%cfg_t%} structure.
+:}
+ * \\param crc The current crc value.
+ * \\return The final crc value.
+ *****************************************************************************/\
+"""
+
+ elif id == "crc_finalize_function_def":
+ return """\
+{%if $simple_crc_finalize_def != True%}{:
+{%crc_t%} {%crc_finalize_function%}(const {%cfg_t%} *cfg, {%crc_t%} crc)\
+:}{%else%}{:
+{%crc_t%} {%crc_finalize_function%}({%crc_t%} crc)\
+:}\
+"""
+
+ elif id == "c_template":
+ return """\
+{%source_header%}
+#include "{%header_filename%}"
+#include <stdint.h>
+#include <stdlib.h>
+{%if $undefined_parameters == True or $crc_algorithm == "bit-by-bit" or $crc_algorithm == "bit-by-bit-fast"%}{:
+{%if $c_std != C89%}{:
+#include <stdbool.h>
+:}
+:}
+
+{%if $use_reflect_func == True and $static_reflect_func == True%}{:
+static {%crc_reflect_function_def%};
+
+:}
+{%if $crc_algorithm == "bit-by-bit"%}{:
+{%c_bit_by_bit%}
+:}{%elif $crc_algorithm == "bit-by-bit-fast"%}{:
+{%c_bit_by_bit_fast%}
+:}{%elif $crc_algorithm == "table-driven"%}{:
+{%c_table_driven%}
+:}
+"""
+
+ elif id == "c_table":
+ return """\
+/**
+ * Static table used for the table_driven implementation.
+{%if $undefined_parameters == True%}{:
+ * Must be initialised with the {%crc_init_function%} function.
+:}
+ *****************************************************************************/
+{%if $undefined_parameters == True%}{:
+static {%crc_t%} crc_table[{%crc_table_width%}];
+:}{%else%}{:
+static const {%crc_t%} crc_table[{%crc_table_width%}] = {
+{%crc_table_init%}
+};
+:}
+"""
+
+ elif id == "c_bit_by_bit":
+ return """\
+{%if $use_reflect_func == True%}{:
+{%crc_reflect_function_body%}
+
+:}
+{%if $constant_crc_init == False%}{:
+{%crc_init_doc%}
+{%crc_init_function_def%}{%%}
+{
+ unsigned int i;
+ {%c_bool%} bit;
+ {%crc_t%} crc = {%cfg_xor_in%};
+ for (i = 0; i < {%cfg_width%}; i++) {
+ bit = crc & 0x01;
+ if (bit) {
+ crc = ((crc ^ {%cfg_poly%}) >> 1) | {%cfg_msb_mask%};
+ } else {
+ crc >>= 1;
+ }
+ }
+ return crc & {%cfg_mask%};
+}
+:}
+
+{%crc_update_doc%}
+{%crc_update_function_def%}{%%}
+{
+ unsigned int i;
+ {%c_bool%} bit;
+ unsigned char c;
+
+ while (data_len--) {
+{%if $crc_reflect_in == Undefined%}{:
+ if ({%cfg_reflect_in%}) {
+ c = {%crc_reflect_function%}(*data++, 8);
+ } else {
+ c = *data++;
+ }
+:}{%elif $crc_reflect_in == True%}{:
+ c = {%crc_reflect_function%}(*data++, 8);
+:}{%else%}{:
+ c = *data++;
+:}
+ for (i = 0; i < 8; i++) {
+ bit = crc & {%cfg_msb_mask%};
+ crc = (crc << 1) | ((c >> (7 - i)) & 0x01);
+ if (bit) {
+ crc ^= {%cfg_poly%};
+ }
+ }
+ crc &= {%cfg_mask%};
+ }
+ return crc & {%cfg_mask%};
+}
+
+
+{%crc_finalize_doc%}
+{%crc_finalize_function_def%}{%%}
+{
+ unsigned int i;
+ {%c_bool%} bit;
+
+ for (i = 0; i < {%cfg_width%}; i++) {
+ bit = crc & {%cfg_msb_mask%};
+ crc = (crc << 1) | 0x00;
+ if (bit) {
+ crc ^= {%cfg_poly%};
+ }
+ }
+{%if $crc_reflect_out == Undefined%}{:
+ if ({%cfg_reflect_out%}) {
+ crc = {%crc_reflect_function%}(crc, {%cfg_width%});
+ }
+:}{%elif $crc_reflect_out == True%}{:
+ crc = {%crc_reflect_function%}(crc, {%cfg_width%});
+:}
+ return (crc ^ {%cfg_xor_out%}) & {%cfg_mask%};
+}
+"""
+
+ elif id == "c_bit_by_bit_fast":
+ return """\
+{%if $use_reflect_func == True%}{:
+{%crc_reflect_function_body%}
+
+:}
+{%if $constant_crc_init == False%}{:
+{%crc_init_doc%}
+{%crc_init_function_def%}{%%}
+{
+ return {%cfg_xor_in%} & {%cfg_mask%};
+}
+:}
+
+{%crc_update_doc%}
+{%crc_update_function_def%}{%%}
+{
+ unsigned int i;
+ {%c_bool%} bit;
+ unsigned char c;
+
+ while (data_len--) {
+{%if $crc_reflect_in == Undefined%}{:
+ if ({%cfg_reflect_in%}) {
+ c = {%crc_reflect_function%}(*data++, 8);
+ } else {
+ c = *data++;
+ }
+:}{%else%}{:
+ c = *data++;
+:}
+{%if $crc_reflect_in == True%}{:
+ for (i = 0x01; i <= 0x80; i <<= 1) {
+:}{%else%}{:
+ for (i = 0x80; i > 0; i >>= 1) {
+:}
+ bit = crc & {%cfg_msb_mask%};
+ if (c & i) {
+ bit = !bit;
+ }
+ crc <<= 1;
+ if (bit) {
+ crc ^= {%cfg_poly%};
+ }
+ }
+ crc &= {%cfg_mask%};
+ }
+ return crc & {%cfg_mask%};
+}
+
+{%if $inline_crc_finalize != True%}{:
+{%crc_finalize_doc%}
+{%crc_finalize_function_def%}{%%}
+{
+{%if $crc_reflect_out == Undefined%}{:
+ if (cfg->reflect_out) {
+ crc = {%crc_reflect_function%}(crc, {%cfg_width%});
+ }
+:}{%elif $crc_reflect_out == True%}{:
+ crc = {%crc_reflect_function%}(crc, {%cfg_width%});
+:}
+ return (crc ^ {%cfg_xor_out%}) & {%cfg_mask%};
+}
+
+:}
+"""
+
+ elif id == "c_table_driven":
+ return """\
+{%c_table%}
+{%if $use_reflect_func == True%}{:
+{%crc_reflect_function_body%}
+:}
+
+{%if $constant_crc_init == False%}{:
+{%crc_init_doc%}
+{%crc_init_function_def%}{%%}
+{
+{%if $crc_reflect_in == Undefined%}{:
+ if ({%cfg_reflect_in%}) {
+ return {%crc_reflect_function%}({%cfg_xor_in%} & {%cfg_mask%}, {%cfg_width%});
+ } else {
+ return {%cfg_xor_in%} & {%cfg_mask%};
+ }
+:}{%elif $crc_reflect_in == True%}{:
+ return {%crc_reflect_function%}({%cfg_xor_in%} & {%cfg_mask%}, {%cfg_width%});
+:}{%else%}{:
+ return {%cfg_xor_in%} & {%cfg_mask%};
+:}
+}
+:}
+
+{%if $undefined_parameters == True%}{:
+{%crc_table_gen_doc%}
+{%crc_table_gen_function_def%}
+{
+ {%crc_t%} crc;
+ unsigned int i, j;
+
+ for (i = 0; i < {%cfg_table_width%}; i++) {
+{%if $crc_reflect_in == Undefined%}{:
+ if (cfg->reflect_in) {
+ crc = {%crc_reflect_function%}(i, {%cfg_table_idx_width%});
+ } else {
+ crc = i;
+ }
+:}{%elif $crc_reflect_in == True%}{:
+ crc = {%crc_reflect_function%}(i, {%cfg_table_idx_width%});
+:}{%else%}{:
+ crc = i;
+:}
+ crc <<= ({%cfg_width%} - {%cfg_table_idx_width%});
+ for (j = 0; j < {%cfg_table_idx_width%}; j++) {
+ if (crc & {%cfg_msb_mask%}) {
+ crc = (crc << 1) ^ {%cfg_poly%};
+ } else {
+ crc = crc << 1;
+ }
+ }
+{%if $crc_reflect_in == Undefined%}{:
+ if (cfg->reflect_in) {
+ crc = {%crc_reflect_function%}(crc, {%cfg_width%});
+ }
+:}{%elif $crc_reflect_in == True%}{:
+ crc = {%crc_reflect_function%}(crc, {%cfg_width%});
+:}
+ crc_table[i] = crc & {%cfg_mask%};
+ }
+}
+
+:}
+{%crc_update_doc%}
+{%crc_update_function_def%}{%%}
+{
+ unsigned int tbl_idx;
+
+{%if $crc_reflect_in == Undefined%}{:
+ if (cfg->reflect_in) {
+ while (data_len--) {
+{%crc_table_core_algorithm_ri%}
+ data++;
+ }
+ } else {
+ while (data_len--) {
+{%crc_table_core_algorithm_ni%}
+ data++;
+ }
+ }
+:}{%else%}{:
+ while (data_len--) {
+{%if $crc_reflect_in == True%}{:
+{%crc_table_core_algorithm_ri%}
+:}{%elif $crc_reflect_in == False%}{:
+{%crc_table_core_algorithm_ni%}
+:}
+ data++;
+ }
+:}
+ return crc & {%cfg_mask%};
+}
+
+{%if $inline_crc_finalize == False%}{:
+{%crc_finalize_doc%}
+{%crc_finalize_function_def%}{%%}
+{
+{%if $crc_reflect_in == Undefined or $crc_reflect_out == Undefined%}{:
+{%if $crc_reflect_in == Undefined and $crc_reflect_out == Undefined%}{:
+ if (cfg->reflect_in == !cfg->reflect_out)
+:}{%elif $crc_reflect_out == Undefined%}{:
+ if ({%if $crc_reflect_in == True%}{:!:}cfg->reflect_out)
+:}{%elif $crc_reflect_in == Undefined%}{:
+ if ({%if $crc_reflect_out == True%}{:!:}cfg->reflect_in)
+:} {
+ crc = {%crc_reflect_function%}(crc, {%cfg_width%});
+ }
+:}{%elif $crc_reflect_in != $crc_reflect_out%}{:
+ crc = {%crc_reflect_function%}(crc, {%cfg_width%});
+:}
+ return (crc ^ {%cfg_xor_out%}) & {%cfg_mask%};
+}
+:}
+"""
+
+ elif id == "main_template":
+ return """\
+#include <stdio.h>
+{%if $undefined_parameters == True%}{:
+#include <getopt.h>
+#include <stdlib.h>
+#include <stdio.h>
+#include <ctype.h>
+:}
+{%if $c_std != C89%}{:
+#include <stdbool.h>
+:}
+#include <string.h>
+
+static char str[256] = "123456789";
+static {%c_bool%} verbose = {%c_false%};
+
+void print_params({%if $undefined_parameters == True%}{:const {%cfg_t%} *cfg:}{%else%}{:void:});
+{%if $undefined_parameters == True%}{:
+{%getopt_template%}
+:}
+
+void print_params({%if $undefined_parameters == True%}{:const {%cfg_t%} *cfg:}{%else%}{:void:})
+{
+ char format[20];
+
+ snprintf(format, sizeof(format), "%%-16s = 0x%%0%dx\\n", (unsigned int)({%cfg_width%} + 3) / 4);
+ printf("%-16s = %d\\n", "width", (unsigned int){%cfg_width%});
+ printf(format, "poly", (unsigned int){%cfg_poly%});
+ printf("%-16s = %s\\n", "reflect_in", {%if crc_reflect_in == Undefined%}{:{%cfg_reflect_in%} ? "true": "false":}{%else%}{:{%if crc_reflect_in == True%}{:"true":}{%else%}{:"false":}:});
+ printf(format, "xor_in", {%cfg_xor_in%});
+ printf("%-16s = %s\\n", "reflect_out", {%if crc_reflect_out == Undefined%}{:{%cfg_reflect_out%} ? "true": "false":}{%else%}{:{%if crc_reflect_out == True%}{:"true":}{%else%}{:"false":}:});
+ printf(format, "xor_out", (unsigned int){%cfg_xor_out%});
+ printf(format, "crc_mask", (unsigned int){%cfg_mask%});
+ printf(format, "msb_mask", (unsigned int){%cfg_msb_mask%});
+}
+
+/**
+ * \\brief C main function.
+ * \\return 0 on success, != 0 on error.
+ *****************************************************************************/
+int main({%if $undefined_parameters == True%}{:int argc, char *argv[]:}{%else%}{:void:})
+{
+{%if $undefined_parameters == True%}{:
+ {%cfg_t%} cfg = {
+{%if $crc_width == Undefined%}{:
+ 0, /* width */
+:}
+{%if $crc_poly == Undefined%}{:
+ 0, /* poly */
+:}
+{%if $crc_xor_in == Undefined%}{:
+ 0, /* xor_in */
+:}
+{%if $crc_reflect_in == Undefined%}{:
+ 0, /* reflect_in */
+:}
+{%if $crc_xor_out == Undefined%}{:
+ 0, /* xor_out */
+:}
+{%if $crc_reflect_out == Undefined%}{:
+ 0, /* reflect_out */
+:}
+{%if $crc_width == Undefined%}{:
+
+ 0, /* crc_mask */
+ 0, /* msb_mask */
+:}
+ };
+:}
+ {%crc_t%} crc;
+
+{%if $undefined_parameters == True%}{:
+ get_config(argc, argv, &cfg);
+{%if $crc_algorithm == "table-driven"%}{:
+ {%crc_table_gen_function%}(&cfg);
+:}
+:}
+{%if $undefined_parameters == True%}{:
+ crc = {%crc_init_function%}({%if $constant_crc_init == False%}{:&cfg:});
+ crc = {%crc_update_function%}(&cfg, crc, (unsigned char *)str, strlen(str));
+:}{%else%}{:
+ crc = {%crc_init_function%}();
+ crc = {%crc_update_function%}(crc, (unsigned char *)str, strlen(str));
+:}
+{%if $simple_crc_finalize_def != True%}{:
+ crc = {%crc_finalize_function%}(&cfg, crc);
+:}{%else%}{:
+ crc = {%crc_finalize_function%}(crc);
+:}
+
+ if (verbose) {
+ print_params({%if $undefined_parameters == True%}{:&cfg:});
+ }
+ printf("0x%lx\\n", (long)crc);
+ return 0;
+}
+"""
+
+ elif id == "getopt_template":
+ return """\
+{%if $crc_reflect_in == Undefined or $crc_reflect_out == Undefined%}{:
+static {%c_bool%} atob(const char *str);
+:}
+{%if $crc_poly == Undefined or $crc_xor_in == Undefined or $crc_xor_out == Undefined%}{:
+static int xtoi(const char *str);
+:}
+static int get_config(int argc, char *argv[], {%cfg_t%} *cfg);
+
+
+{%if $crc_reflect_in == Undefined or $crc_reflect_out == Undefined%}{:
+{%c_bool%} atob(const char *str)
+{
+ if (!str) {
+ return 0;
+ }
+ if (isdigit(str[0])) {
+ return ({%c_bool%})atoi(str);
+ }
+ if (tolower(str[0]) == 't') {
+ return {%c_true%};
+ }
+ return {%c_false%};
+}
+:}
+
+{%if $crc_poly == Undefined or $crc_xor_in == Undefined or $crc_xor_out == Undefined%}{:
+int xtoi(const char *str)
+{
+ int ret = 0;
+
+ if (!str) {
+ return 0;
+ }
+ if (str[0] == '0' && tolower(str[1]) == 'x') {
+ str += 2;
+ while (*str) {
+ if (isdigit(*str))
+ ret = 16 * ret + *str - '0';
+ else if (isxdigit(*str))
+ ret = 16 * ret + tolower(*str) - 'a' + 10;
+ else
+ return ret;
+ str++;
+ }
+ } else if (isdigit(*str)) {
+ while (*str) {
+ if (isdigit(*str))
+ ret = 10 * ret + *str - '0';
+ else
+ return ret;
+ str++;
+ }
+ }
+ return ret;
+}
+:}
+
+
+int get_config(int argc, char *argv[], {%cfg_t%} *cfg)
+{
+ int c;
+ int this_option_optind;
+ int option_index;
+ static struct option long_options[] = {
+ {"width", 1, 0, 'w'},
+ {"poly", 1, 0, 'p'},
+ {"reflect-in", 1, 0, 'n'},
+ {"xor-in", 1, 0, 'i'},
+ {"reflect-out", 1, 0, 'u'},
+ {"xor-out", 1, 0, 'o'},
+ {"verbose", 0, 0, 'v'},
+ {"check-string", 1, 0, 's'},
+ {"table-idx-with", 1, 0, 't'},
+ {0, 0, 0, 0}
+ };
+
+ while (1) {
+ this_option_optind = optind ? optind : 1;
+ option_index = 0;
+
+ c = getopt_long (argc, argv, "w:p:ni:uo:s:v", long_options, &option_index);
+ if (c == -1)
+ break;
+
+ switch (c) {
+ case 0:
+ printf ("option %s", long_options[option_index].name);
+ if (optarg)
+ printf (" with arg %s", optarg);
+ printf ("\\n");
+{%if $crc_width == Undefined%}{:
+ case 'w':
+ cfg->width = atoi(optarg);
+ break;
+:}
+{%if $crc_poly == Undefined%}{:
+ case 'p':
+ cfg->poly = xtoi(optarg);
+ break;
+:}
+{%if $crc_reflect_in == Undefined%}{:
+ case 'n':
+ cfg->reflect_in = atob(optarg);
+ break;
+:}
+{%if $crc_xor_in == Undefined%}{:
+ case 'i':
+ cfg->xor_in = xtoi(optarg);
+ break;
+:}
+{%if $crc_reflect_out == Undefined%}{:
+ case 'u':
+ cfg->reflect_out = atob(optarg);
+ break;
+:}
+{%if $crc_xor_out == Undefined%}{:
+ case 'o':
+ cfg->xor_out = xtoi(optarg);
+ break;
+:}
+ case 's':
+ memcpy(str, optarg, strlen(optarg) < sizeof(str) ? strlen(optarg) + 1 : sizeof(str));
+ str[sizeof(str) - 1] = '\\0';
+ break;
+ case 'v':
+ verbose = {%c_true%};
+ break;
+ case 't':
+ /* ignore --table_idx_with option */
+ break;
+ case '?':
+ return -1;
+ case ':':
+ fprintf(stderr, "missing argument to option %c\\n", c);
+ return -1;
+ default:
+ fprintf(stderr, "unhandled option %c\\n", c);
+ return -1;
+ }
+ }
+{%if $crc_width == Undefined%}{:
+ cfg->msb_mask = 1 << (cfg->width - 1);
+ cfg->crc_mask = (cfg->msb_mask - 1) | cfg->msb_mask;
+:}
+
+{%if $crc_poly == Undefined%}{:
+ cfg->poly &= {%cfg_mask%};
+:}
+{%if $crc_xor_in == Undefined%}{:
+ cfg->xor_in &= {%cfg_mask%};
+:}
+{%if $crc_xor_out == Undefined%}{:
+ cfg->xor_out &= {%cfg_mask%};
+:}
+ return 0;
+}\
+"""
+
+
+ # __pretty_str
+ ###############################################################################
+ def __pretty_str(self, value):
+ """
+ Return a value of width bits as a pretty string.
+ """
+ if value == None:
+ return "Undefined"
+ return str(value)
+
+ # __pretty_hex
+ ###############################################################################
+ def __pretty_hex(self, value, width = None):
+ """
+ Return a value of width bits as a pretty hexadecimal formatted string.
+ """
+ if value == None:
+ return "Undefined"
+ if width == None:
+ return "0x%x" % value
+ width = (width + 3) / 4
+ str = "0x%%0%dx" % width
+ return str % value
+
+ # __pretty_bool
+ ###############################################################################
+ def __pretty_bool(self, value):
+ """
+ Return a boolen value of width bits as a pretty formatted string.
+ """
+ if value == None:
+ return "Undefined"
+ if value:
+ return "True"
+ else:
+ return "False"
+
+ # __pretty_hdrprotection
+ ###############################################################################
+ def __pretty_hdrprotection(self):
+ """
+ Return the name of a C header protection (e.g. __CRC_IMPLEMENTATION_H__)
+ """
+ tr_str = ""
+ for i in range(256):
+ if chr(i).isalpha():
+ tr_str += chr(i).upper()
+ else:
+ tr_str += '_'
+ if self.opt.OutputFile == None:
+ str = "stdout"
+ else:
+ str = self.opt.OutputFile
+ str = os.path.basename(str)
+ str = str.upper()
+ str = str.translate(tr_str)
+ return "__" + str + "__"
+
+ # __get_underlying_crc_t
+ ###############################################################################
+ def __get_underlying_crc_t(self):
+ """
+ Return the C type of the crc_t typedef
+ """
+ if self.opt.Width == None:
+ return "unsigned long"
+ if self.opt.CStd == "C89":
+ if self.opt.Width <= 8:
+ return "unsigned char"
+ elif self.opt.Width <= 16:
+ return "unsigned int"
+ else:
+ return "unsigned long"
+ else: # C99
+ if self.opt.Width <= 8:
+ return "uint8_t"
+ elif self.opt.Width <= 16:
+ return "uint16_t"
+ elif self.opt.Width <= 32:
+ return "uint32_t"
+ return "unsigned long"
+
+ # __get_init_value
+ ###############################################################################
+ def __get_init_value(self):
+ """
+ Return the init value of a C implementation, according to the selected algorithm and
+ to the given options
+ If no default option is given for a given parameter, value in the cfg_t structure must be used.
+ """
+ if self.opt.Algorithm != self.opt.Algo_Bit_by_Bit and self.opt.Algorithm != self.opt.Algo_Bit_by_Bit_Fast and self.opt.Algorithm != self.opt.Algo_Table_Driven:
+ init = 0
+ elif self.opt.Algorithm == self.opt.Algo_Bit_by_Bit:
+ if self.opt.ReflectIn == None or self.opt.XorIn == None or self.opt.Width == None or self.opt.Poly == None:
+ return None
+ register = self.opt.XorIn
+ for j in range(self.opt.Width):
+ bit = register & 1
+ if bit != 0:
+ register = ((register ^ self.opt.Poly) >> 1) | self.opt.MSB_Mask
+ else:
+ register = register >> 1
+ init = register & self.opt.Mask
+ elif self.opt.Algorithm == self.opt.Algo_Bit_by_Bit_Fast:
+ if self.opt.XorIn == None:
+ return None
+ init = self.opt.XorIn
+ elif self.opt.Algorithm == self.opt.Algo_Table_Driven:
+ if self.opt.ReflectIn == None or self.opt.XorIn == None or self.opt.Width == None:
+ return None
+ if self.opt.ReflectIn:
+ crc = Crc(self.opt)
+ init = crc.reflect(self.opt.XorIn, self.opt.Width)
+ else:
+ init = self.opt.XorIn
+ else:
+ init = 0
+ return self.__pretty_hex(init, self.opt.Width)
+
+ # __get_table_init
+ ###############################################################################
+ def __get_table_init(self):
+ """
+ Return the precalculated CRC table for the table_driven implementation
+ """
+ if self.opt.Algorithm != self.opt.Algo_Table_Driven:
+ return "0"
+ if self.opt.UndefinedCrcParameters:
+ return "0"
+ crc = Crc(self.opt)
+ tbl = crc.gen_table()
+ if self.opt.Width >= 32:
+ values_per_line = 4
+ elif self.opt.Width >= 16:
+ values_per_line = 8
+ else:
+ values_per_line = 16
+ out = ""
+ for i in range(self.opt.TableWidth):
+ if i % values_per_line == 0:
+ out += " "
+ if i == (self.opt.TableWidth - 1):
+ out += "%s" % self.__pretty_hex(tbl[i], self.opt.Width)
+ elif i % values_per_line == (values_per_line - 1):
+ out += "%s,\n" % self.__pretty_hex(tbl[i], self.opt.Width)
+ else:
+ out += "%s, " % self.__pretty_hex(tbl[i], self.opt.Width)
+ return out
+
+ # __get_table_core_algorithm_ni
+ ###############################################################################
+ def __get_table_core_algorithm_ni(self):
+ """
+ Return the core loop of the table-driven algorithm
+ """
+ if self.opt.Algorithm != self.opt.Algo_Table_Driven:
+ return ""
+
+ loop_core_ni = ""
+ loop_indent = ""
+ if self.opt.UndefinedCrcParameters:
+ loop_indent = " "
+ else:
+ loop_indent = " "
+ if self.opt.TableIdxWidth == 8:
+ if self.opt.Width == None:
+ shr = "({%cfg_width%} - 8)"
+ else:
+ shr = "%d" % (self.opt.Width - 8)
+ loop_core_ni += loop_indent + "tbl_idx = ((crc >> " + shr + ") ^ *data) & {%crc_table_mask%};" + '\n' + \
+ loop_indent + "crc = (crc_table[tbl_idx] ^ (crc << 8)) & {%cfg_mask%};" + '\n'
+ else:
+ if self.opt.Width == None:
+ shr = "({%cfg_width%} - {%cfg_table_idx_width%})"
+ else:
+ shr = "%d" % (self.opt.Width - self.opt.TableIdxWidth)
+ for i in range (8 / self.opt.TableIdxWidth):
+ str_idx = "%s" % (8 - (i + 1) * self.opt.TableIdxWidth)
+ loop_core_ni += loop_indent + "tbl_idx = (crc >> " + shr + ") ^ (*data >> " + str_idx + ");" + '\n' + \
+ loop_indent + "crc = crc_table[tbl_idx & {%crc_table_mask%}] ^ (crc << {%cfg_table_idx_width%});" + '\n'
+ return loop_core_ni
+
+ # __get_table_core_algorithm_ri
+ ###############################################################################
+ def __get_table_core_algorithm_ri(self):
+ """
+ Return the core loop of the table-driven algorithm
+ """
+ if self.opt.Algorithm != self.opt.Algo_Table_Driven:
+ return ""
+
+ loop_core_ri = ""
+ loop_indent = ""
+ if self.opt.UndefinedCrcParameters:
+ loop_indent = " "
+ else:
+ loop_indent = " "
+ if self.opt.TableIdxWidth == 8:
+ loop_core_ri += loop_indent + "tbl_idx = (crc ^ *data) & {%crc_table_mask%};" + '\n' + \
+ loop_indent + "crc = (crc_table[tbl_idx] ^ (crc >> 8)) & {%cfg_mask%};" + '\n'
+ else:
+ for i in range (8 / self.opt.TableIdxWidth):
+ str_idx = "%d" % i
+ loop_core_ri += loop_indent + "tbl_idx = crc ^ (*data >> (" + str_idx + " * {%cfg_table_idx_width%}));" + '\n' + \
+ loop_indent + "crc = crc_table[tbl_idx & {%crc_table_mask%}] ^ (crc >> {%cfg_table_idx_width%});" + '\n'
+
+ return loop_core_ri
diff --git a/maximus/python/lib/mmentryFields.py b/maximus/python/lib/mmentryFields.py
index 119e02c1c9..8002723b69 100644
--- a/maximus/python/lib/mmentryFields.py
+++ b/maximus/python/lib/mmentryFields.py
@@ -1216,10 +1216,12 @@ class MmentryFields():
self.access=myAccess
if mySnidAccess!=None:
self.snidAccess=mySnidAccess
+ print "snidAccess = "+hex(self.snidAccess)
else:
self.snidAccess = int(self.snid + self.access*pow(2,4))
+ print "snid = "+hex(self.snid)
+ print "access = "+hex(self.access)
self.snidAccessField = pack('B',self.snidAccess)
- print "snidAccess = "+hex(self.snidAccess)
#TEI assigned to the station
staTei = 0 #no backupCco by default
diff --git a/maximus/python/lib/pycrc24.py b/maximus/python/lib/pycrc24.py
new file mode 100644
index 0000000000..4ceb233f0d
--- /dev/null
+++ b/maximus/python/lib/pycrc24.py
@@ -0,0 +1,214 @@
+#!/usr/bin/env python
+# -*- coding: Latin-1 -*-
+
+# pycrc -- parametrisable CRC calculation utility and C source code generator
+#
+# Copyright (c) 2006-2007 Thomas Pircher <tehpeh@gmx.net>
+#
+# Permission is hereby granted, free of charge, to any person obtaining a copy
+# of this software and associated documentation files (the "Software"), to deal
+# in the Software without restriction, including without limitation the rights
+# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+# copies of the Software, and to permit persons to whom the Software is
+# furnished to do so, subject to the following conditions:
+#
+# The above copyright notice and this permission notice shall be included in
+# all copies or substantial portions of the Software.
+#
+# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+# THE SOFTWARE.
+
+
+"""
+pycrc is a fully parametrisable Cyclic Redundancy Check (CRC) calculation
+utility and C source code generator written in Python.
+
+It can:
+ - generate the checksum of a string
+ - generate the checksum of a file
+ - generate the C header file and source of any of the algorithms below
+
+It supports the following CRC algorithms:
+ - bit-by-bit the basic algorithm which operates bit by bit on the augmented message
+ - bit-by-bit-fast a variation of the simple bit-by-bit algorithm
+ - table-driven the standard table driven algorithm
+"""
+
+from crc24 import Options
+from crc24_algorithms import Crc
+from crc24_parser import MacroParser
+import sys
+
+
+# function print_parameters
+###############################################################################
+def print_parameters(opt):
+ """
+ Generate a string with the options pretty-printed (used in the --verbose mode)
+ """
+ out = ""
+ out += "Width = {%crc_width%}\n"
+ out += "Poly = {%crc_poly%}\n"
+ out += "ReflectIn = {%crc_reflect_in%}\n"
+ out += "XorIn = {%crc_xor_in%}\n"
+ out += "ReflectOut = {%crc_reflect_out%}\n"
+ out += "XorOut = {%crc_xor_out%}\n"
+ out += "Algorithm = {%crc_algorithm%}\n"
+
+ mp = MacroParser(opt)
+ if mp.parse(out):
+ return mp.out_str
+ return ""
+
+
+# function check_string
+###############################################################################
+def check_string(myString):
+
+
+ opt=Options(True)
+ opt.CheckString=myString
+ """
+ Returns the calculated CRC sum of a string
+ """
+ if opt.UndefinedCrcParameters:
+ sys.stderr.write("Error: undefined parameters\n")
+ sys.exit(1)
+ if opt.Algorithm == 0:
+ opt.Algorithm = opt.Algo_Bit_by_Bit | opt.Algo_Bit_by_Bit_Fast | opt.Algo_Table_Driven
+
+ alg = Crc(opt)
+ crc = this_crc = None
+ if opt.Algorithm & opt.Algo_Bit_by_Bit:
+ this_crc = alg.bit_by_bit(opt.CheckString)
+ if crc != None and this_crc != crc:
+ sys.stderr.write("Error: different checksums: 0x%x, 0x%x\n" % (this_crc, crc))
+ sys.exit(1)
+ crc = this_crc
+ if opt.Algorithm & opt.Algo_Bit_by_Bit_Fast:
+ this_crc = alg.bit_by_bit_fast(opt.CheckString)
+ if crc != None and this_crc != crc:
+ sys.stderr.write("Error: different checksums: 0x%x, 0x%x\n" % (this_crc, crc))
+ sys.exit(1)
+ crc = this_crc
+ if opt.Algorithm & opt.Algo_Table_Driven:
+ opt.TableIdxWidth = 8 # FIXME cowardly refusing to use less bits for the table
+ this_crc = alg.table_driven(opt.CheckString)
+ if crc != None and this_crc != crc:
+ sys.stderr.write("Error: different checksums: 0x%x, 0x%x\n" % (this_crc, crc))
+ sys.exit(1)
+ crc = this_crc
+ return crc
+
+# function crc_file_update
+###############################################################################
+def crc_file_update(opt, alg, register, str):
+ """
+ Update the CRC using the bit-by-bit-fast CRC algorithm.
+ """
+ for i in range(len(str)):
+ octet = ord(str[i])
+ if alg.ReflectIn:
+ octet = alg.reflect(octet, 8)
+ for j in range(8):
+ bit = register & alg.MSB_Mask
+ register <<= 1
+ if octet & (0x80 >> j):
+ bit ^= alg.MSB_Mask
+ if bit:
+ register ^= alg.Poly
+ register &= alg.Mask
+ return register
+
+# function check_file
+###############################################################################
+def check_file(opt):
+ """
+ Calculate the CRC of a file.
+ This algorithm uses the table_driven CRC algorithm.
+ """
+ if opt.UndefinedCrcParameters:
+ sys.stderr.write("Error: undefined parameters\n")
+ sys.exit(1)
+ alg = Crc(opt)
+
+ try:
+ file = open(opt.CheckFile, 'rb')
+ except IOError:
+ sys.stderr.write("Error: can't open file %s\n" % opt.CheckFile)
+ sys.exit(1)
+
+ if not opt.ReflectIn:
+ register = opt.XorIn
+ else:
+ register = alg.reflect(opt.XorIn, opt.Width)
+ try:
+ str = file.read()
+ except IOError:
+ sys.stderr.write("Error: can't open read %s\n" % opt.CheckFile)
+ sys.exit(1)
+ while len(str):
+ register = crc_file_update(opt, alg, register, str)
+ try:
+ str = file.read()
+ except IOError:
+ sys.stderr.write("Error: can't open read %s\n" % opt.CheckFile)
+ sys.exit(1)
+ file.close()
+
+ if opt.ReflectOut:
+ register = alg.reflect(register, opt.Width)
+ register = register ^ opt.XorOut
+ return register
+
+# main function
+###############################################################################
+def main():
+ """
+ Main function
+ """
+ opt = Options("0.6.4")
+ opt.parse(sys.argv)
+ if opt.Verbose:
+ print print_parameters(opt)
+ if opt.Action == "check_string":
+ crc = check_string(opt)
+ print "0x%x" % crc
+ if opt.Action == "check_file":
+ crc = check_file(opt)
+ print "0x%x" % crc
+ if opt.Action == "generate_h" or opt.Action == "generate_c" or opt.Action == "generate_c-main" or opt.Action == "generate_table":
+ mp = MacroParser(opt)
+ if opt.Action == "generate_h":
+ in_str = "{%h_template%}"
+ elif opt.Action == "generate_c":
+ in_str = "{%c_template%}"
+ elif opt.Action == "generate_c-main":
+ in_str = "{%c_template%}\n\n{%main_template%}"
+ elif opt.Action == "generate_table":
+ in_str = "{%crc_table_init%}"
+ else:
+ sys.stderr.write("Error: unknown action %s\n" % opt.Action)
+ sys.exit(1)
+ if not mp.parse(in_str):
+ sys.stderr.write("Error: Failure parsing internal macro language\n")
+ sys.exit(1)
+ if opt.OutputFile == None:
+ print mp.out_str
+ else:
+ try:
+ file = open(opt.OutputFile, "w")
+ file.write(mp.out_str)
+ file.close()
+ except IOError:
+ sys.stderr.write("Error: cannot write to file %s\n" % opt.OutputFile)
+ sys.exit(1)
+ return 0
+
+if __name__ == "__main__":
+ sys.exit(main())