diff --git a/.github/workflows/wheels.yml b/.github/workflows/wheels.yml index 9baaff0f5..745caa987 100644 --- a/.github/workflows/wheels.yml +++ b/.github/workflows/wheels.yml @@ -8,7 +8,7 @@ jobs: runs-on: ${{ matrix.os }} strategy: matrix: - os: [ubuntu-20.04, windows-2019, macOS-11] + os: [ubuntu-20.04, windows-2019, macOS-13] steps: - uses: actions/checkout@v3 @@ -19,7 +19,7 @@ jobs: - uses: actions/setup-python@v3 - name: Install cibuildwheel - run: python -m pip install cibuildwheel==2.12.1 + run: python -m pip install cibuildwheel==2.16.2 - name: Build wheels run: python -m cibuildwheel --output-dir wheelhouse diff --git a/build_libicsneo.py b/build_libicsneo.py index 89f58caf2..4d7e08518 100644 --- a/build_libicsneo.py +++ b/build_libicsneo.py @@ -4,90 +4,105 @@ import shutil import sys -LIBICSNEO_COMMIT = '9ef93eb73e1ada72ccc7a571744b9db1a564f18b' -LIBUSB_COMMIT = '4239bc3a50014b8e6a5a2a59df1fff3b7469543b' +LIBICSNEO_COMMIT = "9ef93eb73e1ada72ccc7a571744b9db1a564f18b" +LIBUSB_COMMIT = "4239bc3a50014b8e6a5a2a59df1fff3b7469543b" CPUS = str(multiprocessing.cpu_count()) def checkout(): - if not os.path.isdir('libicsneo'): - subprocess.check_output( - ['git', 'clone', 'https://github.com/intrepidcs/libicsneo.git']) - subprocess.check_output( - ['git', 'checkout', LIBICSNEO_COMMIT], cwd='libicsneo') + if not os.path.isdir("libicsneo"): + subprocess.check_output(["git", "clone", "https://github.com/intrepidcs/libicsneo.git"]) + subprocess.check_output(["git", "checkout", LIBICSNEO_COMMIT], cwd="libicsneo") - if not os.path.isdir('libusb') and sys.platform == 'darwin': - subprocess.check_output( - ['git', 'clone', 'https://github.com/libusb/libusb.git']) - subprocess.check_output(['git', 'checkout', LIBUSB_COMMIT], cwd='libusb') + if not os.path.isdir("libusb") and sys.platform == "darwin": + subprocess.check_output(["git", "clone", "https://github.com/libusb/libusb.git"]) + subprocess.check_output(["git", "checkout", LIBUSB_COMMIT], cwd="libusb") def _build_libusb(): - subprocess.check_output(['git', 'clean', '-xdf'], cwd='libusb') + subprocess.check_output(["git", "clean", "-xdf"], cwd="libusb") - subprocess.check_output(['./bootstrap.sh'], cwd='libusb') + subprocess.check_output(["./bootstrap.sh"], cwd="libusb") env = os.environ.copy() - env['CFLAGS'] = '-arch x86_64 -arch arm64 -mmacosx-version-min=10.13' - env['CXXFLAGS'] = '-arch x86_64 -arch arm64 -mmacosx-version-min=10.13' - subprocess.check_output( - ['./configure', '--disable-static', '--prefix=/tmp/libusb'], cwd='libusb', env=env) + env["CFLAGS"] = "-arch x86_64 -arch arm64 -mmacosx-version-min=10.13" + env["CXXFLAGS"] = "-arch x86_64 -arch arm64 -mmacosx-version-min=10.13" + subprocess.check_output(["./configure", "--disable-static", "--prefix=/tmp/libusb"], cwd="libusb", env=env) - subprocess.check_output(['make', '-j' + CPUS], cwd='libusb') - subprocess.check_output(['make', 'install'], cwd='libusb') + subprocess.check_output(["make", "-j" + CPUS], cwd="libusb") + subprocess.check_output(["make", "install"], cwd="libusb") def _build_icsneo_linux(): - subprocess.check_output(['git', 'clean', '-xdf'], cwd='libicsneo') - subprocess.check_output(['mkdir', '-p', 'libicsneo/build']) + subprocess.check_output(["git", "clean", "-xdf"], cwd="libicsneo") + subprocess.check_output(["mkdir", "-p", "libicsneo/build"]) + + subprocess.check_output( + ["cmake", "..", "-DCMAKE_BUILD_TYPE=Release", "-DLIBICSNEO_BUILD_ICSNEOLEGACY=ON"], cwd="libicsneo/build" + ) + subprocess.check_output( + ["cmake", "--build", ".", "--target", "icsneolegacy", "--parallel", CPUS], cwd="libicsneo/build" + ) - subprocess.check_output(['cmake', '..', '-DCMAKE_BUILD_TYPE=Release', '-DLIBICSNEO_BUILD_ICSNEOLEGACY=ON'], cwd='libicsneo/build') - subprocess.check_output(['cmake', '--build', '.', '--target', - 'icsneolegacy', '--parallel', CPUS], cwd='libicsneo/build') def _build_icsneo_macos(): - subprocess.check_output(['git', 'clean', '-xdf'], cwd='libicsneo') - subprocess.check_output(['mkdir', '-p', 'libicsneo/build']) + subprocess.check_output(["git", "clean", "-xdf"], cwd="libicsneo") + subprocess.check_output(["mkdir", "-p", "libicsneo/build"]) - subprocess.check_output(['cmake', '..', '-DCMAKE_BUILD_TYPE=Release', '-DCMAKE_OSX_ARCHITECTURES=arm64;x86_64', - '-DLIBICSNEO_BUILD_ICSNEOLEGACY=ON', '-DCMAKE_OSX_DEPLOYMENT_TARGET=10.13', - '-DLIBUSB_LIBRARIES=/tmp/libusb/lib/libusb-1.0.0.dylib', - '-DLIBUSB_INCLUDE_DIR=/tmp/libusb/include/libusb-1.0'], cwd='libicsneo/build') + subprocess.check_output( + [ + "cmake", + "..", + "-DCMAKE_BUILD_TYPE=Release", + "-DCMAKE_OSX_ARCHITECTURES=arm64;x86_64", + "-DLIBICSNEO_BUILD_ICSNEOLEGACY=ON", + "-DCMAKE_OSX_DEPLOYMENT_TARGET=10.13", + "-DLIBUSB_LIBRARIES=/tmp/libusb/lib/libusb-1.0.0.dylib", + "-DLIBUSB_INCLUDE_DIR=/tmp/libusb/include/libusb-1.0", + ], + cwd="libicsneo/build", + ) - subprocess.check_output(['cmake', '--build', '.', '--target', - 'icsneolegacy', '--parallel', CPUS], cwd='libicsneo/build') - subprocess.check_output(['install_name_tool', '-change', '/tmp/libusb/lib/libusb-1.0.0.dylib', - '@loader_path/libusb-1.0.0.dylib', 'libicsneolegacy.dylib'], cwd='libicsneo/build') + subprocess.check_output( + ["cmake", "--build", ".", "--target", "icsneolegacy", "--parallel", CPUS], cwd="libicsneo/build" + ) + subprocess.check_output( + [ + "install_name_tool", + "-change", + "/tmp/libusb/lib/libusb-1.0.0.dylib", + "@loader_path/libusb-1.0.0.dylib", + "libicsneolegacy.dylib", + ], + cwd="libicsneo/build", + ) def build(): print("Building libicsneo...") - if sys.platform == 'darwin': + if sys.platform == "darwin": _build_libusb() _build_icsneo_macos() - elif sys.platform == 'linux': + elif sys.platform == "linux": _build_icsneo_linux() def copy(): - if sys.platform == 'darwin': - shutil.copyfile('/tmp/libusb/lib/libusb-1.0.0.dylib', - 'ics/libusb-1.0.0.dylib') - shutil.copyfile('libicsneo/build/libicsneolegacy.dylib', - 'ics/libicsneolegacy.dylib') - elif sys.platform == 'linux': - shutil.copyfile('libicsneo/build/libicsneolegacy.so', - 'ics/libicsneolegacy.so') + if sys.platform == "darwin": + shutil.copyfile("/tmp/libusb/lib/libusb-1.0.0.dylib", "ics/libusb-1.0.0.dylib") + shutil.copyfile("libicsneo/build/libicsneolegacy.dylib", "ics/libicsneolegacy.dylib") + elif sys.platform == "linux": + shutil.copyfile("libicsneo/build/libicsneolegacy.so", "ics/libicsneolegacy.so") def clean(): - shutil.rmtree('libicsneo') - shutil.rmtree('libusb') - shutil.rmtree('/tmp/libusb') + shutil.rmtree("libicsneo") + shutil.rmtree("libusb") + shutil.rmtree("/tmp/libusb") -if __name__ == '__main__': - if '--clean' in sys.argv: +if __name__ == "__main__": + if "--clean" in sys.argv: clean() exit(0) checkout() diff --git a/doc/source/conf.py b/doc/source/conf.py index 440df7426..e3fbb9ec2 100644 --- a/doc/source/conf.py +++ b/doc/source/conf.py @@ -19,56 +19,56 @@ # If extensions (or modules to document with autodoc) are in another directory, # add these directories to sys.path here. If the directory is relative to the # documentation root, use os.path.abspath to make it absolute, like shown here. -#sys.path.insert(0, os.path.abspath('.')) -sys.path.insert(0, os.path.abspath('.')) +# sys.path.insert(0, os.path.abspath('.')) +sys.path.insert(0, os.path.abspath(".")) # -- General configuration ------------------------------------------------ # If your documentation needs a minimal Sphinx version, state it here. -#needs_sphinx = '1.0' +# needs_sphinx = '1.0' # Add any Sphinx extension module names here, as strings. They can be # extensions coming with Sphinx (named 'sphinx.ext.*') or your custom # ones. extensions = [ - 'sphinx.ext.autosummary', - 'sphinx.ext.autodoc', + "sphinx.ext.autosummary", + "sphinx.ext.autodoc", ] # Add any paths that contain templates here, relative to this directory. -templates_path = ['_templates'] +templates_path = ["_templates"] # The suffix of source filenames. -source_suffix = '.rst' +source_suffix = ".rst" # The encoding of source files. -#source_encoding = 'utf-8-sig' +# source_encoding = 'utf-8-sig' # The master toctree document. -master_doc = 'index' +master_doc = "index" # General information about the project. -project = 'ics' -copyright = 'Intrepid Control Systems, Inc.' +project = "ics" +copyright = "Intrepid Control Systems, Inc." # The version info for the project you're documenting, acts as replacement for # |version| and |release|, also used in various other places throughout the # built documents. # # The short X.Y version. -version = '913.16' +version = "913.16" # The full version, including alpha/beta/rc tags. release = version # The language for content autogenerated by Sphinx. Refer to documentation # for a list of supported languages. -#language = None +# language = None # There are two options for replacing |today|: either, you set today to some # non-false value, then it is used: -#today = '' +# today = '' # Else, today_fmt is used as the format for a strftime call. -#today_fmt = '%B %d, %Y' +# today_fmt = '%B %d, %Y' # List of patterns, relative to source directory, that match files and # directories to ignore when looking for source files. @@ -76,168 +76,162 @@ # The reST default role (used for this markup: `text`) to use for all # documents. -#default_role = None +# default_role = None # If true, '()' will be appended to :func: etc. cross-reference text. -#add_function_parentheses = True +# add_function_parentheses = True # If true, the current module name will be prepended to all description # unit titles (such as .. function::). -#add_module_names = True +# add_module_names = True # If true, sectionauthor and moduleauthor directives will be shown in the # output. They are ignored by default. -#show_authors = False +# show_authors = False # The name of the Pygments (syntax highlighting) style to use. -pygments_style = 'sphinx' +pygments_style = "sphinx" # A list of ignored prefixes for module index sorting. -#modindex_common_prefix = [] +# modindex_common_prefix = [] # If true, keep warnings as "system message" paragraphs in the built documents. -#keep_warnings = False +# keep_warnings = False # -- Options for HTML output ---------------------------------------------- # The theme to use for HTML and HTML Help pages. See the documentation for # a list of builtin themes. -#html_theme = 'sphinx_rtd_theme' -html_theme = 'classic' +# html_theme = 'sphinx_rtd_theme' +html_theme = "classic" # Theme options are theme-specific and customize the look and feel of a theme # further. For a list of options available for each theme, see the # documentation. -html_theme_options = {'body_max_width': '80%'} +html_theme_options = {"body_max_width": "80%"} # Add any paths that contain custom themes here, relative to this directory. -#html_theme_path = [] +# html_theme_path = [] # The name for this set of Sphinx documents. If None, it defaults to # " v documentation". -#html_title = None +# html_title = None # A shorter title for the navigation bar. Default is the same as html_title. -#html_short_title = None +# html_short_title = None # The name of an image file (relative to this directory) to place at the top # of the sidebar. -#html_logo = None +# html_logo = None # The name of an image file (within the static path) to use as favicon of the # docs. This file should be a Windows icon file (.ico) being 16x16 or 32x32 # pixels large. -#html_favicon = None +# html_favicon = None # Add any paths that contain custom static files (such as style sheets) here, # relative to this directory. They are copied after the builtin static files, # so a file named "default.css" will overwrite the builtin "default.css". -#html_static_path = ['_static'] +# html_static_path = ['_static'] # Add any extra paths that contain custom files (such as robots.txt or # .htaccess) here, relative to this directory. These files are copied # directly to the root of the documentation. -#html_extra_path = [] +# html_extra_path = [] # If not '', a 'Last updated on:' timestamp is inserted at every page bottom, # using the given strftime format. -#html_last_updated_fmt = '%b %d, %Y' +# html_last_updated_fmt = '%b %d, %Y' # If true, SmartyPants will be used to convert quotes and dashes to # typographically correct entities. -#html_use_smartypants = True +# html_use_smartypants = True # Custom sidebar templates, maps document names to template names. -#html_sidebars = {} +# html_sidebars = {} # Additional templates that should be rendered to pages, maps page names to # template names. -#html_additional_pages = {} +# html_additional_pages = {} # If false, no module index is generated. -#html_domain_indices = True +# html_domain_indices = True # If false, no index is generated. -#html_use_index = True +# html_use_index = True # If true, the index is split into individual pages for each letter. -#html_split_index = False +# html_split_index = False # If true, links to the reST sources are added to the pages. -#html_show_sourcelink = True +# html_show_sourcelink = True # If true, "Created using Sphinx" is shown in the HTML footer. Default is True. -#html_show_sphinx = True +# html_show_sphinx = True # If true, "(C) Copyright ..." is shown in the HTML footer. Default is True. -#html_show_copyright = True +# html_show_copyright = True # If true, an OpenSearch description file will be output, and all pages will # contain a tag referring to it. The value of this option must be the # base URL from which the finished HTML is served. -#html_use_opensearch = '' +# html_use_opensearch = '' # This is the file name suffix for HTML files (e.g. ".xhtml"). -#html_file_suffix = None +# html_file_suffix = None # Output file base name for HTML help builder. -htmlhelp_basename = 'icsdoc' +htmlhelp_basename = "icsdoc" # -- Options for LaTeX output --------------------------------------------- latex_elements = { -# The paper size ('letterpaper' or 'a4paper'). -#'papersize': 'letterpaper', - -# The font size ('10pt', '11pt' or '12pt'). -#'pointsize': '10pt', - -# Additional stuff for the LaTeX preamble. -#'preamble': '', + # The paper size ('letterpaper' or 'a4paper'). + #'papersize': 'letterpaper', + # The font size ('10pt', '11pt' or '12pt'). + #'pointsize': '10pt', + # Additional stuff for the LaTeX preamble. + #'preamble': '', } # Grouping the document tree into LaTeX files. List of tuples # (source start file, target name, title, # author, documentclass [howto, manual, or own class]). latex_documents = [ - ('index', 'ics.tex', 'python\\_ics Documentation', - 'David Rebbe', 'manual'), + ("index", "ics.tex", "python\\_ics Documentation", "David Rebbe", "manual"), ] # The name of an image file (relative to this directory) to place at the top of # the title page. -#latex_logo = None +# latex_logo = None # For "manual" documents, if this is true, then toplevel headings are parts, # not chapters. -#latex_use_parts = False +# latex_use_parts = False # If true, show page references after internal links. -#latex_show_pagerefs = False +# latex_show_pagerefs = False # If true, show URL addresses after external links. -#latex_show_urls = False +# latex_show_urls = False # Documents to append as an appendix to all manuals. -#latex_appendices = [] +# latex_appendices = [] # If false, no module index is generated. -#latex_domain_indices = True +# latex_domain_indices = True # -- Options for manual page output --------------------------------------- # One entry per manual page. List of tuples # (source start file, name, description, authors, manual section). -man_pages = [ - ('index', 'ics', 'ics Documentation', - ['David Rebbe'], 1) -] +man_pages = [("index", "ics", "ics Documentation", ["David Rebbe"], 1)] # If true, show URL addresses after external links. -#man_show_urls = False +# man_show_urls = False # -- Options for Texinfo output ------------------------------------------- @@ -246,21 +240,19 @@ # (source start file, target name, title, author, # dir menu entry, description, category) texinfo_documents = [ - ('index', 'ics', 'ics Documentation', - 'David Rebbe', 'ics', 'One line description of project.', - 'Miscellaneous'), + ("index", "ics", "ics Documentation", "David Rebbe", "ics", "One line description of project.", "Miscellaneous"), ] # Documents to append as an appendix to all manuals. -#texinfo_appendices = [] +# texinfo_appendices = [] # If false, no module index is generated. -#texinfo_domain_indices = True +# texinfo_domain_indices = True # How to display URL addresses: 'footnote', 'no', or 'inline'. -#texinfo_show_urls = 'footnote' +# texinfo_show_urls = 'footnote' # If true, do not generate a @detailmenu in the "Top" node's menu. -#texinfo_no_detailmenu = False +# texinfo_no_detailmenu = False -autodoc_member_order = 'groupwise' +autodoc_member_order = "groupwise" diff --git a/doc/source/generate_documentation.py b/doc/source/generate_documentation.py index 70f24338c..422b9dccd 100644 --- a/doc/source/generate_documentation.py +++ b/doc/source/generate_documentation.py @@ -1,46 +1,50 @@ import inspect import ics + def generate_structures(): - #data = '.. autosummary::\n' + # data = '.. autosummary::\n' """ \t.. automodule:: ics.structures.{name}.{name}\n\t\t:members:\n\t\t:undoc-members:\n\n" """ - data = '' + data = "" for name, value in inspect.getmembers(ics.structures, inspect.ismodule): - #data += f"\t.. automodule:: ics.structures.{name}\n\t\t:members:\n\t\t:show-inheritance:\n\t\t:undoc-members:\n\n" + # data += f"\t.. automodule:: ics.structures.{name}\n\t\t:members:\n\t\t:show-inheritance:\n\t\t:undoc-members:\n\n" data += f"\t.. autoclass:: ics.structures.{name}.{name}\n\t\t:members:\n\t\t:undoc-members:\n\n" return data + def generate_functions(): - data = '' + data = "" functions = inspect.getmembers(ics, inspect.isroutine) new_style_functions = [] icsneo_style_functions = [] inbetween_style_functions = [] for function_name, function_type in functions: - if function_name.startswith('icsneo'): + if function_name.startswith("icsneo"): icsneo_style_functions.append(function_name) - elif '_' in function_name: + elif "_" in function_name: new_style_functions.append(function_name) else: inbetween_style_functions.append(function_name) - data += '.. autosummary::\n' + data += ".. autosummary::\n" for name in new_style_functions + inbetween_style_functions + icsneo_style_functions: if name: data += f"\tics.{name}\n" return data + def generate_variables(): - data = '' + data = "" for variable in [item for item in dir(ics) if not item.startswith("__") and item.isupper()]: data += f"\t.. py:data:: {str(variable)}\n\t\t:annotation: = {str(getattr(ics, variable))}\n\n" return data + def generate_documentation(): return inspect.cleandoc( - """.. include:: header.rst + """.. include:: header.rst .. include:: examples.rst ============================================================ @@ -69,8 +73,11 @@ def generate_documentation(): %s - """ % (generate_functions(), generate_structures(), generate_variables())) + """ + % (generate_functions(), generate_structures(), generate_variables()) + ) + -with open('index.rst', 'w+') as f: +with open("index.rst", "w+") as f: f.write(generate_documentation()) -print("Done.") \ No newline at end of file +print("Done.") diff --git a/examples/canfd_transmit_example.py b/examples/canfd_transmit_example.py index 2de778c08..3e211e980 100644 --- a/examples/canfd_transmit_example.py +++ b/examples/canfd_transmit_example.py @@ -1,4 +1,4 @@ -import ics +import ics if __name__ == "__main__": # Create a CAN Message like normal but set the StatusBitFields @@ -8,8 +8,8 @@ msg.Protocol = ics.SPY_PROTOCOL_CANFD msg.StatusBitField = ics.SPY_STATUS_CANFD msg.StatusBitField3 = ics.SPY_STATUS3_CANFD_BRS - msg.ExtraDataPtr = tuple([x for x in range(64)]) + msg.ExtraDataPtr = tuple([x for x in range(64)]) # Open Device and transmit the message device = ics.open_device() - ics.transmit_messages(device, msg) \ No newline at end of file + ics.transmit_messages(device, msg) diff --git a/examples/iso15765_example.py b/examples/iso15765_example.py index aadf14b9c..66dc8d037 100644 --- a/examples/iso15765_example.py +++ b/examples/iso15765_example.py @@ -4,6 +4,7 @@ enable_print_message = False enable_use_server = True + # Helper Functions ########################################################## def dev_name(device): if int("0A0000", 36) <= device.SerialNumber <= int("ZZZZZZ", 36): @@ -11,34 +12,40 @@ def dev_name(device): else: return device.Name + " " + str(device.SerialNumber) + def print_message(msg): if not enable_print_message: if isinstance(msg, ics.SpyMessage): - print('\tArbID: {}\tData: {}'.format(hex(msg.ArbIDOrHeader), [hex(x) for x in msg.Data])) + print("\tArbID: {}\tData: {}".format(hex(msg.ArbIDOrHeader), [hex(x) for x in msg.Data])) return - print('\t' + str(type(msg))) + print("\t" + str(type(msg))) for attribute in dir(msg): if attribute.startswith("_"): continue length = len(attribute) - if attribute == 'data': - print("\t\t{}:{}{}".format(attribute, " "*(30-length), msg.data[:msg.num_bytes])) + if attribute == "data": + print("\t\t{}:{}{}".format(attribute, " " * (30 - length), msg.data[: msg.num_bytes])) else: value = getattr(msg, attribute) try: value = hex(value) except: pass - print("\t\t{}:{}{}".format(attribute, " "*(30-length), value)) + print("\t\t{}:{}{}".format(attribute, " " * (30 - length), value)) print() + def open_device(index=0): device = None if enable_use_server: # ics.open_device() won't open a device if we have handles open already # so we need to find them and specify which ones to connect to. devices = ics.find_devices() - print("Opening Device {} (Open Client handles: {})...".format(dev_name(devices[index]), devices[index].NumberOfClients)) + print( + "Opening Device {} (Open Client handles: {})...".format( + dev_name(devices[index]), devices[index].NumberOfClients + ) + ) ics.open_device(devices[index]) device = devices[index] else: @@ -47,6 +54,7 @@ def open_device(index=0): print("Opened Device %s." % dev_name(device)) return device + # Iso15765 Fuctions ######################################################### def transmit_iso15765_msg(device, netid=ics.NETID_HSCAN, is_canfd=False): number_of_bytes = 64 @@ -59,8 +67,8 @@ def transmit_iso15765_msg(device, netid=ics.NETID_HSCAN, is_canfd=False): msg.fc_id = 0x7E8 msg.fc_id_mask = 0xFFF msg.flowControlExtendedAddress = 0xFE - msg.fs_timeout = 0x10 # ms - msg.fs_wait = 0x3000 # ms + msg.fs_timeout = 0x10 # ms + msg.fs_wait = 0x3000 # ms msg.blockSize = 0 msg.stMin = 0 # paddingEnable @@ -73,16 +81,17 @@ def transmit_iso15765_msg(device, netid=ics.NETID_HSCAN, is_canfd=False): msg.tx_dl = 1 # Data my_data = [x for x in range(number_of_bytes)] - msg.data = (ctypes.c_ubyte*len(msg.data))(*my_data) + msg.data = (ctypes.c_ubyte * len(msg.data))(*my_data) # Transmit the message print("Transmitting iso15765 message on {}...".format(dev_name(device))) ics.iso15765_transmit_message(device, netid, msg, 3000) # Wait for the messages to be transmitted, this can be calculated a lot better but works here. - time.sleep((((number_of_bytes/8)*msg.fs_timeout)/1000.0)+0.5) - #print_message(msg) + time.sleep((((number_of_bytes / 8) * msg.fs_timeout) / 1000.0) + 0.5) + # print_message(msg) print("Transmitted iso15765 message on {}.".format(dev_name(device))) + def setup_rx_iso15765_msg(device, netid=ics.NETID_HSCAN, is_canfd=False): msg = ics.st_cm_iso157652_rx_message.st_cm_iso157652_rx_message() @@ -106,27 +115,29 @@ def setup_rx_iso15765_msg(device, netid=ics.NETID_HSCAN, is_canfd=False): print("Setting up iso15765 message on {}...".format(dev_name(device))) ics.iso15765_receive_message(device, netid, msg) print("Setup iso15765 message on {}.".format(dev_name(device))) - + def get_iso15765_msgs(device): msgs, error_count = ics.get_messages(device) print("Received {} messages with {} errors.".format(len(msgs), error_count)) for i, m in enumerate(msgs): - print('Message #{}\t'.format(i+1), end='') + print("Message #{}\t".format(i + 1), end="") print_message(m) - + + if __name__ == "__main__": import time + netid = ics.NETID_HSCAN - + tx_device = open_device(0) rx_device = open_device(1) - + ics.iso15765_enable_networks(tx_device, netid) ics.iso15765_enable_networks(rx_device, netid) setup_rx_iso15765_msg(rx_device) transmit_iso15765_msg(tx_device) get_iso15765_msgs(rx_device) - + ics.iso15765_disable_networks(tx_device) ics.iso15765_disable_networks(rx_device) diff --git a/examples/lin_settings_example.py b/examples/lin_settings_example.py index c62e808d3..a46a4eb0f 100644 --- a/examples/lin_settings_example.py +++ b/examples/lin_settings_example.py @@ -43,9 +43,7 @@ def get_device_specific_settings(s: s_device_settings) -> object: setting_map[e_device_settings_type.DeviceOBD2LCSettingsType] = "obd2lc" if s.DeviceSettingType not in setting_map: - raise KeyError( - f"Error: {s.DeviceSettingType} is not a known type in setting_map" - ) + raise KeyError(f"Error: {s.DeviceSettingType} is not a known type in setting_map") return getattr(s.Settings, setting_map[s.DeviceSettingType]) @@ -69,9 +67,7 @@ def print_settings(device_specific_settings): try: # Open the first device device = ics.open_device() - print( - f"Opened Device {dev_name(device)} (Open Client handles: {device.NumberOfClients})..." - ) + print(f"Opened Device {dev_name(device)} (Open Client handles: {device.NumberOfClients})...") except ics.RuntimeError as ex: print(f"Failed to open first device: {ex}") exit(1) diff --git a/examples/open_device_example.py b/examples/open_device_example.py index edcee52cb..826e9a673 100644 --- a/examples/open_device_example.py +++ b/examples/open_device_example.py @@ -4,20 +4,26 @@ # with neoVI Server enabled so we can successfully open devices enable_use_server = True + def dev_name(device): # Return a friendly name of the device (ie. neoVI FIRE2 CY1234) if int("0A0000", 36) <= device.SerialNumber <= int("ZZZZZZ", 36): return device.Name + " " + ics.base36enc(device.SerialNumber) else: return device.Name + " " + str(device.SerialNumber) - + + def open_device(index=0): device = None if enable_use_server: # ics.open_device() won't open a device if we have handles open already # so we need to find them and specify which ones to connect to. devices = ics.find_devices() - print("Opening Device {} (Open Client handles: {})...".format(dev_name(devices[index]), devices[index].NumberOfClients)) + print( + "Opening Device {} (Open Client handles: {})...".format( + dev_name(devices[index]), devices[index].NumberOfClients + ) + ) ics.open_device(devices[index]) device = devices[index] else: @@ -25,8 +31,8 @@ def open_device(index=0): device = ics.open_device() print("Opened Device %s." % dev_name(device)) return device - - + + if __name__ == "__main__": # Lets figure out how many are connected to the PC and display it connected_count = len(ics.find_devices()) @@ -37,4 +43,4 @@ def open_device(index=0): # the device will automatically close here # because the device object is going out of # scope. - print("Finished.") \ No newline at end of file + print("Finished.") diff --git a/examples/transmit_can_example.py b/examples/transmit_can_example.py index 84a86e334..4ec554a03 100644 --- a/examples/transmit_can_example.py +++ b/examples/transmit_can_example.py @@ -4,20 +4,26 @@ # with neoVI Server enabled so we can successfully open devices enable_use_server = True + def dev_name(device): # Return a friendly name of the device (ie. neoVI FIRE2 CY1234) if int("0A0000", 36) <= device.SerialNumber <= int("ZZZZZZ", 36): return device.Name + " " + ics.base36enc(device.SerialNumber) else: return device.Name + " " + str(device.SerialNumber) - + + def open_device(index=0): device = None if enable_use_server: # ics.open_device() won't open a device if we have handles open already # so we need to find them and specify which ones to connect to. devices = ics.find_devices() - print("Opening Device {} (Open Client handles: {})...".format(dev_name(devices[index]), devices[index].NumberOfClients)) + print( + "Opening Device {} (Open Client handles: {})...".format( + dev_name(devices[index]), devices[index].NumberOfClients + ) + ) ics.open_device(devices[index]) device = devices[index] else: @@ -25,34 +31,37 @@ def open_device(index=0): device = ics.open_device() print("Opened Device %s." % dev_name(device)) return device - + + def transmit_can(device): msg = ics.SpyMessage() - msg.ArbIDOrHeader = 0x01 # CAN Arbitration ID - msg.Data = (1,2,3,4,5,6,7,8) # Data Bytes go here - msg.NetworkID = ics.NETID_HSCAN # First channel of CAN on the device - + msg.ArbIDOrHeader = 0x01 # CAN Arbitration ID + msg.Data = (1, 2, 3, 4, 5, 6, 7, 8) # Data Bytes go here + msg.NetworkID = ics.NETID_HSCAN # First channel of CAN on the device + # msg parameter here can also be a tuple of messages ics.transmit_messages(device, msg) + def receive_can(device): msgs, error_count = ics.get_messages(device) print("Received {} messages with {} errors.".format(len(msgs), error_count)) for i, m in enumerate(msgs): - print('Message #{}\t'.format(i+1), end='') - print('\tArbID: {}\tData: {}'.format(hex(m.ArbIDOrHeader), [hex(x) for x in m.Data])) - - + print("Message #{}\t".format(i + 1), end="") + print("\tArbID: {}\tData: {}".format(hex(m.ArbIDOrHeader), [hex(x) for x in m.Data])) + + if __name__ == "__main__": import time + # Lets figure out how many are connected to the PC and display it connected_count = len(ics.find_devices()) print("Found {} connected device(s)...".format(connected_count)) - + tx_dev = open_device(0) rx_dev = open_device(1) - + transmit_can(tx_dev) receive_can(rx_dev) - + print("Finished.") diff --git a/examples/transmit_can_xtd_example.py b/examples/transmit_can_xtd_example.py index 747d0c7a8..4d2e5acbf 100644 --- a/examples/transmit_can_xtd_example.py +++ b/examples/transmit_can_xtd_example.py @@ -4,20 +4,26 @@ # with neoVI Server enabled so we can successfully open devices enable_use_server = True + def dev_name(device): # Return a friendly name of the device (ie. neoVI FIRE2 CY1234) if int("0A0000", 36) <= device.SerialNumber <= int("ZZZZZZ", 36): return device.Name + " " + ics.base36enc(device.SerialNumber) else: return device.Name + " " + str(device.SerialNumber) - + + def open_device(index=0): device = None if enable_use_server: # ics.open_device() won't open a device if we have handles open already # so we need to find them and specify which ones to connect to. devices = ics.find_devices() - print("Opening Device {} (Open Client handles: {})...".format(dev_name(devices[index]), devices[index].NumberOfClients)) + print( + "Opening Device {} (Open Client handles: {})...".format( + dev_name(devices[index]), devices[index].NumberOfClients + ) + ) ics.open_device(devices[index]) device = devices[index] else: @@ -25,38 +31,41 @@ def open_device(index=0): device = ics.open_device() print("Opened Device %s." % dev_name(device)) return device - + + def transmit_can(device): msg = ics.SpyMessage() - msg.ArbIDOrHeader = 0xFFFFFF # CAN Arbitration ID - msg.Data = (1,2,3,4,5,6,7,8) # Data Bytes go here - msg.NetworkID = ics.NETID_HSCAN # First channel of CAN on the device + msg.ArbIDOrHeader = 0xFFFFFF # CAN Arbitration ID + msg.Data = (1, 2, 3, 4, 5, 6, 7, 8) # Data Bytes go here + msg.NetworkID = ics.NETID_HSCAN # First channel of CAN on the device msg.NumberBytesHeader = 4 msg.StatusBitField = ics.SPY_STATUS_XTD_FRAME - + # msg parameter here can also be a tuple of messages ics.transmit_messages(device, msg) + def receive_can(device): msgs, error_count = ics.get_messages(device) print("Received {} messages with {} errors.".format(len(msgs), error_count)) for i, m in enumerate(msgs): if m.NetworkID != ics.NETID_HSCAN: continue - print('Message #{}\t'.format(i+1), end='') - print('\tArbID: {}\tData: {}'.format(hex(m.ArbIDOrHeader), [hex(x) for x in m.Data])) - - + print("Message #{}\t".format(i + 1), end="") + print("\tArbID: {}\tData: {}".format(hex(m.ArbIDOrHeader), [hex(x) for x in m.Data])) + + if __name__ == "__main__": import time + # Lets figure out how many are connected to the PC and display it connected_count = len(ics.find_devices()) print("Found {} connected device(s)...".format(connected_count)) - + tx_dev = open_device(0) rx_dev = open_device(1) - + transmit_can(tx_dev) receive_can(rx_dev) - + print("Finished.") diff --git a/examples/transmit_canfd_example.py b/examples/transmit_canfd_example.py index f5dd091b7..e0e6b9dc2 100644 --- a/examples/transmit_canfd_example.py +++ b/examples/transmit_canfd_example.py @@ -1,5 +1,6 @@ import ics import time + # Tells our custom open_device() function to do special behavior # with neoVI Server enabled so we can successfully open devices enable_use_server = True @@ -7,6 +8,7 @@ DATA_BYTES = tuple([x for x in range(64)]) + def are_errors_present(msg): """Helper function to detect if a message error occurred.""" error_flags = 0 @@ -49,8 +51,11 @@ def open_device(index=0): # ics.open_device() won't open a device if we have handles open already # so we need to find them and specify which ones to connect to. devices = ics.find_devices() - print("Opening Device {} (Open Client handles: {})...".format( - dev_name(devices[index]), devices[index].NumberOfClients)) + print( + "Opening Device {} (Open Client handles: {})...".format( + dev_name(devices[index]), devices[index].NumberOfClients + ) + ) ics.open_device(devices[index]) device = devices[index] else: @@ -73,38 +78,43 @@ def transmit_can(device): _, _ = ics.get_messages(device) # msg parameter here can also be a tuple of messages ics.transmit_messages(device, msg) - # Give the bus and buffers time to do their magic. + # Give the bus and buffers time to do their magic. # In a real application we should poll until we find our actual message. time.sleep(0.5) # get all the messages on this device and print out the transmitted messages - print("="*80) + print("=" * 80) print(f"Transmitted Messages on {dev_name(device)}") - print("="*80) + print("=" * 80) msgs, error_count = ics.get_messages(device) for i, m in enumerate(msgs): # Only process transmitted messages if m.StatusBitField & ics.SPY_STATUS_TX_MSG == ics.SPY_STATUS_TX_MSG: - print('Message #{}\t'.format(i+1), end='') + print("Message #{}\t".format(i + 1), end="") data = m.Data if not m.ExtraDataPtr else m.ExtraDataPtr netid = m.NetworkID | (m.NetworkID2 << 8) - print('NetID: {}\tArbID: {}\tData: {}\tErrors Present: {}'.format(hex(netid), hex(m.ArbIDOrHeader), [hex(x) for x in data], are_errors_present(m))) + print( + "NetID: {}\tArbID: {}\tData: {}\tErrors Present: {}".format( + hex(netid), hex(m.ArbIDOrHeader), [hex(x) for x in data], are_errors_present(m) + ) + ) + def receive_can(device): msgs, error_count = ics.get_messages(device) - print("="*80) + print("=" * 80) print(f"Received Messages on {dev_name(device)}") - print("="*80) + print("=" * 80) print("Received {} messages with {} errors.".format(len(msgs), error_count)) for i, m in enumerate(msgs): # Ignore transmitted messages if m.StatusBitField & ics.SPY_STATUS_TX_MSG == ics.SPY_STATUS_TX_MSG: continue - #if m.Protocol != ics.SPY_PROTOCOL_CANFD: + # if m.Protocol != ics.SPY_PROTOCOL_CANFD: # continue - print('Message #{}\t'.format(i+1), end='') + print("Message #{}\t".format(i + 1), end="") data = m.Data if not m.ExtraDataPtr else m.ExtraDataPtr netid = m.NetworkID | (m.NetworkID2 << 8) - print('NetID: {}\tArbID: {}\tData: {}'.format(hex(netid), hex(m.ArbIDOrHeader), [hex(x) for x in data])) + print("NetID: {}\tArbID: {}\tData: {}".format(hex(netid), hex(m.ArbIDOrHeader), [hex(x) for x in data])) if __name__ == "__main__": diff --git a/examples/transmit_ethernet_example.py b/examples/transmit_ethernet_example.py index fddef4656..8cf579789 100644 --- a/examples/transmit_ethernet_example.py +++ b/examples/transmit_ethernet_example.py @@ -1,5 +1,6 @@ import ics import time + # Tells our custom open_device() function to do special behavior # with neoVI Server enabled so we can successfully open devices enable_use_server = True @@ -7,6 +8,7 @@ DATA_BYTES = tuple([x for x in range(64)]) + def are_errors_present(msg): """Helper function to detect if a message error occurred.""" error_flags = 0 @@ -49,8 +51,11 @@ def open_device(index=0): # ics.open_device() won't open a device if we have handles open already # so we need to find them and specify which ones to connect to. devices = ics.find_devices() - print("Opening Device {} (Open Client handles: {})...".format( - dev_name(devices[index]), devices[index].NumberOfClients)) + print( + "Opening Device {} (Open Client handles: {})...".format( + dev_name(devices[index]), devices[index].NumberOfClients + ) + ) ics.open_device(devices[index]) device = devices[index] else: @@ -71,8 +76,24 @@ def transmit_ethernet(device): # use ARP packet # Gigalog requires this for Ethernet 10G to be detected in Vspy (0x08, 0x06) # Last two bytes are the network id - data = [0x00, 0xFC, 0x70, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, - 0xFF, 0xFF, 0x08, 0x06, netid & 0xFF, (netid >> 8) & 0xFF] + data = [ + 0x00, + 0xFC, + 0x70, + 0xFF, + 0xFF, + 0xFF, + 0xFF, + 0xFF, + 0xFF, + 0xFF, + 0xFF, + 0xFF, + 0x08, + 0x06, + netid & 0xFF, + (netid >> 8) & 0xFF, + ] # Append 62 random bytes on the end. data += [x for x in range(62)] msg.ExtraDataPtr = tuple(data) @@ -82,36 +103,41 @@ def transmit_ethernet(device): _, _ = ics.get_messages(device) # msg parameter here can also be a tuple of messages ics.transmit_messages(device, msg) - # Give the bus and buffers time to do their magic. + # Give the bus and buffers time to do their magic. # In a real application we should poll until we find our actual message. time.sleep(0.5) # get all the messages on this device and print out the transmitted messages - print("="*80) + print("=" * 80) print(f"Transmitted Messages on {dev_name(device)}") - print("="*80) + print("=" * 80) msgs, error_count = ics.get_messages(device) for i, m in enumerate(msgs): # Only process transmitted messages if m.StatusBitField & ics.SPY_STATUS_TX_MSG == ics.SPY_STATUS_TX_MSG: - print('Message #{}\t'.format(i+1), end='') + print("Message #{}\t".format(i + 1), end="") data = m.Data if not m.ExtraDataPtr else m.ExtraDataPtr netid = m.NetworkID | (m.NetworkID2 << 8) - print('NetID: {}\tArbID: {}\tData: {}\tErrors Present: {}'.format(hex(netid), hex(m.ArbIDOrHeader), [hex(x) for x in data], are_errors_present(m))) + print( + "NetID: {}\tArbID: {}\tData: {}\tErrors Present: {}".format( + hex(netid), hex(m.ArbIDOrHeader), [hex(x) for x in data], are_errors_present(m) + ) + ) + def receive_ethernet(device): msgs, error_count = ics.get_messages(device) - print("="*80) + print("=" * 80) print(f"Received Messages on {dev_name(device)}") - print("="*80) + print("=" * 80) print("Received {} messages with {} errors.".format(len(msgs), error_count)) for i, m in enumerate(msgs): # Ignore transmitted messages if m.StatusBitField & ics.SPY_STATUS_TX_MSG == ics.SPY_STATUS_TX_MSG: continue - print('Message #{}\t'.format(i+1), end='') + print("Message #{}\t".format(i + 1), end="") data = m.Data if not m.ExtraDataPtr else m.ExtraDataPtr netid = m.NetworkID | (m.NetworkID2 << 8) - print('NetID: {}\tArbID: {}\tData: {}'.format(hex(netid), hex(m.ArbIDOrHeader), [hex(x) for x in data])) + print("NetID: {}\tArbID: {}\tData: {}".format(hex(netid), hex(m.ArbIDOrHeader), [hex(x) for x in data])) if __name__ == "__main__": diff --git a/examples/transmit_lin_example.py b/examples/transmit_lin_example.py index 91a148dac..e698a8e40 100755 --- a/examples/transmit_lin_example.py +++ b/examples/transmit_lin_example.py @@ -6,20 +6,26 @@ # with neoVI Server enabled so we can successfully open devices enable_use_server = True + def dev_name(device): # Return a friendly name of the device (ie. neoVI FIRE2 CY1234) if int("0A0000", 36) <= device.SerialNumber <= int("ZZZZZZ", 36): return device.Name + " " + ics.base36enc(device.SerialNumber) else: return device.Name + " " + str(device.SerialNumber) - + + def open_device(index=0): device = None if enable_use_server: # ics.open_device() won't open a device if we have handles open already # so we need to find them and specify which ones to connect to. devices = ics.find_devices() - print("Opening Device {} (Open Client handles: {})...".format(dev_name(devices[index]), devices[index].NumberOfClients)) + print( + "Opening Device {} (Open Client handles: {})...".format( + dev_name(devices[index]), devices[index].NumberOfClients + ) + ) ics.open_device(devices[index]) device = devices[index] else: @@ -28,14 +34,16 @@ def open_device(index=0): print("Opened Device %s." % dev_name(device)) return device + def calc_checksum(msg): checksum = 0 - for byte in msg.Header[1:]+msg.Data: + for byte in msg.Header[1:] + msg.Data: checksum += byte - if (checksum > 255): + if checksum > 255: checksum -= 255 msg.Data += tuple([~checksum & 0xFF]) + def transmit_lin(msg): calc_checksum(msg) msg.NumberBytesHeader = len(msg.Header) @@ -46,6 +54,7 @@ def transmit_lin(msg): print(ex) raise ex + def prepare_message(device): msg = ics.SpyMessageJ1850() msg.StatusBitField = ics.SPY_STATUS_INIT_MESSAGE @@ -55,30 +64,33 @@ def prepare_message(device): msg.Data = (0x33, 0x44, 0x55, 0x66, 0x77, 0x88, 0x88) transmit_lin(msg) + def receive_lin(device): msgs, error_count = ics.get_messages(device) print("Received {} messages with {} errors.".format(len(msgs), error_count)) - netids = { ics.NETID_LIN: "LIN 1", ics.NETID_LIN2: "LIN 2" } + netids = {ics.NETID_LIN: "LIN 1", ics.NETID_LIN2: "LIN 2"} for i, m in enumerate(msgs): - print('\nMessage #{}: '.format(i+1), end='') + print("\nMessage #{}: ".format(i + 1), end="") netid = netids.get(m.NetworkID) if netid is not None: - print('{}'.format(netid), end='') - if (m.StatusBitField & ics.SPY_STATUS_INIT_MESSAGE): - print(' | Init', end='') + print("{}".format(netid), end="") + if m.StatusBitField & ics.SPY_STATUS_INIT_MESSAGE: + print(" | Init", end="") data_list = [] for x in m.Header[1:]: data_list.append(x) for y in m.Data: data_list.append(y) - print('\nID: {} | '.format(hex(m.Header[0])), end='') + print("\nID: {} | ".format(hex(m.Header[0])), end="") if len(data_list): checksum = data_list.pop() - print('Data: {} | '.format([hex(x) for x in data_list]), end='') - print('Checksum: {}'.format(hex(checksum))) + print("Data: {} | ".format([hex(x) for x in data_list]), end="") + print("Checksum: {}".format(hex(checksum))) + if __name__ == "__main__": import time + # Lets figure out how many are connected to the PC and display it connected_count = len(ics.find_devices()) print("Found {} connected device(s)...".format(connected_count)) diff --git a/examples/transmit_lin_ldf_example.py b/examples/transmit_lin_ldf_example.py index 955bad5c2..c937810cc 100755 --- a/examples/transmit_lin_ldf_example.py +++ b/examples/transmit_lin_ldf_example.py @@ -4,10 +4,12 @@ import os import ldfparser + def parse_ldf(): - path = os.path.join(os.path.dirname(__file__), 'lin22.ldf') + path = os.path.join(os.path.dirname(__file__), "lin22.ldf") return ldfparser.parse_ldf(path) + def dev_name(device): # Return a friendly name of the device (ie. neoVI FIRE2 CY1234) if int("0A0000", 36) <= device.SerialNumber <= int("ZZZZZZ", 36): @@ -15,28 +17,34 @@ def dev_name(device): else: return device.Name + " " + str(device.SerialNumber) + def open_device(index=0): device = None # ics.open_device() won't open a device if we have handles open already # so we need to find them and specify which ones to connect to. devices = ics.find_devices() - print("Opening Device {} (Open Client handles: {})...".format(dev_name(devices[index]), devices[index].NumberOfClients)) + print( + "Opening Device {} (Open Client handles: {})...".format( + dev_name(devices[index]), devices[index].NumberOfClients + ) + ) ics.open_device(devices[index]) device = devices[index] print("Opened Device %s." % dev_name(device)) return device + def receive_lin(device): msgs, error_count = ics.get_messages(device) print("Received {} messages with {} errors.".format(len(msgs), error_count)) - netids = { ics.NETID_LIN: "LIN 1" }#, ics.NETID_LIN2: "LIN 2" } + netids = {ics.NETID_LIN: "LIN 1"} # , ics.NETID_LIN2: "LIN 2" } for i, m in enumerate(msgs): netid = netids.get(m.NetworkID) if netid is not None: - #print('\nMessage #{}: '.format(i+1), end='') - print('{}'.format(netid), end='') - if (m.StatusBitField & ics.SPY_STATUS_INIT_MESSAGE): - print(' | Init') + # print('\nMessage #{}: '.format(i+1), end='') + print("{}".format(netid), end="") + if m.StatusBitField & ics.SPY_STATUS_INIT_MESSAGE: + print(" | Init") data_list = [] for x in m.Header[1:]: data_list.append(x) @@ -45,39 +53,40 @@ def receive_lin(device): try: frame_name = ldf.get_frame(m.Header[0] & 0x3F).name if frame_name is not None: - print('{} | '.format(frame_name), end='') + print("{} | ".format(frame_name), end="") except: pass - print('ID: {} | '.format(hex(m.Header[0])), end='') + print("ID: {} | ".format(hex(m.Header[0])), end="") if len(data_list): checksum = data_list.pop() - print('Data: {} | '.format([hex(x) for x in data_list]), end='') - print('Checksum: {}'.format(hex(checksum))) + print("Data: {} | ".format([hex(x) for x in data_list]), end="") + print("Checksum: {}".format(hex(checksum))) print() return True + def send_frame(self, baudrate: int, frame_id: int, data: bytearray, netid: int, is_commander: bool): # set baudrate with device settings? msg = ics.SpyMessageJ1850() - if(is_commander): + if is_commander: msg.StatusBitField = ics.SPY_STATUS_INIT_MESSAGE msg.Protocol = ics.SPY_PROTOCOL_LIN msg.NetworkID = netid header_bytes = [frame_id] frame_bytes = [] - if(len(data)): + if len(data): hdr_len = min(len(data), 2) data_len = min((len(data) - hdr_len), 6) checksum = 0 - if(hdr_len > 0): + if hdr_len > 0: header_bytes += list(data[0:hdr_len]) - if(data_len > 0): + if data_len > 0: frame_bytes += list(data[hdr_len:]) - for byte in header_bytes+frame_bytes: + for byte in header_bytes + frame_bytes: checksum += byte - if (checksum > 255): + if checksum > 255: checksum -= 255 - if(len(header_bytes) == 2): + if len(header_bytes) == 2: header_bytes.append(~checksum & 0xFF) else: frame_bytes.append(~checksum & 0xFF) @@ -92,6 +101,7 @@ def send_frame(self, baudrate: int, frame_id: int, data: bytearray, netid: int, return False return True + class LINCommander: def __init__(self, device): self.device = device @@ -100,6 +110,7 @@ def __init__(self, device): def send_commander_frame(self, baudrate: int, frame_id: int, data: bytearray): send_frame(self, baudrate, frame_id, data, ics.NETID_LIN, True) + class LINResponder: def __init__(self, device): self.device = device @@ -108,8 +119,10 @@ def __init__(self, device): def send_responder_frame(self, baudrate: int, frame_id: int, data: bytearray): send_frame(self, baudrate, frame_id, data, ics.NETID_LIN2, False) + if __name__ == "__main__": import time + ldf = parse_ldf() # Lets figure out how many are connected to the PC and display it connected_count = len(ics.find_devices()) @@ -124,28 +137,28 @@ def send_responder_frame(self, baudrate: int, frame_id: int, data: bytearray): lin_resp.frames.update({each.name: each}) for cmdr in commander_nodes.publishes_frames: - lin_cmdr.frames.update({cmdr.name: cmdr}) + lin_cmdr.frames.update({cmdr.name: cmdr}) collision_schedule = ldf.get_schedule_table("Collision_resolver") for entry in collision_schedule.schedule: - if(entry.frame is not None): - if(entry.frame.name in lin_cmdr.frames): + if entry.frame is not None: + if entry.frame.name in lin_cmdr.frames: cmdr_data = entry.frame.encode({}) lin_cmdr.send_commander_frame(ldf.baudrate, entry.frame.frame_id, cmdr_data) - elif(entry.frame.name in lin_resp.frames): + elif entry.frame.name in lin_resp.frames: resp_data = entry.frame.encode({}) lin_resp.send_responder_frame(ldf.baudrate, entry.frame.frame_id, resp_data) - time.sleep(150/1000) + time.sleep(150 / 1000) lin_cmdr.send_commander_frame(ldf.baudrate, entry.frame.frame_id, bytearray()) - time.sleep(150/1000) + time.sleep(150 / 1000) - #request_frame = ldf.get_unconditional_frame('CEM_Frm1') - #request_data = request_frame.encode({"InternalLightsRequest": 'on'}, ldf.converters) - #lin_cmdr.send_commander_frame(ldf.baudrate, request_frame.frame_id, request_data) + # request_frame = ldf.get_unconditional_frame('CEM_Frm1') + # request_data = request_frame.encode({"InternalLightsRequest": 'on'}, ldf.converters) + # lin_cmdr.send_commander_frame(ldf.baudrate, request_frame.frame_id, request_data) - #responseFrame = ldf.get_unconditional_frame('RSM_Frm1') - #responseData = responseFrame.encode({"RightIntLightsSwitch": 'off'}, ldf.converters) - #lin_resp.send_responder_frame(ldf.baudrate, responseFrame.frame_id, responseData) + # responseFrame = ldf.get_unconditional_frame('RSM_Frm1') + # responseData = responseFrame.encode({"RightIntLightsSwitch": 'off'}, ldf.converters) + # lin_resp.send_responder_frame(ldf.baudrate, responseFrame.frame_id, responseData) receive_lin(device) time.sleep(1) print("Finished.") diff --git a/extract_icsneo40_defines.py b/extract_icsneo40_defines.py index 5e29070c8..5163abe11 100644 --- a/extract_icsneo40_defines.py +++ b/extract_icsneo40_defines.py @@ -12,10 +12,11 @@ def format_file(filename, preprocessor=False): import os + processed_fname = os.path.basename(filename) name, ext = os.path.splitext(processed_fname) - processed_fname = f'{name}_processed{ext}' - #processed_fname = "icsnVC40_processed.h" + processed_fname = f"{name}_processed{ext}" + # processed_fname = "icsnVC40_processed.h" # Run it through the preprocessor # clang -E -P .\include\ics\icsnVC40.h -o output.h if preprocessor: @@ -27,8 +28,11 @@ def format_file(filename, preprocessor=False): shutil.copy(str(original_path), str(new_path)) # Format the file - result = run(["clang-format", "-i", "--style", - "{BasedOnStyle: Mozilla, ColumnLimit: '200'}", processed_fname], stdout=PIPE, stderr=PIPE) + result = run( + ["clang-format", "-i", "--style", "{BasedOnStyle: Mozilla, ColumnLimit: '200'}", processed_fname], + stdout=PIPE, + stderr=PIPE, + ) result.check_returncode() return processed_fname @@ -36,7 +40,7 @@ def format_file(filename, preprocessor=False): def extract(): use_internal = False - if os.path.isfile('include/ics/icsnVC40Internal.h'): + if os.path.isfile("include/ics/icsnVC40Internal.h"): use_internal = True print("Using Internal Header!") @@ -48,103 +52,122 @@ def extract(): """ # write the header file first - with open('include/setup_module_auto_defines.h', 'w') as f: + with open("include/setup_module_auto_defines.h", "w") as f: print("#ifndef __SETUP_MODULE_AUTO_DEFINES_H__", file=f) print("#define __SETUP_MODULE_AUTO_DEFINES_H__", file=f) if use_internal: print("\n#ifndef _USE_INTERNAL_HEADER_\n#define _USE_INTERNAL_HEADER_\n#endif\n", file=f) - print('#include ', file=f) + print("#include ", file=f) print("\nint setup_module_auto_defines(PyObject * module);\n", file=f) print("#endif // __SETUP_MODULE_AUTO_DEFINES_H__", file=f) - ignores = ('(', '#endif', '#define', 'icscm_', 'GCC_MODIFIER', 'VS_MODIFIER', - '{', 'ICSNVC40_H', 'ICSNVC40INTERNAL__H_', 'SYellowSettings_SIZE', 'IS_64BIT_SYSTEM') + ignores = ( + "(", + "#endif", + "#define", + "icscm_", + "GCC_MODIFIER", + "VS_MODIFIER", + "{", + "ICSNVC40_H", + "ICSNVC40INTERNAL__H_", + "SYellowSettings_SIZE", + "IS_64BIT_SYSTEM", + ) use_enums = True - with open('src/setup_module_auto_defines.cpp', 'w') as f: + with open("src/setup_module_auto_defines.cpp", "w") as f: print(boiler_plate, file=f) # Include the header files needed for the defines - print("#include \"setup_module_auto_defines.h\"\n#include \n#include \"ics/icsnVC40.h\"", file=f) + print('#include "setup_module_auto_defines.h"\n#include \n#include "ics/icsnVC40.h"', file=f) if use_internal: - print("#include \"ics/icsnVC40Internal.h\"", file=f) + print('#include "ics/icsnVC40Internal.h"', file=f) print("\nint setup_module_auto_defines(PyObject * module)\n{", file=f) print("\tint result = 0;\n", file=f) fnames = [] - fnames.append(format_file('include/ics/icsnVC40.h')) + fnames.append(format_file("include/ics/icsnVC40.h")) if use_internal: - fnames.append(format_file('include/ics/icsnVC40Internal.h')) + fnames.append(format_file("include/ics/icsnVC40Internal.h")) # Let's get to work here! for header_file in fnames: # if not os.path.isfile(header_file) and 'Internal' in header_file: # # Ignore this file # continue - with open(header_file, 'r') as fname: - if 'icsnVC40Internal' in header_file: - print("\n#ifdef _USE_INTERNAL_HEADER_ /* ALL THESE DEFINES ARE SPECIFIED IN THE INTERNAL HEADER */\n", file=f) + with open(header_file, "r") as fname: + if "icsnVC40Internal" in header_file: + print( + "\n#ifdef _USE_INTERNAL_HEADER_ /* ALL THESE DEFINES ARE SPECIFIED IN THE INTERNAL HEADER */\n", + file=f, + ) inside_enum = False inside_comment = False line_number = 0 for line in fname: line_number += 1 - if line.lstrip().startswith('//'): + if line.lstrip().startswith("//"): continue - if inside_enum and '}' in line: + if inside_enum and "}" in line: inside_enum = False if use_enums: - print('\t// end of enum - ', line, file=f) + print("\t// end of enum - ", line, file=f) continue - elif inside_comment and '*/' in line: + elif inside_comment and "*/" in line: inside_comment = False continue - elif inside_enum and not '{' in line: + elif inside_enum and not "{" in line: sline = line.split() if not sline: continue if any(x in sline[0] for x in ignores): continue if use_enums: - if ',' in sline[0]: + if "," in sline[0]: # This removes anything after the comma as we don't need it - sline[0] = sline[0].split(',')[0] + sline[0] = sline[0].split(",")[0] # This removes anything after the equal sign as we don't need it - sline[0] = sline[0].split('=')[0] - print('\tresult += PyModule_AddIntMacro(module, %s);' % sline[0].replace(',', ''), file=f) + sline[0] = sline[0].split("=")[0] + print("\tresult += PyModule_AddIntMacro(module, %s);" % sline[0].replace(",", ""), file=f) continue - if '#define' in line: - sline = line.split('//')[0].split() + if "#define" in line: + sline = line.split("//")[0].split() # DEBUG: print('\t\t' + str(line_number) + '\t' + str(sline)) if any(x in sline[1] for x in ignores): continue if len(sline) >= 3 and re.match("^\d+?\.\d+?$", sline[2]) is not None: # Value is a float print( - '\tresult += PyModule_AddObject(module, "{0}", PyFloat_FromDouble({0}));'.format(sline[1]), file=f) + '\tresult += PyModule_AddObject(module, "{0}", PyFloat_FromDouble({0}));'.format( + sline[1] + ), + file=f, + ) elif len(sline) == 2: # There is no value, this is used for preprocessor only # and really shouldn't care about it in python. Going to set it as 0 "just in case" print( '\tresult += PyModule_AddObject(module, "{}", PyLong_FromLong(0));'.format(sline[1]), - file=f) + file=f, + ) else: - print('\tresult += PyModule_AddIntMacro(module, %s);' % sline[1], file=f) + print("\tresult += PyModule_AddIntMacro(module, %s);" % sline[1], file=f) - elif '/*' in line: + elif "/*" in line: inside_comment = True continue - elif 'enum' in line.split('//')[0]: + elif "enum" in line.split("//")[0]: inside_enum = True if use_enums: - print('\t// enum', file=f) - if '{' in line and '};' in line: + print("\t// enum", file=f) + if "{" in line and "};" in line: # Special Case here - sline = "".join(line[line.find("{")+1:line.find("}")].split()).split(',') + sline = "".join(line[line.find("{") + 1 : line.find("}")].split()).split(",") # Remove =X assignments if present. - sline = [x.split('=')[0] for x in sline] + sline = [x.split("=")[0] for x in sline] for e in sline: - print('\tresult += PyModule_AddIntMacro(module, %s);' % e, file=f) + print("\tresult += PyModule_AddIntMacro(module, %s);" % e, file=f) inside_enum = False continue - if 'icsnVC40Internal' in header_file: + if "icsnVC40Internal" in header_file: print("\n#endif // _USE_INTERNAL_HEADER_\n", file=f) print("\n\treturn result == 0 ? 1 : 0;\n}", file=f) diff --git a/generate_icsneo40_structs.py b/generate_icsneo40_structs.py index f4829d7e3..128ff0ef6 100644 --- a/generate_icsneo40_structs.py +++ b/generate_icsneo40_structs.py @@ -48,16 +48,16 @@ def __init__(self, name, data_type, array_length, bitfield_size, enum_value=None self.is_enum = bool(self.enum_value) def __repr__(self): - return f'<{self.__class__.__name__} {self.name} {self.data_type} @ {hex(id(self))}>' + return f"<{self.__class__.__name__} {self.name} {self.data_type} @ {hex(id(self))}>" def to_ordered_dict(self): od = OrderedDict() - od['name'] = self.name - od['data_type'] = self.data_type - od['array_length'] = self.array_length - od['bitfield_size'] = self.bitfield_size - od['is_enum'] = self.is_enum - od['enum_value'] = self.enum_value + od["name"] = self.name + od["data_type"] = self.data_type + od["array_length"] = self.array_length + od["bitfield_size"] = self.bitfield_size + od["is_enum"] = self.is_enum + od["enum_value"] = self.enum_value return od @@ -81,44 +81,44 @@ def __repr__(self): if self.names: name = self.names[-1] else: - name = 'Anon' + name = "Anon" if self.data_type == DataType.Struct: - t_name = 'Struct' + t_name = "Struct" elif self.data_type == DataType.Union: - t_name = 'Union' + t_name = "Union" elif self.data_type == DataType.Enum: - t_name = 'Enum' + t_name = "Enum" else: - t_name = 'Unknown' + t_name = "Unknown" - return f'<{self.__class__.__name__} {name} {t_name} {len(self.members)} members @ {hex(id(self))}>' + return f"<{self.__class__.__name__} {name} {t_name} {len(self.members)} members @ {hex(id(self))}>" def to_ordered_dict(self): od = OrderedDict() if self.data_type == DataType.Struct: - t_name = 'Struct' + t_name = "Struct" elif self.data_type == DataType.Union: - t_name = 'Union' + t_name = "Union" elif self.data_type == DataType.Enum: - t_name = 'Enum' + t_name = "Enum" else: - t_name = 'Unknown' + t_name = "Unknown" - od['names'] = self.names - od['data_type'] = t_name - od['packing'] = self.packing - od['is_anonymous'] = self.is_anonymous - od['members'] = [] + od["names"] = self.names + od["data_type"] = t_name + od["packing"] = self.packing + od["is_anonymous"] = self.is_anonymous + od["members"] = [] for member in self.members: - od['members'].append(member.to_ordered_dict()) + od["members"].append(member.to_ordered_dict()) return od def assign_preferred_name(self, is_embedded=False): """This assigns a name to the object if we are nameless and anonymous, safe to call multiple times.""" self.preferred_name = get_preferred_struct_name(self.names) # Any object that starts with _ won't be imported with import * statement so lets push it to the end - if self.preferred_name and self.preferred_name.startswith('_'): + if self.preferred_name and self.preferred_name.startswith("_"): modified_name = reverse_leading_underscores(self.preferred_name) self.names.append(modified_name) self.preferred_name = get_preferred_struct_name(self.names) @@ -128,9 +128,7 @@ def assign_preferred_name(self, is_embedded=False): self.preferred_name = convert_to_snake_case(self.preferred_name) -_start_of_obj_blacklist = ( - re.compile(r'''struct [aA-zZ\\_]+ [aA-zZ\\_]+;'''), # struct some_random_struct_name value; -) +_start_of_obj_blacklist = (re.compile(r"""struct [aA-zZ\\_]+ [aA-zZ\\_]+;"""),) # struct some_random_struct_name value; def is_line_start_of_object(line): @@ -138,7 +136,7 @@ def is_line_start_of_object(line): for regex in _start_of_obj_blacklist: if bool(regex.search(line)): return False - return bool(re.search('\btypedef struct$|struct$|struct \S*$|enum$|enum |union$|union ', line)) + return bool(re.search("\btypedef struct$|struct$|struct \S*$|enum$|enum |union$|union ", line)) # This contains all the objects that don't pass convert_to_ctype_object @@ -175,16 +173,16 @@ def parse_object(f, pos=-1, pack_size=None, is_embedded=False): new_obj = CObject() new_obj.packing = pack_size # Grab the object name - name = re.sub('typedef|struct|enum|union|\{|\s*', '', line) + name = re.sub("typedef|struct|enum|union|\{|\s*", "", line) # Only append the name if its not anonymous if name: new_obj.names.append(name) # Determine the type of object - if 'struct' in line: + if "struct" in line: new_obj.data_type = DataType.Struct - elif 'union' in line: + elif "union" in line: new_obj.data_type = DataType.Union - elif 'enum' in line: + elif "enum" in line: new_obj.data_type = DataType.Enum else: new_obj.data_type = DataType.Unknown @@ -204,15 +202,15 @@ def parse_object(f, pos=-1, pack_size=None, is_embedded=False): embedded_object = parse_object(f, -1, pack_size, True) new_obj.members.append(embedded_object) continue - opening_bracket_count += line.count('{') - opening_bracket_count -= line.count('}') - assert (opening_bracket_count >= 0) + opening_bracket_count += line.count("{") + opening_bracket_count -= line.count("}") + assert opening_bracket_count >= 0 # Determine if we are at the end of the struct - if opening_bracket_count == 0 and re.match('}.*;', line): - extra_names = ''.join(line.split()).strip('};').split(',') + if opening_bracket_count == 0 and re.match("}.*;", line): + extra_names = "".join(line.split()).strip("};").split(",") try: # Remove dangling empty string - extra_names.remove('') + extra_names.remove("") except ValueError: pass if extra_names: @@ -221,7 +219,7 @@ def parse_object(f, pos=-1, pack_size=None, is_embedded=False): finished = True break # Nothing to do with this line anymore - if re.match('.*{.*', line): + if re.match(".*{.*", line): continue # Parse the member if new_obj.data_type == DataType.Enum: @@ -250,9 +248,9 @@ def parse_object(f, pos=-1, pack_size=None, is_embedded=False): def reverse_leading_underscores(value: str): """Take a string starting with underscores and moves them to the end. Returns a string""" - if value.startswith('_'): - underscore_count = len(value) - len(value.lstrip('_')) - return value.lstrip('_') + '_'*underscore_count + if value.startswith("_"): + underscore_count = len(value) - len(value.lstrip("_")) + return value.lstrip("_") + "_" * underscore_count # We didn't have underscores in the value return value @@ -277,61 +275,60 @@ def parse_struct_member(buffered_line): # for line in buffered_line.split('\n'): # new_buffered_line += re.sub('{|union|}|;', '', line) + '\n' # buffered_line = new_buffered_line - buffered_line = re.sub("\s*\[", "[", ' '.join(buffered_line.split())) + buffered_line = re.sub("\s*\[", "[", " ".join(buffered_line.split())) # print("DEBUG AFTER:", buffered_line) # Figure out if we are an array type and get the array length - array_subsection = re.search('\[.*\]', buffered_line) + array_subsection = re.search("\[.*\]", buffered_line) is_array = array_subsection is not None if is_array: - array_length = int(eval(array_subsection.group(0).strip('[]'))) + array_length = int(eval(array_subsection.group(0).strip("[]"))) else: array_length = 0 # Remove the array portion - buffered_line = re.sub('\[.*\]', '', buffered_line) + buffered_line = re.sub("\[.*\]", "", buffered_line) # split up the remaining words = buffered_line.split() if not len(words): - return None, '', 0, 0 # data_type, array_length, bitwise_length - if ':' in words: + return None, "", 0, 0 # data_type, array_length, bitwise_length + if ":" in words: # we are a bitfield ;( try: - bitwise_length = int( - re.search('\d*', words[words.index(":")+1]).group(0)) + bitwise_length = int(re.search("\d*", words[words.index(":") + 1]).group(0)) except Exception as ex: if debug_print: print("EXCEPTION:", ex) bitwise_length = 0 # see if we get a valid ctype object before : to check for things like "unsigned : 31;" - pre_colon_text = ' '.join(words[:words.index(":")]) + pre_colon_text = " ".join(words[: words.index(":")]) check_data_type = convert_to_ctype_object(pre_colon_text) if check_data_type: - data_name = '' + data_name = "" data_type = pre_colon_text else: - data_name_index = words.index(":")-1 + data_name_index = words.index(":") - 1 data_name = words[data_name_index] - data_type = ' '.join(words[0:data_name_index]) + data_type = " ".join(words[0:data_name_index]) else: bitwise_length = 0 data_name = words[-1] - data_type = ' '.join(words[0:len(words)-1]) - if data_name.startswith('*'): - data_type += ' *' - data_name = data_name.lstrip('*') + data_type = " ".join(words[0 : len(words) - 1]) + if data_name.startswith("*"): + data_type += " *" + data_name = data_name.lstrip("*") # DEBUG: ['uint8_t', 'MACAddress[6];'] # print("DEBUG:", words, buffered_line) # remove stuff that shouldn't be in the name - data_name = re.sub('{|{|}|\s*', '', data_name) - data_type = re.sub('union|{|{|}|^struct', '', data_type) + data_name = re.sub("{|{|}|\s*", "", data_name) + data_type = re.sub("union|{|{|}|^struct", "", data_type) data_type = data_type.strip() if not data_type: - data_name = '' + data_name = "" # Any object that starts with _ won't be imported with import * statement so lets push it to the end - if data_type.startswith('_') and not convert_to_ctype_object(data_type): + if data_type.startswith("_") and not convert_to_ctype_object(data_type): data_type = reverse_leading_underscores(data_type) - return re.sub('\[.*\]|;', '', data_name), data_type, array_length, bitwise_length + return re.sub("\[.*\]|;", "", data_name), data_type, array_length, bitwise_length def parse_enum_member(buffered_line): @@ -339,34 +336,34 @@ def parse_enum_member(buffered_line): # VARIABLE_NAME = 0, # remove all unneeded whitespace - buffered_line = re.sub("\s*\[", "[", ' '.join(buffered_line.split())) + buffered_line = re.sub("\s*\[", "[", " ".join(buffered_line.split())) - if '=' in buffered_line: - name = buffered_line.split('=')[0] - value = buffered_line.split('=')[1] - value = re.sub('{|{|}|,|\s*', '', value) + if "=" in buffered_line: + name = buffered_line.split("=")[0] + value = buffered_line.split("=")[1] + value = re.sub("{|{|}|,|\s*", "", value) try: value = int(value) except ValueError as ex: - if '0X' in value.upper(): + if "0X" in value.upper(): value = int(value, 16) - elif '0B' in value.upper(): + elif "0B" in value.upper(): value = int(value, 2) else: - name = re.sub(',', '', buffered_line) + name = re.sub(",", "", buffered_line) value = None return name, value def get_struct_name_from_header(line): # line.split('struct ')[-1] - struct_name = re.sub('typedef|struct|enum|union|\{|\s*', '', line) + struct_name = re.sub("typedef|struct|enum|union|\{|\s*", "", line) if not struct_name: # == 'typedef struct': anonymous_struct = True - struct_name = 'anonymous' - elif '{' == struct_name: + struct_name = "anonymous" + elif "{" == struct_name: anonymous_struct = True - struct_name = 'anonymous' + struct_name = "anonymous" else: anonymous_struct = False return struct_name, anonymous_struct @@ -378,12 +375,14 @@ def get_struct_names(data): # key = the "key" in the data # values = list of other names for name in data.keys(): - if name in ('names', 'pack'): + if name in ("names", "pack"): continue - if 'names' in data[name]: - names[name] = data[name]['names'] + if "names" in data[name]: + names[name] = data[name]["names"] else: - names[name] = [name, ] + names[name] = [ + name, + ] return names @@ -416,9 +415,9 @@ def get_preferred_struct_name(_names): def convert_to_snake_case(name): # return name - s1 = re.sub('(.)([A-Z][a-z]+)', r'\1_\2', name) - s2 = re.sub('([a-z0-9])([A-Z])', r'\1_\2', s1).lower() - return re.sub(r'(_)\1{1,}', '_', s2) + s1 = re.sub("(.)([A-Z][a-z]+)", r"\1_\2", name) + s2 = re.sub("([a-z0-9])([A-Z])", r"\1_\2", s1).lower() + return re.sub(r"(_)\1{1,}", "_", s2) def convert_to_ctype_object(data_type): @@ -431,37 +430,52 @@ def convert_to_ctype_object(data_type): "c_short": ("short",), "c_ushort": ("unsigned short",), "c_int": ("int",), - "c_uint": ("unsigned", "unsigned int",), + "c_uint": ( + "unsigned", + "unsigned int", + ), "c_long": ("long",), "c_ulong": ("unsigned long",), - "c_longlong": ("__int64", "long long",), - "c_ulonglong": ("unsigned __int64", "unsigned long long",), + "c_longlong": ( + "__int64", + "long long", + ), + "c_ulonglong": ( + "unsigned __int64", + "unsigned long long", + ), "c_size_t": ("size_t",), - "c_ssize_t": ("ssize_t", "Py_ssize_t",), + "c_ssize_t": ( + "ssize_t", + "Py_ssize_t", + ), "c_float": ("float",), "c_double": ("double",), - "c_void_p": ("void*", "void *",), + "c_void_p": ( + "void*", + "void *", + ), } # Add all the intX_t types for d in [8, 16, 32, 64]: - ctype_types[f'c_int{d}'] = (f'int{d}_t',) - ctype_types[f'c_uint{d}'] = (f'uint{d}_t',) + ctype_types[f"c_int{d}"] = (f"int{d}_t",) + ctype_types[f"c_uint{d}"] = (f"uint{d}_t",) # This is dirty but we don't parse typedefs... ctype_types["c_uint16"] = ctype_types["c_uint16"] + ("descIdType",) ctype_types["c_uint64"] = ctype_types["c_uint64"] + ("_clock_identity",) - is_pointer = '*' in data_type and not 'void' in data_type + is_pointer = "*" in data_type and not "void" in data_type for ctype_type, c_types in ctype_types.items(): for c_type in c_types: if is_pointer: - data_type = data_type.replace('*', '') + data_type = data_type.replace("*", "") if c_type == data_type: try: t = f"ctypes.{ctype_type}" eval(t) if is_pointer: - t = f'ctypes.POINTER({t})' + t = f"ctypes.POINTER({t})" return t except AttributeError as ex: return None @@ -470,34 +484,40 @@ def convert_to_ctype_object(data_type): def format_file(filename): import os + processed_fname = os.path.basename(filename) name, ext = os.path.splitext(processed_fname) - processed_fname = f'{name}_processed{ext}' + processed_fname = f"{name}_processed{ext}" # processed_fname = "icsnVC40_processed.h" # Run it through the preprocessor # clang -E -P .\include\ics\icsnVC40.h -o output.h - result = run(["clang", "-DEXTERNAL_PROJECT", "-E", "-P", filename, "-o", processed_fname], stdout=PIPE, stderr=STDOUT) + result = run( + ["clang", "-DEXTERNAL_PROJECT", "-E", "-P", filename, "-o", processed_fname], stdout=PIPE, stderr=STDOUT + ) try: result.check_returncode() except CalledProcessError as ex: print(f"ERROR: {' '.join(result.args)} failed with error code {ex.returncode}") - print(ex.stdout.decode('UTF-8')) - #print(ex.stderr) + print(ex.stdout.decode("UTF-8")) + # print(ex.stderr) # Format the file - result = run(["clang-format", "-i", "--style", - "{BasedOnStyle: Mozilla, ColumnLimit: '200'}", processed_fname], stdout=PIPE, stderr=STDOUT) + result = run( + ["clang-format", "-i", "--style", "{BasedOnStyle: Mozilla, ColumnLimit: '200'}", processed_fname], + stdout=PIPE, + stderr=STDOUT, + ) try: result.check_returncode() except CalledProcessError as ex: print(f"ERROR: {' '.join(result.args)} failed with error code {ex.returncode}") - print(ex.stdout.decode('UTF-8')) + print(ex.stdout.decode("UTF-8")) return processed_fname def parse_header_file(filename): - with open(filename, 'r') as f: + with open(filename, "r") as f: pack_size = 0 line_count = 0 last_pos = f.tell() @@ -511,20 +531,20 @@ def parse_header_file(filename): line = line.strip() line_count += 1 # Remove all unneeded whitespace - line = ' '.join(line.split()) + line = " ".join(line.split()) # Remove preprocessor statements if line.startswith("#"): # get the pack size - if re.match('#pragma.*pack.*.*pop.*', line): + if re.match("#pragma.*pack.*.*pop.*", line): if pack_size_stack: pack_size = pack_size_stack.pop() else: pack_size = 0 - elif re.match('#pragma.*pack.*.*push.*', line) or re.match('#pragma.*pack\(\d\)', line): - pushing = 'push' in line + elif re.match("#pragma.*pack.*.*push.*", line) or re.match("#pragma.*pack\(\d\)", line): + pushing = "push" in line try: last = pack_size - pack_size = int(re.search('\d{1,}', line).group(0)) + pack_size = int(re.search("\d{1,}", line).group(0)) if pushing: pack_size_stack.append(last) except AttributeError: @@ -533,20 +553,24 @@ def parse_header_file(filename): pack_size_stack.append(pack_size) if debug_print: print("PACK SIZE:", pack_size) - elif re.match('#define.*', line) and len(line.split(' ')) == 3 and not '\\' in line and not 'sizeof' in line: + elif ( + re.match("#define.*", line) + and len(line.split(" ")) == 3 + and not "\\" in line + and not "sizeof" in line + ): # preprocessor define that can be used as a number in array sizes... # we are going to hack the variable into the module's globals so we can eval() it later - words = line.split(' ') + words = line.split(" ") if debug_print: - print("ADDING {} to globals with value of {}".format( - words[1], words[2])) + print("ADDING {} to globals with value of {}".format(words[1], words[2])) try: globals()[words[1]] = eval(words[2]) except SyntaxError as ex: # This happens when we have an integer literal # https://en.cppreference.com/w/cpp/language/integer_literal # TODO: 0x1p5 - literals = ('u', 'U', 'l', 'L', 'z', 'Z', 'f', 'F') + literals = ("u", "U", "l", "L", "z", "Z", "f", "F") modified_word = words[2] while modified_word.endswith(literals): for literal in literals: @@ -578,10 +602,11 @@ def parse_header_file(filename): return c_objects, enum_objects -def generate(filename='include/ics/icsnVC40.h'): +def generate(filename="include/ics/icsnVC40.h"): import shutil import json import os + basename = os.path.basename(filename) filename = format_file(filename) c_objects, enum_objects = parse_header_file(filename) @@ -593,30 +618,57 @@ def generate(filename='include/ics/icsnVC40.h'): for enum_object in enum_objects: enum_objects_converted.append(enum_object.to_ordered_dict()) j = json.dumps(c_objects_converted, indent=4, sort_keys=False) - with open(f'{basename}.json', 'w+') as f: + with open(f"{basename}.json", "w+") as f: f.write(j) j = json.dumps(enum_objects_converted, indent=4, sort_keys=False) - with open(f'{basename}.enums.json', 'w+') as f: + with open(f"{basename}.enums.json", "w+") as f: f.write(j) # generate the python files - output_dir = './ics/structures' + output_dir = "./ics/structures" print(f"Removing {output_dir}...") try: shutil.rmtree(output_dir) except FileNotFoundError: pass ignore_names = [ - '__fsid_t', '__darwin_pthread_handler_rec', - '_mbstate_t', 'mbstate_t_', 'mbstatet_', 'Mbstatet_', '_Mbstatet', - '_LONGDOUBLE', 'LONGDOUBLE_', - '_opaque_pthread_attr_t', '_opaque_pthread_cond_t', '_opaque_pthread_condattr_t', - '_opaque_pthread_mutex_t', '_opaque_pthread_mutexattr_t', '_opaque_pthread_once_t', - '_opaque_pthread_rwlock_t', '_opaque_pthread_rwlockattr_t', '_opaque_pthread_t', - 'crt_locale_pointers_', 'crt_locale_data_public_', '__crt_locale_data_public', - 'ldiv_t', 'lldiv_t', 'ldouble_', 'ldbl12_', 'div_t', 'crt_float_', 'crt_double_', - 'ndis_adapter_information', - 'NeoDevice', 'neo_device', 'NeoDeviceEx', 'neo_device_ex', - 'icsSpyMessage', 'icsSpyMessageJ1850', 'ics_spy_message', 'ics_spy_message_j1850'] + "__fsid_t", + "__darwin_pthread_handler_rec", + "_mbstate_t", + "mbstate_t_", + "mbstatet_", + "Mbstatet_", + "_Mbstatet", + "_LONGDOUBLE", + "LONGDOUBLE_", + "_opaque_pthread_attr_t", + "_opaque_pthread_cond_t", + "_opaque_pthread_condattr_t", + "_opaque_pthread_mutex_t", + "_opaque_pthread_mutexattr_t", + "_opaque_pthread_once_t", + "_opaque_pthread_rwlock_t", + "_opaque_pthread_rwlockattr_t", + "_opaque_pthread_t", + "crt_locale_pointers_", + "crt_locale_data_public_", + "__crt_locale_data_public", + "ldiv_t", + "lldiv_t", + "ldouble_", + "ldbl12_", + "div_t", + "crt_float_", + "crt_double_", + "ndis_adapter_information", + "NeoDevice", + "neo_device", + "NeoDeviceEx", + "neo_device_ex", + "icsSpyMessage", + "icsSpyMessageJ1850", + "ics_spy_message", + "ics_spy_message_j1850", + ] file_names = [] prefered_names = [] all_objects = c_objects + enum_objects @@ -654,11 +706,11 @@ def generate(filename='include/ics/icsnVC40.h'): print(f"Generated all python {len(all_objects)-ignored_enum_count} files.") # Generate __init__.py and add all the modules to __all__ - with open(os.path.join(output_dir, '__init__.py'), 'w+') as f: + with open(os.path.join(output_dir, "__init__.py"), "w+") as f: f.write("__all__ = [\n") for file_name in file_names: - fname = re.sub('(\.py)', '', file_name) - r = re.compile('(' + fname + ')') + fname = re.sub("(\.py)", "", file_name) + r = re.compile("(" + fname + ")") if list(filter(r.match, ignore_names)): # print("IGNORING:", fname) continue @@ -667,16 +719,16 @@ def generate(filename='include/ics/icsnVC40.h'): f.write('",\n') f.write("]\n") # write a hidden_import python file for pyinstaller - with open('./ics/hiddenimports.py', 'w+') as f: - f.write('hidden_imports = [\n') + with open("./ics/hiddenimports.py", "w+") as f: + f.write("hidden_imports = [\n") for file_name in file_names: - fname = re.sub('(\.py)', '', file_name) - r = re.compile('(' + fname + ')') + fname = re.sub("(\.py)", "", file_name) + r = re.compile("(" + fname + ")") if list(filter(r.match, ignore_names)): # print("IGNORING:", fname) continue f.write(f' "ics.structures.{fname}",\n') - f.write(']\n\n') + f.write("]\n\n") # Verify We can at least import all of the modules - quick check to make sure parser worked. # TODO: This is broke @@ -697,16 +749,16 @@ def generate(filename='include/ics/icsnVC40.h'): def _write_c_object(f, c_object): # Write the header if c_object.data_type == DataType.Struct: - f.write(f'class {c_object.preferred_name}(ctypes.Structure):\n') + f.write(f"class {c_object.preferred_name}(ctypes.Structure):\n") elif c_object.data_type == DataType.Union: - f.write(f'class {c_object.preferred_name}(ctypes.Union):\n') + f.write(f"class {c_object.preferred_name}(ctypes.Union):\n") elif c_object.data_type == DataType.Enum: - f.write(f'class {c_object.preferred_name}(enum.IntEnum):\n') + f.write(f"class {c_object.preferred_name}(enum.IntEnum):\n") f.write(' """A ctypes-compatible IntEnum superclass."""\n') - f.write(' @classmethod\n') - f.write(' def from_param(cls, obj):\n') - f.write(' return int(obj)\n') - f.write('\n') + f.write(" @classmethod\n") + f.write(" def from_param(cls, obj):\n") + f.write(" return int(obj)\n") + f.write("\n") else: raise ValueError("CObject is not of a known data type!") @@ -714,15 +766,15 @@ def _write_c_object(f, c_object): if c_object.data_type in (DataType.Struct, DataType.Union): # Setup the packing if c_object.packing: - f.write(f' _pack_ = {c_object.packing}\n') + f.write(f" _pack_ = {c_object.packing}\n") # Grab all the anonymous names anonymous_names = [] for member in c_object.members: if isinstance(member, CObject) and member.is_anonymous: anonymous_names.append(member.preferred_name) if anonymous_names: - f.write(f' _anonymous_ = {str(tuple(anonymous_names))}\n') - f.write(f' _fields_ = [\n') + f.write(f" _anonymous_ = {str(tuple(anonymous_names))}\n") + f.write(f" _fields_ = [\n") # Write the members for member in c_object.members: @@ -730,16 +782,16 @@ def _write_c_object(f, c_object): enum_value = member.enum_value if enum_value == None: if c_object.enum_last_value != None: - enum_value = 'enum.auto()' + enum_value = "enum.auto()" c_object.enum_last_value += 1 else: # https://docs.python.org/3/library/enum.html#enum.auto # By default, the initial value starts at 1. c_object.enum_last_value = 0 - enum_value = '0' + enum_value = "0" elif c_object.enum_last_value == None: c_object.enum_last_value = 0 - f.write(f' {member.name} = {enum_value}\n') + f.write(f" {member.name} = {enum_value}\n") else: # Struct/Union def _write_member(f, member, is_struct_or_union=False): @@ -757,7 +809,7 @@ def _write_member(f, member, is_struct_or_union=False): # C enum types can be char, unsigned, signed but seem to default to # 4 byte integer on most systems (even 64-bit) # This is a potential hole but nothing we can do here - data_type = 'ctypes.c_int32' + data_type = "ctypes.c_int32" else: data_type = member.data_type if member.bitfield_size: @@ -776,22 +828,22 @@ def _write_member(f, member, is_struct_or_union=False): # Finalize the _fields_ attribute and extra names if c_object.data_type in (DataType.Struct, DataType.Union): - f.write(f' ]\n') + f.write(f" ]\n") # Extra names here - f.write('\n\n') + f.write("\n\n") for name in c_object.names: # Ignore the actual object name if name == c_object.preferred_name: continue - f.write('{} = {}\n'.format(re.sub('^\*', '', name), c_object.preferred_name)) - f.write('\n') + f.write("{} = {}\n".format(re.sub("^\*", "", name), c_object.preferred_name)) + f.write("\n") def generate_pyfile(c_object, path): # name = get_preferred_struct_name(c_object.names) # c_object.preferred_name = convert_to_snake_case(name) # Make the fname and the path - fname = f'{c_object.preferred_name}.py' + fname = f"{c_object.preferred_name}.py" fname_with_path = os.path.normpath(os.path.join(path, fname)) # create the needed directories if not os.path.exists(os.path.split(fname_with_path)[0]): @@ -799,16 +851,16 @@ def generate_pyfile(c_object, path): os.makedirs(os.path.split(fname_with_path)[0]) except OSError as ex: import errno + if ex.errno != errno.EEXIST: # Race condition handler, if someone else makes a directory after we check if exists raise - with open(fname_with_path, 'w+') as f: + with open(fname_with_path, "w+") as f: # Write the boiler plate code - f.write( - '# This file was auto generated; Do not modify, if you value your sanity!\n') - f.write('import ctypes\n') - f.write('import enum\n') - f.write('\n') + f.write("# This file was auto generated; Do not modify, if you value your sanity!\n") + f.write("import ctypes\n") + f.write("import enum\n") + f.write("\n") # Generate all the imports def get_c_object_imports(c_object): @@ -832,15 +884,16 @@ def get_c_object_imports(c_object): return sorted(set(import_names)) import_names = get_c_object_imports(c_object) - for import_name in (import_names): + for import_name in import_names: f.write(f"from ics.structures.{import_name} import *\n") - f.write('\n\n') + f.write("\n\n") def _generate_inner_objects(f, c_object): for member in c_object.members: if isinstance(member, CObject): _generate_inner_objects(f, member) _write_c_object(f, member) + # generate all the inner objects _generate_inner_objects(f, c_object) # Finally write our main object @@ -853,16 +906,16 @@ def generate_all_files(): import os import pathlib - filenames = ('icsnVC40.h', 'icsnVC40Internal.h') + filenames = ("icsnVC40.h", "icsnVC40Internal.h") for filename in filenames: - path = pathlib.Path('include/ics/') + path = pathlib.Path("include/ics/") path = path.joinpath(filename) if path.exists(): - if 'Internal' in str(filename): + if "Internal" in str(filename): print("WARNING: Generating internal header!") print(f"Parsing {str(path)}...") generate(str(path)) -if __name__ == '__main__': +if __name__ == "__main__": generate_all_files() diff --git a/include/object_neo_device.h b/include/object_neo_device.h index 51e77194b..2570f0ac7 100644 --- a/include/object_neo_device.h +++ b/include/object_neo_device.h @@ -42,7 +42,7 @@ #define ICS_HANDLE_PY_TYPE T_INT #else #define ICS_HANDLE void* -#define ICS_HANDLE_PY_TYPE T_INT +#define ICS_HANDLE_PY_TYPE T_ULONGLONG #endif typedef struct diff --git a/pyproject.toml b/pyproject.toml index 57842c7da..ecbffedae 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -13,4 +13,19 @@ archs = ["universal2"] before-build = "brew install automake libtool cmake clang-format" [tool.cibuildwheel.windows] -before-build = "choco install llvm" \ No newline at end of file +before-build = "choco install llvm" + +[tool.black] +line-length = 120 +# https://stackoverflow.com/questions/73247204/black-not-respecting-extend-exclude-in-pyproject-toml +force-exclude = ''' +/( + | .vscode + | .venv + | build + | ics + | include + | msvc + | src +)/ +''' \ No newline at end of file diff --git a/setup.py b/setup.py index 86f2f8f64..65a3fe41c 100644 --- a/setup.py +++ b/setup.py @@ -13,16 +13,16 @@ POST_VERSION = None if POST_VERSION: - VERSION_STRING = '%d.%d-%d' % (MAJOR_VERSION, MINOR_VERSION, POST_VERSION) + VERSION_STRING = "%d.%d-%d" % (MAJOR_VERSION, MINOR_VERSION, POST_VERSION) else: - VERSION_STRING = '%d.%d' % (MAJOR_VERSION, MINOR_VERSION) + VERSION_STRING = "%d.%d" % (MAJOR_VERSION, MINOR_VERSION) def _run_tests(): - directory = os.path.abspath(os.path.dirname(sys.modules['__main__'].__file__)) + directory = os.path.abspath(os.path.dirname(sys.modules["__main__"].__file__)) loader = unittest.defaultTestLoader runner = unittest.TextTestRunner() - suite = loader.discover(os.path.join(directory, 'test')) + suite = loader.discover(os.path.join(directory, "test")) runner.run(suite) @@ -37,6 +37,7 @@ def finalize_options(self): def run_tests(self): _run_tests() + except ImportError: from distutils.core import Command @@ -57,10 +58,12 @@ class build(build_module.build): def run(self): import extract_icsneo40_defines import generate_icsneo40_structs + extract_icsneo40_defines.extract() generate_icsneo40_structs.generate_all_files() - if platform.system().upper() in ('DARWIN', 'LINUX'): + if platform.system().upper() in ("DARWIN", "LINUX"): import build_libicsneo + build_libicsneo.checkout() build_libicsneo.build() build_libicsneo.copy() @@ -68,47 +71,47 @@ def run(self): source_files = [ - 'src/object_spy_message.cpp', - 'src/defines.cpp', - 'src/exceptions.cpp', - 'src/dll.cpp', - 'src/setup_module_auto_defines.cpp', - 'src/main.cpp', - 'src/object_neo_device.cpp', - 'src/methods.cpp', - 'src/ice/src/ice_library_manager.cpp', - 'src/ice/src/ice_library_name.cpp', - 'src/ice/src/ice_library.cpp' + "src/object_spy_message.cpp", + "src/defines.cpp", + "src/exceptions.cpp", + "src/dll.cpp", + "src/setup_module_auto_defines.cpp", + "src/main.cpp", + "src/object_neo_device.cpp", + "src/methods.cpp", + "src/ice/src/ice_library_manager.cpp", + "src/ice/src/ice_library_name.cpp", + "src/ice/src/ice_library.cpp", ] # gcc and clang arguments GCC_COMPILE_ARGS = [ - '-fpermissive', - '-Wno-unused-variable', - '-Wno-unused-function', - '-Wno-write-strings', + "-fpermissive", + "-Wno-unused-variable", + "-Wno-unused-function", + "-Wno-write-strings", ] # Set compiler flags here -if 'WINDOWS' in platform.system().upper(): +if "WINDOWS" in platform.system().upper(): compile_args = [] # mingw and clang python builds won't have MSC in the version string if "MSC" not in sys.version: compile_args = GCC_COMPILE_ARGS -elif 'LINUX' in platform.system().upper(): +elif "LINUX" in platform.system().upper(): compile_args = GCC_COMPILE_ARGS -elif 'DARWIN' in platform.system().upper(): +elif "DARWIN" in platform.system().upper(): # Mac doesn't respect the compiler args, but will append with ARCHFLAGS environment variable - os.environ['ARCHFLAGS'] = '-std=c++17' + os.environ["ARCHFLAGS"] = "-std=c++17" compile_args = [] else: compile_args = [] # Check for clang stuff here, read the docs doesn't have this so use what is in the repo if not os.getenv("READTHEDOCS"): - if not shutil.which('clang'): + if not shutil.which("clang"): raise RuntimeError("clang is required for building python_ics.") - if not shutil.which('clang-format'): + if not shutil.which("clang-format"): raise RuntimeError("clang-format is required for building python_ics.") @@ -117,44 +120,49 @@ def read(fname): ics_extension = Extension( - 'ics.ics', - define_macros=[('MAJOR_VERSION', MAJOR_VERSION), - ('MINOR_VERSION', MINOR_VERSION), - ('EXTERNAL_PROJECT', 1)], - include_dirs=['include', 'include/ics', 'src/ice/include', 'src/ice/include/ice'], + "ics.ics", + define_macros=[("MAJOR_VERSION", MAJOR_VERSION), ("MINOR_VERSION", MINOR_VERSION), ("EXTERNAL_PROJECT", 1)], + include_dirs=["include", "include/ics", "src/ice/include", "src/ice/include/ice"], libraries=[], - library_dirs=['/usr/local/lib'], - sources=source_files, extra_compile_args=compile_args) + library_dirs=["/usr/local/lib"], + sources=source_files, + extra_compile_args=compile_args, +) package_data = {} -if 'DARWIN' in platform.system().upper(): - package_data['ics'] = ['*.dylib'] -elif 'LINUX' in platform.system().upper(): - package_data[''] = ['*.so'] - -setup(name='python_ics', - version=VERSION_STRING, - description='Library for interfacing with Intrepid devices in Python', - long_description=read('README.md'), - long_description_content_type='text/markdown', - license="MIT", - author='David Rebbe', - author_email='drebbe@intrepidcs.com', - maintainer='David Rebbe', - maintainer_email='drebbe@intrepidcs.com', - url='https://github.com/intrepidcs/python_ics/', - cmdclass={'build': build, 'test': UnitTests, }, - download_url='https://github.com/intrepidcs/python_ics/releases', - packages=['ics', 'ics.structures'], - package_data=package_data, - include_package_data=True, - ext_modules=[ics_extension], - classifiers=[ - 'Programming Language :: Python :: 3', - 'Programming Language :: Python :: 3.6', - 'Programming Language :: Python :: 3.7', - 'Programming Language :: Python :: 3.8', - 'Programming Language :: Python :: 3.9', - 'Programming Language :: Python :: 3.10', - 'Programming Language :: Python :: 3.11', - ],) +if "DARWIN" in platform.system().upper(): + package_data["ics"] = ["*.dylib"] +elif "LINUX" in platform.system().upper(): + package_data[""] = ["*.so"] + +setup( + name="python_ics", + version=VERSION_STRING, + description="Library for interfacing with Intrepid devices in Python", + long_description=read("README.md"), + long_description_content_type="text/markdown", + license="MIT", + author="David Rebbe", + author_email="drebbe@intrepidcs.com", + maintainer="David Rebbe", + maintainer_email="drebbe@intrepidcs.com", + url="https://github.com/intrepidcs/python_ics/", + cmdclass={ + "build": build, + "test": UnitTests, + }, + download_url="https://github.com/intrepidcs/python_ics/releases", + packages=["ics", "ics.structures"], + package_data=package_data, + include_package_data=True, + ext_modules=[ics_extension], + classifiers=[ + "Programming Language :: Python :: 3", + "Programming Language :: Python :: 3.6", + "Programming Language :: Python :: 3.7", + "Programming Language :: Python :: 3.8", + "Programming Language :: Python :: 3.9", + "Programming Language :: Python :: 3.10", + "Programming Language :: Python :: 3.11", + ], +) diff --git a/test/obsolete/cmvspy.py b/test/obsolete/cmvspy.py index 58a03d390..11c59d8b9 100644 --- a/test/obsolete/cmvspy.py +++ b/test/obsolete/cmvspy.py @@ -1,58 +1,519 @@ -#This file was automatically generated by 'cmvspyconvert.py' -#from a cmvspy.h file. -#Example usage: -# from cmvspy import data as coremini_data +# This file was automatically generated by 'cmvspyconvert.py' +# from a cmvspy.h file. +# Example usage: +# from cmvspy import data as coremini_data -data = ( \ - 0x07, 0x09, 0x13, 0x00, 0x00, 0x02, 0x2B, 0x20, 0x04, 0xD2, \ - 0xBA, 0xB4, 0x3F, 0x43, 0xFF, 0xF4, 0xBD, 0x2A, 0x75, 0xE4, \ - 0x47, 0xFA, 0xE1, 0xE4, 0xA8, 0x82, 0xCE, 0x87, 0x0E, 0xB3, \ - 0xEA, 0x7A, 0xD5, 0xF1, 0x6B, 0x2E, 0x1B, 0x8F, 0x0B, 0x82, \ - 0x17, 0xE8, 0x09, 0x4D, 0x88, 0x78, 0xED, 0xA4, 0xC1, 0x40, \ - 0x67, 0x73, 0xE3, 0xB0, 0xB6, 0xAD, 0xC6, 0x7C, 0x9D, 0x0C, \ - 0x64, 0x71, 0xF9, 0xEF, 0xD0, 0xFF, 0xD1, 0x62, 0x3A, 0x7D, \ - 0x6D, 0x31, 0x59, 0xA6, 0x9D, 0x2D, 0xB1, 0x2E, 0x3B, 0x84, \ - 0xD3, 0x53, 0x56, 0xC8, 0x18, 0x45, 0x81, 0xDB, 0x0A, 0x3D, \ - 0x6D, 0xAB, 0x06, 0x4F, 0x2D, 0x38, 0x0A, 0x3D, 0x6D, 0xAB, \ - 0x06, 0x4F, 0x2D, 0x38, 0x0A, 0x3D, 0x6D, 0xAB, 0x06, 0x4F, \ - 0x2D, 0x38, 0x0A, 0x3D, 0x6D, 0xAB, 0x06, 0x4F, 0x2D, 0x38, \ - 0x7B, 0xE6, 0x3C, 0x8F, 0x4F, 0x6D, 0xB6, 0xE5, 0x05, 0x6F, \ - 0x8C, 0xCE, 0xA4, 0x0A, 0xDC, 0x31, 0xDA, 0x52, 0x6F, 0xE6, \ - 0xE2, 0xC2, 0x3A, 0xF3, 0xA7, 0xF5, 0x30, 0x48, 0xD7, 0x91, \ - 0x22, 0x0E, 0x6E, 0x18, 0xF1, 0x05, 0xF1, 0xEB, 0xF9, 0xEF, \ - 0x93, 0x7F, 0x60, 0x67, 0x94, 0x13, 0xCF, 0x9D, 0x78, 0x8B, \ - 0xD5, 0x18, 0x06, 0xEE, 0xA4, 0xE5, 0x8D, 0xBA, 0x17, 0x22, \ - 0x0C, 0x72, 0x19, 0xD2, 0xE8, 0xC9, 0x11, 0x03, 0xEE, 0x0D, \ - 0x3B, 0x9A, 0xBD, 0x0C, 0x16, 0x28, 0x51, 0x47, 0x1A, 0x42, \ - 0x0D, 0xEA, 0xD3, 0x56, 0x72, 0x00, 0xD4, 0x55, 0xB8, 0x69, \ - 0x4C, 0xCD, 0xB9, 0x7F, 0xDB, 0x50, 0xE4, 0x67, 0xB5, 0xFC, \ - 0x7F, 0x10, 0x63, 0xF2, 0x33, 0xA1, 0xD8, 0x00, 0x4D, 0xEE, \ - 0xE8, 0x7A, 0xE0, 0xC4, 0x40, 0x0C, 0x90, 0x9A, 0xC8, 0x28, \ - 0x43, 0x86, 0x06, 0xA8, 0xC7, 0xE8, 0x38, 0xE7, 0xC4, 0x9B, \ - 0x7D, 0xC0, 0x50, 0x82, 0x27, 0x91, 0x67, 0xFF, 0x14, 0xDF, \ - 0x62, 0x49, 0x0C, 0x0F, 0x9E, 0x1A, 0xC2, 0xA7, 0xF5, 0x03, \ - 0x63, 0x15, 0x63, 0xB0, 0x10, 0x33, 0x14, 0xF9, 0xEC, 0x6A, \ - 0xAA, 0x7C, 0xB3, 0x91, 0x79, 0x5C, 0x09, 0x79, 0xDC, 0x6C, \ - 0xED, 0x97, 0x66, 0xB7, 0x49, 0xD7, 0xB5, 0x64, 0xAD, 0xCB, \ - 0x3F, 0x30, 0x8B, 0x69, 0x5F, 0xF1, 0xB5, 0x23, 0x2D, 0x14, \ - 0xE8, 0x9A, 0x2E, 0xC7, 0xFE, 0xEA, 0xBA, 0x3F, 0x4E, 0x27, \ - 0x9E, 0xDA, 0xC1, 0x57, 0xEE, 0x9B, 0x88, 0x77, 0x8D, 0xB0, \ - 0x8C, 0x55, 0x3F, 0x9C, 0xC3, 0x3F, 0xF9, 0x97, 0x59, 0xDA, \ - 0x15, 0xAA, 0xFB, 0xF6, 0xAF, 0xA4, 0x4B, 0x50, 0xC1, 0xB0, \ - 0x0A, 0x93, 0x1B, 0xF7, 0x1F, 0x44, 0xB7, 0xFD, 0x4E, 0x2B, \ - 0x54, 0xDD, 0xF2, 0x55, 0xB5, 0xC7, 0xA9, 0xF1, 0x30, 0x0B, \ - 0xAF, 0x29, 0xF8, 0xB3, 0xB0, 0x99, 0x00, 0x00, 0x00, 0x00, \ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, \ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, \ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, \ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, \ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, \ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, \ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, \ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, \ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, \ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, \ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, \ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, \ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, \ - 0x00, 0x00, ) +data = ( + 0x07, + 0x09, + 0x13, + 0x00, + 0x00, + 0x02, + 0x2B, + 0x20, + 0x04, + 0xD2, + 0xBA, + 0xB4, + 0x3F, + 0x43, + 0xFF, + 0xF4, + 0xBD, + 0x2A, + 0x75, + 0xE4, + 0x47, + 0xFA, + 0xE1, + 0xE4, + 0xA8, + 0x82, + 0xCE, + 0x87, + 0x0E, + 0xB3, + 0xEA, + 0x7A, + 0xD5, + 0xF1, + 0x6B, + 0x2E, + 0x1B, + 0x8F, + 0x0B, + 0x82, + 0x17, + 0xE8, + 0x09, + 0x4D, + 0x88, + 0x78, + 0xED, + 0xA4, + 0xC1, + 0x40, + 0x67, + 0x73, + 0xE3, + 0xB0, + 0xB6, + 0xAD, + 0xC6, + 0x7C, + 0x9D, + 0x0C, + 0x64, + 0x71, + 0xF9, + 0xEF, + 0xD0, + 0xFF, + 0xD1, + 0x62, + 0x3A, + 0x7D, + 0x6D, + 0x31, + 0x59, + 0xA6, + 0x9D, + 0x2D, + 0xB1, + 0x2E, + 0x3B, + 0x84, + 0xD3, + 0x53, + 0x56, + 0xC8, + 0x18, + 0x45, + 0x81, + 0xDB, + 0x0A, + 0x3D, + 0x6D, + 0xAB, + 0x06, + 0x4F, + 0x2D, + 0x38, + 0x0A, + 0x3D, + 0x6D, + 0xAB, + 0x06, + 0x4F, + 0x2D, + 0x38, + 0x0A, + 0x3D, + 0x6D, + 0xAB, + 0x06, + 0x4F, + 0x2D, + 0x38, + 0x0A, + 0x3D, + 0x6D, + 0xAB, + 0x06, + 0x4F, + 0x2D, + 0x38, + 0x7B, + 0xE6, + 0x3C, + 0x8F, + 0x4F, + 0x6D, + 0xB6, + 0xE5, + 0x05, + 0x6F, + 0x8C, + 0xCE, + 0xA4, + 0x0A, + 0xDC, + 0x31, + 0xDA, + 0x52, + 0x6F, + 0xE6, + 0xE2, + 0xC2, + 0x3A, + 0xF3, + 0xA7, + 0xF5, + 0x30, + 0x48, + 0xD7, + 0x91, + 0x22, + 0x0E, + 0x6E, + 0x18, + 0xF1, + 0x05, + 0xF1, + 0xEB, + 0xF9, + 0xEF, + 0x93, + 0x7F, + 0x60, + 0x67, + 0x94, + 0x13, + 0xCF, + 0x9D, + 0x78, + 0x8B, + 0xD5, + 0x18, + 0x06, + 0xEE, + 0xA4, + 0xE5, + 0x8D, + 0xBA, + 0x17, + 0x22, + 0x0C, + 0x72, + 0x19, + 0xD2, + 0xE8, + 0xC9, + 0x11, + 0x03, + 0xEE, + 0x0D, + 0x3B, + 0x9A, + 0xBD, + 0x0C, + 0x16, + 0x28, + 0x51, + 0x47, + 0x1A, + 0x42, + 0x0D, + 0xEA, + 0xD3, + 0x56, + 0x72, + 0x00, + 0xD4, + 0x55, + 0xB8, + 0x69, + 0x4C, + 0xCD, + 0xB9, + 0x7F, + 0xDB, + 0x50, + 0xE4, + 0x67, + 0xB5, + 0xFC, + 0x7F, + 0x10, + 0x63, + 0xF2, + 0x33, + 0xA1, + 0xD8, + 0x00, + 0x4D, + 0xEE, + 0xE8, + 0x7A, + 0xE0, + 0xC4, + 0x40, + 0x0C, + 0x90, + 0x9A, + 0xC8, + 0x28, + 0x43, + 0x86, + 0x06, + 0xA8, + 0xC7, + 0xE8, + 0x38, + 0xE7, + 0xC4, + 0x9B, + 0x7D, + 0xC0, + 0x50, + 0x82, + 0x27, + 0x91, + 0x67, + 0xFF, + 0x14, + 0xDF, + 0x62, + 0x49, + 0x0C, + 0x0F, + 0x9E, + 0x1A, + 0xC2, + 0xA7, + 0xF5, + 0x03, + 0x63, + 0x15, + 0x63, + 0xB0, + 0x10, + 0x33, + 0x14, + 0xF9, + 0xEC, + 0x6A, + 0xAA, + 0x7C, + 0xB3, + 0x91, + 0x79, + 0x5C, + 0x09, + 0x79, + 0xDC, + 0x6C, + 0xED, + 0x97, + 0x66, + 0xB7, + 0x49, + 0xD7, + 0xB5, + 0x64, + 0xAD, + 0xCB, + 0x3F, + 0x30, + 0x8B, + 0x69, + 0x5F, + 0xF1, + 0xB5, + 0x23, + 0x2D, + 0x14, + 0xE8, + 0x9A, + 0x2E, + 0xC7, + 0xFE, + 0xEA, + 0xBA, + 0x3F, + 0x4E, + 0x27, + 0x9E, + 0xDA, + 0xC1, + 0x57, + 0xEE, + 0x9B, + 0x88, + 0x77, + 0x8D, + 0xB0, + 0x8C, + 0x55, + 0x3F, + 0x9C, + 0xC3, + 0x3F, + 0xF9, + 0x97, + 0x59, + 0xDA, + 0x15, + 0xAA, + 0xFB, + 0xF6, + 0xAF, + 0xA4, + 0x4B, + 0x50, + 0xC1, + 0xB0, + 0x0A, + 0x93, + 0x1B, + 0xF7, + 0x1F, + 0x44, + 0xB7, + 0xFD, + 0x4E, + 0x2B, + 0x54, + 0xDD, + 0xF2, + 0x55, + 0xB5, + 0xC7, + 0xA9, + 0xF1, + 0x30, + 0x0B, + 0xAF, + 0x29, + 0xF8, + 0xB3, + 0xB0, + 0x99, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, +) diff --git a/test/obsolete/cmvspyconvert.py b/test/obsolete/cmvspyconvert.py index fefcae071..fdb718a35 100644 --- a/test/obsolete/cmvspyconvert.py +++ b/test/obsolete/cmvspyconvert.py @@ -4,38 +4,40 @@ import sys import re -file_boiler_plate = \ -"""#This file was automatically generated by '%s' +file_boiler_plate = ( + """#This file was automatically generated by '%s' #from a cmvspy.h file. #Example usage: -# from cmvspy import data as coremini_data\n\n""" % sys.argv[0] +# from cmvspy import data as coremini_data\n\n""" + % sys.argv[0] +) if __name__ == "__main__": - try: - cmvspy_filename = sys.argv[1] - except IndexError: - cmvspy_filename = "cmvspy.h" - try: - cmvspy_py_filename = sys.argv[2] - except IndexError: - cmvspy_py_filename = "cmvspy.py" - print("'%s' Will be converted in '%s'" % (cmvspy_filename, cmvspy_py_filename)) - cmvspy_py_file = open(cmvspy_py_filename, "w+") - cmvspy_py_file.write(file_boiler_plate) - cmvspy_py_file.write("data = ( \\\n\t") - hex_regex = re.compile("^\s*0[xX][0-9a-fA-F]+") - BYTES_PER_LINE = 10 - bytes_current = 0 - with open(cmvspy_filename) as cmvspy_file: - for line in cmvspy_file: - matches = hex_regex.match(line) - if not matches: - continue - cmvspy_py_file.write(matches.group() + ", ") - bytes_current += 1 - if bytes_current >= 10: - bytes_current = 0 - cmvspy_py_file.write(" \\\n\t") - cmvspy_py_file.write(")\n") - cmvspy_py_file.close() - print("Done.") \ No newline at end of file + try: + cmvspy_filename = sys.argv[1] + except IndexError: + cmvspy_filename = "cmvspy.h" + try: + cmvspy_py_filename = sys.argv[2] + except IndexError: + cmvspy_py_filename = "cmvspy.py" + print("'%s' Will be converted in '%s'" % (cmvspy_filename, cmvspy_py_filename)) + cmvspy_py_file = open(cmvspy_py_filename, "w+") + cmvspy_py_file.write(file_boiler_plate) + cmvspy_py_file.write("data = ( \\\n\t") + hex_regex = re.compile("^\s*0[xX][0-9a-fA-F]+") + BYTES_PER_LINE = 10 + bytes_current = 0 + with open(cmvspy_filename) as cmvspy_file: + for line in cmvspy_file: + matches = hex_regex.match(line) + if not matches: + continue + cmvspy_py_file.write(matches.group() + ", ") + bytes_current += 1 + if bytes_current >= 10: + bytes_current = 0 + cmvspy_py_file.write(" \\\n\t") + cmvspy_py_file.write(")\n") + cmvspy_py_file.close() + print("Done.") diff --git a/test/obsolete/test_coremini.py b/test/obsolete/test_coremini.py index dcd17ece1..f99cd0d20 100644 --- a/test/obsolete/test_coremini.py +++ b/test/obsolete/test_coremini.py @@ -6,6 +6,7 @@ from cmvspy import data + class testCoreMini(unittest.TestCase): def _clear_coremini(self): if self.dev1.DeviceType == ics.NEODEVICE_VCAN3: @@ -13,10 +14,10 @@ def _clear_coremini(self): else: ics.coremini_clear(self.dev1, ics.SCRIPT_LOCATION_FLASH_MEM) ics.coremini_clear(self.dev1, ics.SCRIPT_LOCATION_SDCARD) - + @classmethod def setUpClass(self): - #input() # for debugging purposes + # input() # for debugging purposes self.dev1 = ics.open_device() self._clear_coremini(self) @@ -38,9 +39,10 @@ def load_coremini(self, contents, location): ics.coremini_clear(self.dev1, location) time.sleep(0.1) self.assertFalse(ics.coremini_get_status(self.dev1)) + # This allows us to work in other directories and leave the vs3cmb file # inside same directory as the script. - vs3file = os.path.dirname(os.path.realpath(__file__)) + '/cmvspy.vs3cmb' + vs3file = os.path.dirname(os.path.realpath(__file__)) + "/cmvspy.vs3cmb" if self.dev1.DeviceType == ics.NEODEVICE_VCAN3: load_coremini(self, data, ics.SCRIPT_LOCATION_VCAN3_MEM) load_coremini(self, vs3file, ics.SCRIPT_LOCATION_VCAN3_MEM) @@ -70,4 +72,4 @@ def testFblock(self): if __name__ == "__main__": - unittest.main() + unittest.main() diff --git a/test/obsolete/test_get_device_status.py b/test/obsolete/test_get_device_status.py index bd66ccc75..86a7b674d 100644 --- a/test/obsolete/test_get_device_status.py +++ b/test/obsolete/test_get_device_status.py @@ -1,17 +1,19 @@ import ics import time + def print_device_status(s): for attr_name in dir(s): - if attr_name.startswith('_'): + if attr_name.startswith("_"): continue - print(attr_name, " "*(35-len(attr_name)), getattr(s, attr_name)) - if attr_name.upper() in ('FIRE2STATUS', 'VCAN4STATUS'): + print(attr_name, " " * (35 - len(attr_name)), getattr(s, attr_name)) + if attr_name.upper() in ("FIRE2STATUS", "VCAN4STATUS"): print() print_device_status(getattr(s, attr_name)) print() + d = ics.open_device() -time.sleep(0.250) # Give the device time to send the frame +time.sleep(0.250) # Give the device time to send the frame s = ics.get_device_status(d) print_device_status(s) diff --git a/test/obsolete/test_network_fire.py b/test/obsolete/test_network_fire.py index f517688ce..38bf5da3e 100644 --- a/test/obsolete/test_network_fire.py +++ b/test/obsolete/test_network_fire.py @@ -3,6 +3,7 @@ import time import random + class testneoVIFIRENetworks(unittest.TestCase): @classmethod def setUpClass(self): @@ -11,19 +12,18 @@ def setUpClass(self): ics.open_device(devices[1]) self.dev1 = devices[0] self.dev2 = devices[1] - + @classmethod def setUp(self): ics.load_default_settings(self.dev1) ics.load_default_settings(self.dev2) - + # Make sure we start with a "clean" network ics.get_error_messages(self.dev1) ics.get_error_messages(self.dev2) ics.get_messages(self.dev1, False, 0.1) ics.get_messages(self.dev2, False, 0.1) - - + @classmethod def tearDownClass(self): # For some reason tp_dealloc doesn't get called on @@ -31,13 +31,19 @@ def tearDownClass(self): # Lets force it here. del self.dev1 del self.dev2 - + def testCAN(self): message = ics.SpyMessage() message.ArbIDOrHeader = 0xFF - message.Data = (1,2,3,4,5,6,7,8) - for network in (ics.NETID_HSCAN, ics.NETID_MSCAN, ics.NETID_HSCAN2, \ - ics.NETID_HSCAN3, ics.NETID_LSFTCAN, ics.NETID_SWCAN): + message.Data = (1, 2, 3, 4, 5, 6, 7, 8) + for network in ( + ics.NETID_HSCAN, + ics.NETID_MSCAN, + ics.NETID_HSCAN2, + ics.NETID_HSCAN3, + ics.NETID_LSFTCAN, + ics.NETID_SWCAN, + ): message.NetworkID = network try: self.assertTrue(ics.transmit_messages(self.dev1, message) == None, network) @@ -54,23 +60,21 @@ def testCAN(self): self.assertEqual(message.Data, messages[0].Data) self.assertFalse(ics.get_error_messages(self.dev1)) self.assertFalse(ics.get_error_messages(self.dev2)) - + def testLIN(self): message = ics.SpyMessageJ1850() message.Header = (0x3C, 1, 2) - message.StatusBitField = ics.SPY_STATUS_NETWORK_MESSAGE_TYPE | \ - ics.SPY_STATUS_LIN_MASTER + message.StatusBitField = ics.SPY_STATUS_NETWORK_MESSAGE_TYPE | ics.SPY_STATUS_LIN_MASTER message.Protocol = ics.SPY_PROTOCOL_LIN - - for network in (ics.NETID_LIN, ics.NETID_LIN2, ics.NETID_LIN3, \ - ics.NETID_LIN4): + + for network in (ics.NETID_LIN, ics.NETID_LIN2, ics.NETID_LIN3, ics.NETID_LIN4): message.NetworkID = network message.Data = tuple([random.randint(x, 0xFF) for x in range(6)]) # Generate the checksum checksum = 0 - for byte in message.Data+message.Header[1:3]: + for byte in message.Data + message.Header[1:3]: checksum += byte - if (checksum > 255): + if checksum > 255: checksum -= 255 message.Data += ((~checksum & 0xFF),) self.assertTrue(ics.transmit_messages(self.dev1, message) == None) @@ -84,9 +88,9 @@ def testLIN(self): self.assertEqual(message.Data[0:-1], messages[0].Data) self.assertFalse(ics.get_error_messages(self.dev1)) self.assertFalse(ics.get_error_messages(self.dev2)) - + def testMISC(self): - #dev1 = output, dev2 = input + # dev1 = output, dev2 = input def _test_misc(self, state): arbs = (0x203, 0x204, 0x205, 0x206, 0x201, 0x202) for arb in arbs: @@ -104,14 +108,13 @@ def _test_misc(self, state): self.assertNotEqual(len(messages), 0) self.assertEqual(messages[-1].ArbIDOrHeader, 0x100) for i, arb in enumerate(arbs): - #print(messages[-1].Data, messages[-1].Data[1]>>i & 1) - self.assertEqual(messages[-1].Data[1]>>i & 1, state, \ - "MISC%d PIN state is wrong" % (arb-0x200)) + # print(messages[-1].Data, messages[-1].Data[1]>>i & 1) + self.assertEqual(messages[-1].Data[1] >> i & 1, state, "MISC%d PIN state is wrong" % (arb - 0x200)) self.assertFalse(ics.get_error_messages(self.dev1)) self.assertFalse(ics.get_error_messages(self.dev2)) # Change the device settings - #dev1 = output, dev2 = input + # dev1 = output, dev2 = input settings = ics.get_device_settings(self.dev1) settings.misc_io_initial_ddr = 0x3F settings.misc_io_initial_latch = 0x3F diff --git a/test/obsolete/test_open_close.py b/test/obsolete/test_open_close.py index 9e124bcd3..ed2884649 100644 --- a/test/obsolete/test_open_close.py +++ b/test/obsolete/test_open_close.py @@ -2,14 +2,15 @@ import unittest import time + class testneoVIFIRENetworks(unittest.TestCase): @classmethod def setUpClass(self): self.devices = ics.find_devices() - + @classmethod def setUp(self): - pass #time.sleep(2) + pass # time.sleep(2) @classmethod def tearDownClass(self): @@ -17,28 +18,28 @@ def tearDownClass(self): # ics.NeoDevice when initialzed in setUpClass(). # Lets force it here. del self.devices - + def testAutoClose(self): devices = ics.find_devices() for device in devices: ics.open_device(device) - del devices # emulate NeoDevice list going out of scope + del devices # emulate NeoDevice list going out of scope devices = ics.find_devices() for device in devices: ics.open_device(device) - + def testOpenCloseByFind(self): # Open by ics.NeoDevice for device in self.devices: ics.open_device(device) ics.close_device(device) - + def testOpenCloseBySerial(self): # Open by serial number for device in self.devices: d = ics.open_device(device.SerialNumber) ics.close_device(d) - + def testOpenCloseByFirstFound(self): # Open by first found first_devices = [] @@ -47,7 +48,7 @@ def testOpenCloseByFirstFound(self): # Close by API for device in first_devices: ics.close_device(device) - + def testOpenClose100Times(self): for x in range(100): ics.open_device(self.devices[0]) diff --git a/test/test_find_devices.py b/test/test_find_devices.py index bbff56f8b..232373193 100644 --- a/test/test_find_devices.py +++ b/test/test_find_devices.py @@ -1,22 +1,25 @@ import timeit import unittest import ics + # This test requries 2 devices attached, one neoVI FIRE2s and one ValueCAN3 _DEBUG = False + class TestFindDevicesLegacy(unittest.TestCase): @classmethod def setUpClass(self): ics.override_library_name(r"icsneo40-legacy.dll") if _DEBUG: import os + input("Pause... " + str(os.getpid())) - + def test_default_parameters(self): devices = ics.find_devices() self.assertTrue(len(devices) == 2) - + def test_default_parameters_time(self): if not _DEBUG: self.assertTrue((timeit.timeit("ics.find_devices()", setup="import ics", number=1000)) <= 5.0) @@ -24,39 +27,49 @@ def test_default_parameters_time(self): def test_find_fire2(self): devices = ics.find_devices(ics.NEODEVICE_FIRE2) self.assertTrue(len(devices) == 1) - + def test_find_vcan3(self): devices = ics.find_devices(ics.NEODEVICE_VCAN3) self.assertTrue(len(devices) == 1) - + def test_find_fire2_and_vcan3(self): devices = ics.find_devices(ics.NEODEVICE_FIRE2 | ics.NEODEVICE_VCAN3) self.assertTrue(len(devices) == 2) - + + class TestFindDevicesNewStyle(unittest.TestCase): @classmethod def setUpClass(self): ics.override_library_name(r"icsneo40.dll") if _DEBUG: import os + input("Pause... " + str(os.getpid())) - + def test_default_parameters(self): devices = ics.find_devices() self.assertTrue(len(devices) == 2) - + def test_default_parameters_time(self): if not _DEBUG: self.assertTrue((timeit.timeit("ics.find_devices()", setup="import ics", number=1000)) <= 5.0) def test_find_fire2(self): - devices = ics.find_devices([ics.NEODEVICE_FIRE2,]) + devices = ics.find_devices( + [ + ics.NEODEVICE_FIRE2, + ] + ) self.assertTrue(len(devices) == 1) - + def test_find_vcan3(self): - devices = ics.find_devices([ics.NEODEVICE_VCAN3,]) + devices = ics.find_devices( + [ + ics.NEODEVICE_VCAN3, + ] + ) self.assertTrue(len(devices) == 1) - + def test_find_fire2_and_vcan3(self): devices = ics.find_devices([ics.NEODEVICE_FIRE2, ics.NEODEVICE_VCAN3]) self.assertTrue(len(devices) == 2) @@ -68,23 +81,32 @@ def setUpClass(self): ics.override_library_name(r"icsneo40-legacy.dll") if _DEBUG: import os + input("Pause... " + str(os.getpid())) - + def test_default_parameters(self): devices = ics.find_devices() self.assertTrue(len(devices) == 2) - + def test_default_parameters_time(self): self.assertTrue((timeit.timeit("ics.find_devices()", setup="import ics", number=1000)) <= 5.0) def test_find_fire2(self): - devices = ics.find_devices([ics.NEODEVICE_FIRE2,]) + devices = ics.find_devices( + [ + ics.NEODEVICE_FIRE2, + ] + ) self.assertTrue(len(devices) == 2) - + def test_find_vcan3(self): - devices = ics.find_devices([ics.NEODEVICE_VCAN3,]) + devices = ics.find_devices( + [ + ics.NEODEVICE_VCAN3, + ] + ) self.assertTrue(len(devices) == 2) - + def test_find_fire2_and_vcan3(self): devices = ics.find_devices([ics.NEODEVICE_FIRE2, ics.NEODEVICE_VCAN3]) self.assertTrue(len(devices) == 2) @@ -93,5 +115,6 @@ def test_find_fire2_and_vcan3(self): if __name__ == "__main__": if _DEBUG: import os + input("Pause... " + str(os.getpid())) - unittest.main() \ No newline at end of file + unittest.main() diff --git a/test/test_structs.py b/test/test_structs.py index dbc61d004..25a9de512 100644 --- a/test/test_structs.py +++ b/test/test_structs.py @@ -1,14 +1,16 @@ import unittest import sys import os -#print(os.getcwd()) -print(os.path.abspath('../')) -sys.path.append('../') + +# print(os.getcwd()) +print(os.path.abspath("../")) +sys.path.append("../") from ics.structures.inner_structure import * from ics.structures.test_structure import * from ics.structures.test import * + class TestTestEnum(unittest.TestCase): def test_all(self): self.assertEqual(test.TestNone, 0) @@ -18,32 +20,33 @@ def test_all(self): self.assertEqual(test.TestD, 4) self.assertEqual(test.TestE, 5) + class TestInnerStructure(unittest.TestCase): def test_all(self): t = inner_structure() self.assertTrue(isinstance(t, ctypes.Structure)) # default init - self.assertEqual(t.a, b'\x00') + self.assertEqual(t.a, b"\x00") self.assertEqual(t.b, 0) self.assertEqual(t.t, 0) - t.a = b'Z' - self.assertEqual(t.a, b'Z') + t.a = b"Z" + self.assertEqual(t.a, b"Z") self.assertEqual(t.b, 0) self.assertEqual(t.t, 0) - t.a = b'\x00' + t.a = b"\x00" t.b = 10 - self.assertEqual(t.a, b'\x00') + self.assertEqual(t.a, b"\x00") self.assertEqual(t.b, 10) self.assertEqual(t.t, 0) t.b = 0 t.t = test.TestD - self.assertEqual(t.a, b'\x00') + self.assertEqual(t.a, b"\x00") self.assertEqual(t.b, 0) self.assertEqual(t.t, test.TestD) -class TestTestStructure(unittest.TestCase): +class TestTestStructure(unittest.TestCase): def test_a(self): t = A() self.assertTrue(isinstance(t, ctypes.Structure)) @@ -65,7 +68,7 @@ def test_a(self): self.assertEqual(t.a, 0) self.assertEqual(t.b, 0) self.assertEqual(t.c, 10) - + def test_b(self): t = B() self.assertTrue(isinstance(t, ctypes.Structure)) @@ -87,7 +90,7 @@ def test_b(self): self.assertEqual(t.d, 0) self.assertEqual(t.e, 0) self.assertEqual(t.f, 1) - + def test_c(self): t = C() self.assertTrue(isinstance(t, ctypes.Union)) @@ -151,7 +154,7 @@ def test_d(self): self.assertEqual(t.j, 1) self.assertEqual(t.k, 1) self.assertEqual(t.m, 1) - + def test_e(self): t = E() self.assertTrue(isinstance(t, ctypes.Structure)) @@ -203,7 +206,7 @@ def test_f(self): self.assertEqual(t.r, 0) self.assertEqual(t.s, 0) self.assertEqual(t.t, 0) - + def test_anonymous(self): t = test_structure() self.assertTrue(isinstance(t, ctypes.Structure)) @@ -232,7 +235,7 @@ def test_anonymous(self): self.assertEqual(t.B.d, 0) self.assertEqual(t.B.e, 0) self.assertEqual(t.B.f, 1) - t._def = 0x7 + t._def = 0x7 self.assertEqual(t._def, 0x7) self.assertEqual(t.B.d, 1) self.assertEqual(t.B.e, 1) @@ -243,4 +246,4 @@ def test_anonymous(self): try: unittest.main() except SystemExit as ex: - print(f'Return code: {int(ex.code)}') + print(f"Return code: {int(ex.code)}")