#!/usr/bin/env python3

# bitbusGatewayTest.py: Communicate with a SLAC BitBus power supply controller using 
# an Elzet ethernet-to-bitbus gateway (see https://www.elzet80.com/eth-bit.html).
# mdunning Sep 2019

import argparse
import socket
import struct
import sys
from time import sleep

FLAGS = b'\x40'
TASK = b'\x01'
bb_header = b'\x6c\x1f\x08\x00'

STATUS_SHORT = {'cmd':b'\xc0', 'data':b'\xc0\x00'}
IDES         = {'cmd':b'\xc1', 'data':b'\xbf\x01\x00\x00\x00\x00\x00\x01\x00'}
IDES_RBV     = {'cmd':b'\xc3', 'data':b'\xc3\x01\x00'}
INT_RESET    = {'cmd':b'\xc4', 'data':b'\xbf\x00'}
PS_OFF       = {'cmd':b'\xc5', 'data':b'\xbf\x00'}
PS_ON        = {'cmd':b'\xc6', 'data':b'\xbf\x00'}
ANALOG_RBV   = {'cmd':b'\xc8', 'data':b'\xc8\x00'}
INFO_MSG     = {'cmd':b'\xc9', 'data':b'\xc9\x00'}
STATUS_DIAG  = {'cmd':b'\xca', 'data':b'\xca\x00'}
CTRL_INFO    = {'cmd':b'\xcb', 'data':b'\xcb\x00'}
CAL_DATA     = {'cmd':b'\xcc', 'data':b'\xcc\x00'}
STATUS_FAST  = {'cmd':b'\xcd', 'data':b'\xcd\x00'}
PS_RESET     = {'cmd':b'\xe3', 'data':b'\x00\x01'}


def bb_open_master(skt, app, card, debug=False):
    fun = b'\x01'
    msg_length = b'\x10'
    data = b'\x15'
    message = b''.join([bb_header, msg_length, b'\x00', fun, b'\x00', app, b'\x00', card,  b'\x00', data, b'\x00\x00', b'\x00\x00'])
    if debug: print('BitbusOpenMaster...')
    if debug: print('Sending {} bytes: {}'.format(len(message), message))
    skt.sendall(message)
    rsp = skt.recv(256)
    if debug: print('Received {} bytes: {}'.format(len(rsp), rsp))
    handle = rsp[8:12]
    if debug: print('Handle = {}'.format(handle))
    return handle

def bb_send_msg(skt, node, hdl, cmd, data, debug=False):
    if debug: print('BitbusSendMsg... Node={}, cmd={}, data={}'.format(node, hex(data[0]), data[1:]))
    length = bytes([len(data) + 7])
    msg_length = bytes([int.from_bytes(length, "little") + 4])
    message = b''.join([bb_header, msg_length, b'\x00', b'\x07\x00', hdl, b'\x00\x00', length, FLAGS, node, TASK, cmd, data])
    if debug: print('Sending {} bytes: {}'.format(len(message), message))
    skt.sendall(message)
    rsp = skt.recv(256)
    if debug: print('Received {} bytes: {}'.format(len(rsp), rsp))

def bb_wait_msg(skt, hdl, timeout=b'\x05\xdc', debug=False):
    if debug: print('BitbusWaitMsg...')
    message = b''.join([bb_header, b'\x08\x00\x09\x00', hdl, timeout, b'\x00\x00'])  # Timeout 05dc = 1500 ms
    if debug: print('Sending {} bytes: {}'.format(len(message), message))
    skt.sendall(message)
    rsp = skt.recv(256)
    if debug: print('Received {} bytes: {}'.format(len(rsp), rsp))
    try:
        msg_size = rsp[4]
        bapi_stat = rsp[8:12]
        length = rsp[14]
        node = rsp[16]
        cmd = rsp[19]
        data = rsp[19:]
        if debug: print('Msg. size={}, Node={}, cmd={}, bapi_stat={}, length={},\n data={}, data length={}'
                .format(msg_size, node, hex(cmd), bapi_stat, length, data, len(data)))
        if debug: print('bapi_stat[0]={}'.format(bapi_stat[0]))
        if bapi_stat[0]==9:
            print('*** bapi status not ok ({})***'.format(bapi_stat[0]))
    except IndexError as e:
        print(e)
    return node,data

def bb_close(skt, hdl, debug=False):
    if debug: print('BitbusClose...')
    message = b''.join([bb_header, b'\x04\x00\x05\x00', hdl])
    if debug: print('Sending {} bytes: {}'.format(len(message), message))
    skt.sendall(message)
    rsp = skt.recv(256)
    if debug: print('Received {} bytes: {}'.format(len(rsp), rsp))

def send_msg(skt, node, handle, cmd_dict, wait=False, debug=False):
    if debug: print('send_msg: cmd={}'.format(cmd_dict['cmd']))
    # Send BitbusSendMsg
    bb_send_msg(s, node, handle, cmd_dict['cmd'], cmd_dict['data'], debug=debug)
    # Send BitbusWaitMsg
    if wait:
        node,rsp = bb_wait_msg(s, handle, debug=debug)
        return node,rsp

def process_rsp(node, cmd, rsp):
    if cmd==STATUS_SHORT:
        status_byte1 = rsp[2]
        status_byte2 = rsp[3]
        i_rbv = struct.unpack("f", rsp[4:8])[0]
        print('Node: {}, status_byte1={}, status_byte2={}, i_rbv={}'.format(node,
                hex(status_byte1), hex(status_byte2), i_rbv))
    elif cmd==IDES:
        status_byte1 = rsp[2]
        status_byte2 = rsp[3]
        print('Node: {}, status_byte1={}, status_byte2={}'.format(node,
        hex(status_byte1), hex(status_byte2)))
    elif cmd==IDES_RBV:
        status_byte1 = rsp[2]
        status_byte2 = rsp[3]
        rbv = struct.unpack("f", rsp[4:8])[0]
        ramp = struct.unpack("h", rsp[8:10])[0]/100
        print('Node: {}, status_byte1={}, status_byte2={}, ides_rbv={}, ramp={} s'.format(node,
                hex(status_byte1), hex(status_byte2), rbv, ramp))
    elif cmd==INT_RESET:
        status_byte1 = rsp[2]
        status_byte2 = rsp[3]
        print('Node: {}, status_byte1={}, status_byte2={}'.format(node,
                hex(status_byte1), hex(status_byte2)))
    elif cmd==PS_OFF:
        status_byte1 = rsp[2]
        status_byte2 = rsp[3]
        print('Node: {}, status_byte1={}, status_byte2={}'.format(node,
                hex(status_byte1), hex(status_byte2)))
    elif cmd==PS_ON:
        status_byte1 = rsp[2]
        status_byte2 = rsp[3]
        print('Node: {}, status_byte1={}, status_byte2={}'.format(node,
                hex(status_byte1), hex(status_byte2)))
    elif cmd==ANALOG_RBV:
        i_xduct1 = struct.unpack("f", rsp[2:6])[0]
        i_xduct2 = struct.unpack("f", rsp[6:10])[0]
        dac_out = struct.unpack("f", rsp[10:14])[0]
        i_ripple = struct.unpack("f", rsp[14:18])[0]
        i_grnd = struct.unpack("f", rsp[18:22])[0]
        temp = struct.unpack("f", rsp[22:26])[0]
        bulk_volt = struct.unpack("f", rsp[26:30])[0]
        spare_volt = struct.unpack("f", rsp[30:34])[0]
        print('Node: {}, i_xduct1={}, i_xduct2={}, dac_out={}, i_ripple={}, i_grnd={}, temp={}, bulk_volt={}, spare_volt={}'
                .format(node, i_xduct1, i_xduct2, dac_out, i_ripple, i_grnd,
                temp, bulk_volt, spare_volt))
    elif cmd==INFO_MSG:
        info_msg = rsp[2:]
        print('Node: {}, info_msg={}'.format(node, info_msg))
    elif cmd==STATUS_DIAG:
        status_byte1 = rsp[2]
        status_byte2 = rsp[3]
        status_byte3 = rsp[4]
        status_byte4 = rsp[5]
        ramp_state = rsp[6]
        i_set = struct.unpack("f", rsp[7:11])[0]
        ramp_start = struct.unpack("f", rsp[11:15])[0]
        ramp_time_left = struct.unpack("f", rsp[15:19])[0]
        adc_offset = struct.unpack("H", rsp[19:21])[0]
        adc_gain = struct.unpack("H", rsp[21:23])[0]
        dac_offset = struct.unpack("H", rsp[23:25])[0]
        dac_gain = struct.unpack("H", rsp[25:27])[0]
        last_reset_code = rsp[27]
        last_off_code = rsp[28]
        cal_err_code = rsp[29]
        self_test_err_code = rsp[30]
        print('''Node: {}, status_byte1={}, status_byte2={}, status_byte3={}, status_byte4={},
                ramp_state={}, i_set={}, ramp_start={}, ramp_time_left={},
                adc_offset={}, adc_gain={}, dac_offset={}, dac_gain={},
                last_reset_code={}, last_off_code={}, cal_err_code={}, self_test_err_code={}'''
                .format(node, hex(status_byte1), hex(status_byte2), hex(status_byte3), hex(status_byte4),
                ramp_state, i_set, ramp_start, ramp_time_left, adc_offset, adc_gain, dac_offset,
                dac_gain, last_reset_code, last_off_code, cal_err_code, self_test_err_code))
    elif cmd==CTRL_INFO:
        chassis_type = rsp[2:3]
        serial = rsp[3:11]
        fw_ver = rsp[11:19]
        mag_id = rsp[19:27]
        print('Node: {}, chassis_type={}, serial={}, fw_ver={}, mag_id={}'.format(node,
                chassis_type, serial, fw_ver, mag_id))
    elif cmd==CAL_DATA:
        reg_xduct = struct.unpack("f", rsp[2:6])[0]
        aux_xduct = struct.unpack("f", rsp[6:10])[0]
        grnd_const = struct.unpack("f", rsp[10:14])[0]
        ps_const = struct.unpack("f", rsp[14:18])[0]
        ref_volt = struct.unpack("f", rsp[18:22])[0]
        cal_date = rsp[22:30]
        print('Node: {}, reg_xduct={}, aux_xduct={}, grnd_const={}, ps_const={},\n ref_volt={}, cal_date={}'
                .format(node, reg_xduct, aux_xduct, grnd_const, ps_const, ref_volt, cal_date))
    elif cmd==STATUS_FAST:
        status_byte1 = rsp[2]
        status_byte2 = rsp[3]
        i_rbv = struct.unpack("f", rsp[4:8])[0]
        print('Node: {}, status_byte1={}, status_byte2={}, i_rbv={}'.format(node,
                hex(status_byte1), hex(status_byte2), i_rbv))

if __name__ == "__main__":
    parser = argparse.ArgumentParser()
    parser.add_argument('-d', '--debug', help='Debug', action='store_true')
    parser.add_argument('-n', '--node', help='Controller node address in decimal', required=True)
    parser.add_argument('-q', '--host', help='Host (BitBus gateway) IP address', default='b118-eth-bitr-1')
    parser.add_argument('-p', '--port', help='Host (BitBus gateway) tcp port', default=8044)
    parser.add_argument('--status_short', help='Short status (up to date)', action='store_true')
    parser.add_argument('--ides', help='Set desired current')
    parser.add_argument('--ides_rbv', help='Desired current readback', action='store_true')
    parser.add_argument('--int_reset', help='Reset interlocks', action='store_true')
    parser.add_argument('--off', help='Turn supply off', action='store_true')
    parser.add_argument('--on', help='Turn supply off', action='store_true')
    parser.add_argument('--analog_rbv', help='Analog readback', action='store_true')
    parser.add_argument('--info_msg', help='Info message', action='store_true')
    parser.add_argument('--status_diag', help='Diagnostic status', action='store_true')
    parser.add_argument('--ctrl_info', help='Controller info', action='store_true')
    parser.add_argument('--cal_data', help='Cal data', action='store_true')
    parser.add_argument('--status_fast', help='Last read status (may not be up to date)', action='store_true')
    parser.add_argument('--reset', help='Reset controller', action='store_true')
    parser.add_argument('--ramp', help='Set ramp rate [0.01s]', default=100)
    args = parser.parse_args()
    
    node = bytes([int(args.node)])

    wait=True    
    if args.status_short:
        cmd = STATUS_SHORT
    elif args.ides:
        print('Setting i to {}...'.format(args.ides))
        ides_bytes = bytearray(struct.pack("f", float(args.ides)))
        ramp = args.ramp
        ramp_bytes = bytearray(struct.pack("h", int(ramp)))
        data_ides = b'\xbf\x01\x00' + ides_bytes + ramp_bytes
        IDES  = {'cmd':b'\xc1', 'data':data_ides}
        cmd = IDES
    elif args.ides_rbv:
        cmd = IDES_RBV
    elif args.int_reset:
        cmd = INT_RESET
        print('Resetting interlocks...')
    elif args.off:
        cmd = PS_OFF
        print('Turning PS off...')
    elif args.on:
        cmd = PS_ON
        print('Turning PS on...')
    elif args.analog_rbv:
        cmd = ANALOG_RBV
    elif args.info_msg:
        cmd = INFO_MSG
    elif args.status_diag:
        cmd = STATUS_DIAG
    elif args.ctrl_info:
        cmd = CTRL_INFO
    elif args.cal_data:
        cmd = CAL_DATA
    elif args.status_fast:
        cmd = STATUS_FAST
    elif args.reset:
        cmd = PS_RESET
        wait = False
        print('Resetting PS...')


    with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
        s.connect((args.host, args.port))
        # Send BitbusOpenMaster
        handle = bb_open_master(s, b'APPL', b'BBUS0', debug=args.debug)
        # Send message(s)
        node,rsp = send_msg(s, node, handle, cmd, wait, debug=args.debug)
        process_rsp(node, cmd, rsp)
        # Send BitbusClose
        bb_close(s, handle, debug=args.debug)

    

