#!/usr/bin/python3
import sys
from subprocess import check_output
from viavi.mts.ScpiAccess import ScpiAccess

sys.stdout = open('/tmp/fiberscope-can-launch.log', 'w')
try:
    # Count the arguments
    arguments = len(sys.argv) - 1
    print("The script %s is called with %i arguments" % (sys.argv[0], arguments))

    # Output arguments
    position = 1
    jsonStr = None
    while arguments >= position:
        print("Parameter %i: %s" % (position, sys.argv[position]))
        if position == 2:
            jsonStr = sys.argv[position]
        position = position + 1

    # ISU port number
    port = 8000
    # Check if the Microscope App is running
    try:
        pidMic = check_output(['pidof', 'Microscope'])
        print('Microscope running with PID: %s' % (pidMic))
    except Exception as err:
        print("ERROR_MODULE^MICROSCOPE")
        print("Test requires an Inspection Probe. Plug-in the Probe.")
        sys.stdout.close()
        sys.exit(1)

    # Connecting to Fiber-ISU port and sending SCPI commands
    isu = ScpiAccess('127.0.0.1', port)

    # Check if there is a Microscope plugged in
    found = False
    params = str(port) + ' '
    tmpCmd = 'MOD:FUNC:LIST? BOTH,BASE'
    tmpReply = isu.SendAndReadCommand(tmpCmd)
    print('Checking : %s --> %s' % (tmpCmd, tmpReply))
    if 'MICROSCOPE' in str(tmpReply):
        print('Found Microscope')
        found = True

    if not found:
        print("ERROR_MODULE^MICROSCOPE")
        print("Test requires an Inspection Probe. Plug-in the Probe.")
        sys.stdout.close()
        sys.exit(1)
    else:
        print("Inspection Probe detected, continuing...")
except Exception as err:
    print(">>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> %s" % str(err))

sys.stdout.close()
sys.exit(0)
