################################################################################
# Copyright © 2019 TRINAMIC Motion Control GmbH & Co. KG
# (now owned by Analog Devices Inc.),
#
# Copyright © 2023 Analog Devices Inc. All Rights Reserved.
# This software is proprietary to Analog Devices, Inc. and its licensors.
################################################################################

# This program downloads a TMCL binary file to a module.
# Such binary files can be generated using the TMCL Creator in the TMCL-IDE
# (switch on the option "Generate binary file") or by the command line tool TMCLAsm.

from functools import partial
from pytrinamic.connections import ConnectionManager
from pytrinamic.tmcl import TMCLCommand

filename = "test.bin"   # This can be any TMCL binary file generated by the TMCL-IDE or by TMCLAsm

with open(filename, 'rb') as TMCLFile:
    connection_manager = ConnectionManager("--interface serial_tmcl --port COM4 --data-rate 9600")   # This can also be any other interface
    with connection_manager.connect() as my_interface:
        my_interface.send(TMCLCommand.START_DOWNLOAD_MODE, 0, 0, 0)
        for cmd_array in iter(partial(TMCLFile.read, 8), b''):
            my_interface.send(cmd_array[0], cmd_array[1], cmd_array[2], (cmd_array[3]<<24)|(cmd_array[4]<<16)|(cmd_array[5]<<8)|(cmd_array[6]))
       
        my_interface.send(TMCLCommand.QUIT_DOWNLOAD_MODE, 0, 0, 0)
        my_interface.send(TMCLCommand.RESET_APPLICATION, 0, 0, 0)
        my_interface.send(TMCLCommand.RUN_APPLICATION, 0, 0, 0)    # This can be omitted if the porgram does not need to be started right after downloading
    TMCLFile.close()
