# This file is part of the SIS Digitizer Driver.
# It is subject to the license terms in the LICENSE.txt file found in the
# top-level directory of this distribution and at
# https://confluence.slac.stanford.edu/display/ppareg/LICENSE.html. No part
# of the SIS Digitizer Driver, including this file, may be copied,
# modified, propagated, or distributed except according to the terms
# contained in the LICENSE.txt file.


from __future__ import print_function
import os
import argparse
import sys
import json

INIT_DEVICES_FILE = 'SISInitDevices.cmd'
LOAD_DB_FILE = 'SISLoadDb.cmd'
DEFAULT_JSON_FILE = 'singleDevice.json'

def is_valid_channel(num):
    return type(num) is int and 0 <= num < 8

def main():
    dir_path = os.path.dirname(os.path.realpath(__file__))

    parser = argparse.ArgumentParser(formatter_class=argparse.ArgumentDefaultsHelpFormatter)
    parser.add_argument('json_file', nargs='?', default=os.path.join(dir_path, DEFAULT_JSON_FILE), help='File containing device configuration')
    args = parser.parse_args()

    with open(args.json_file, 'r') as conffile:
        devices = json.load(conffile)

    with open(os.path.join(dir_path, INIT_DEVICES_FILE), 'w') as f:
        f.write('# This file was generated by gen_devices_and_channels.py\n' +
                '# Initialize each device and its channels.')
        for device in devices:
            f.write(('\n\n# Device {name:}\n' +
                     'SISInitDevice("{name:}","{vme_addr:}","{vme_int_vec:}","{vme_int_lev:}","$(READ_THREAD_PRIO)","$(READ_THREAD_STACK)","$(AD_MAX_BUFS)","$(AD_MAX_MEM)","$(INTR_THREAD_PRIO)")\n\n').format(**device))
            for channel in device['channels']:
                assert is_valid_channel(channel)
                f.write('NDStdArraysConfigure("{name:}_{0:}",$(STDAR_QU_SZ),$(STDAR_BL_CB),"{name:}_channels",{0:},$(STDAR_MAX_MEM),$(STDARR_PRI),$(STDAR_ST_SZ))\n'.format(channel, **device))

    with open(os.path.join(dir_path, LOAD_DB_FILE), 'w') as f:
        f.write('# This file was generated by gen_devices_and_channels.py\n' +
                '# Load EPICS records for each device and its channels.')
        for device in devices:
            f.write(('\n\n# Device {name:}\n' +
                     'dbLoadRecords("$(TOP)/db/$(DB_PREFIX)TRBase.db","PREFIX={prefix:},PORT={name:},SIZE=$(WFSIZ),PRESAMPLES=,NOCLK=#,LNK_NEW_BURST={prefix:}:_on_new_burst")\n' +
                     'dbLoadRecords("$(TOP)/db/$(DB_PREFIX)TRSIS.db","PREFIX={prefix:},PORT={name:},STATES_SCAN=$(STATES_SCAN),ACTUAL_SCAN=$(ACTUAL_SCAN)")\n\n').format(**device))
            for channel in range(8):
                ch_prefix = device['prefix'] + ':CH{0:}'.format(channel)
                channel_enabled = (channel in device['channels'])
                f.write(('# Channel {1:}\n' +
                        'dbLoadRecords("$(TOP)/db/$(DB_PREFIX)TRSIS_Channel.db","PREFIX={0:},MPREFIX={prefix:},PORT={name:},CHANNEL={1:},VOLT_EOFF=$(VOLT_EOFF),VOLT_ESLO=$(VOLT_ESLO),ENBLD={2:d}")\n'
                         ).format(ch_prefix, channel, channel_enabled, **device))
                if channel_enabled:
                    f.write(('dbLoadRecords("$(TOP)/db/$(DB_PREFIX)TRChannel.db","PREFIX={0:},CHANNELS_PORT={name:}_channels,CHANNEL={1:}")\n' +
                             'dbLoadRecords("$(TOP)/db/$(DB_PREFIX)TRChannelData.db","PREFIX={0:},STDAR_PORT={name:}_{1:},SIZE=$(WFSIZ),FTVL=FLOAT,WF_DTYP=asynFloat32ArrayIn,SNAP_SCAN=$(SNAP_SCAN),SNAPSHOT=$(SNAP)")\n'
                             ).format(ch_prefix, channel, **device))

if __name__ == '__main__':
    main()

# This file is part of the SIS Digitizer Driver.
# It is subject to the license terms in the LICENSE.txt file found in the
# top-level directory of this distribution and at
# https://confluence.slac.stanford.edu/display/ppareg/LICENSE.html. No part
# of the SIS Digitizer Driver, including this file, may be copied,
# modified, propagated, or distributed except according to the terms
# contained in the LICENSE.txt file.


from __future__ import print_function
import os
import argparse
import sys
import json

INIT_DEVICES_FILE = 'SISInitDevices.cmd'
LOAD_DB_FILE = 'SISLoadDb.cmd'
DEFAULT_JSON_FILE = 'singleDevice.json'

def is_valid_channel(num):
    return type(num) is int and 0 <= num < 8

def main():
    dir_path = os.path.dirname(os.path.realpath(__file__))

    parser = argparse.ArgumentParser(formatter_class=argparse.ArgumentDefaultsHelpFormatter)
    parser.add_argument('json_file', nargs='?', default=os.path.join(dir_path, DEFAULT_JSON_FILE), help='File containing device configuration')
    args = parser.parse_args()

    with open(args.json_file, 'r') as conffile:
        devices = json.load(conffile)

    with open(os.path.join(dir_path, INIT_DEVICES_FILE), 'w') as f:
        f.write('# This file was generated by gen_devices_and_channels.py\n' +
                '# Initialize each device and its channels.')
        for device in devices:
            f.write(('\n\n# Device {name:}\n' +
                     'SISInitDevice("{name:}","{vme_addr:}","{vme_int_vec:}","{vme_int_lev:}","$(READ_THREAD_PRIO)","$(READ_THREAD_STACK)","$(AD_MAX_BUFS)","$(AD_MAX_MEM)","$(INTR_THREAD_PRIO)")\n\n').format(**device))
            for channel in device['channels']:
                assert is_valid_channel(channel)
                f.write('NDStdArraysConfigure("{name:}_{0:}",$(STDAR_QU_SZ),$(STDAR_BL_CB),"{name:}_channels",{0:},$(STDAR_MAX_MEM),$(STDARR_PRI),$(STDAR_ST_SZ))\n'.format(channel, **device))

    with open(os.path.join(dir_path, LOAD_DB_FILE), 'w') as f:
        f.write('# This file was generated by gen_devices_and_channels.py\n' +
                '# Load EPICS records for each device and its channels.')
        for device in devices:
            f.write(('\n\n# Device {name:}\n' +
                     'dbLoadRecords("$(TOP)/db/$(DB_PREFIX)TRBase.db","PREFIX={prefix:},PORT={name:},SIZE=$(WFSIZ),PRESAMPLES=,NOCLK=#,LNK_NEW_BURST={prefix:}:_on_new_burst")\n' +
                     'dbLoadRecords("$(TOP)/db/$(DB_PREFIX)TRSIS.db","PREFIX={prefix:},PORT={name:},STATES_SCAN=$(STATES_SCAN),ACTUAL_SCAN=$(ACTUAL_SCAN)")\n\n').format(**device))
            for channel in range(8):
                ch_prefix = device['prefix'] + ':CH{0:}'.format(channel)
                channel_enabled = (channel in device['channels'])
                f.write(('# Channel {1:}\n' +
                        'dbLoadRecords("$(TOP)/db/$(DB_PREFIX)TRSIS_Channel.db","PREFIX={0:},MPREFIX={prefix:},PORT={name:},CHANNEL={1:},VOLT_EOFF=$(VOLT_EOFF),VOLT_ESLO=$(VOLT_ESLO),ENBLD={2:d}")\n'
                         ).format(ch_prefix, channel, channel_enabled, **device))
                if channel_enabled:
                    f.write(('dbLoadRecords("$(TOP)/db/$(DB_PREFIX)TRChannel.db","PREFIX={0:},CHANNELS_PORT={name:}_channels,CHANNEL={1:}")\n' +
                             'dbLoadRecords("$(TOP)/db/$(DB_PREFIX)TRChannelData.db","PREFIX={0:},STDAR_PORT={name:}_{1:},SIZE=$(WFSIZ),FTVL=FLOAT,WF_DTYP=asynFloat32ArrayIn,SNAP_SCAN=$(SNAP_SCAN),SNAPSHOT=$(SNAP)")\n'
                             ).format(ch_prefix, channel, **device))

if __name__ == '__main__':
    main()

# This file is part of the SIS Digitizer Driver. # It is subject to the license terms in the LICENSE.txt file found in the # top-level directory of this distribution and at # https://confluence.slac.stanford.edu/display/ppareg/LICENSE.html. No part # of the SIS Digitizer Driver, including this file, may be copied, # modified, propagated, or distributed except according to the terms # contained in the LICENSE.txt file. # Device {name:}\n' + # Device {name:}\n' + #,LNK_NEW_BURST={prefix:}:_on_new_burst")\n' +