"""
Copyright 2021 Stichting Nederlandse Wetenschappelijk Onderzoek Instituten,
ASTRON Netherlands Institute for Radio Astronomy
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
 http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.

Check APSCT_CLK

"""
import apsct_lib
import sys

READ_ALL = False # True

CLK_FREQ = '200MHz'

if len(sys.argv) < 2:
    print("Production_apsct.py <ASTRON NR> <Serial number>")
    print("e.g. python3 production_apsct.py 2023-01 1234")
    exit()

apsct = apsct_lib.ApsctClass(CLK_FREQ)
state = True
modi = ["200MHz", "160MHz", "OFF"]
for mode in modi:
    print(f"Check APSCT in {mode} mode")
    apsct.frequency = mode
    apsct.set_apsct()
    if mode == "200MHz":
        state = state & apsct.pll_200.read_lock()
    if mode == "160MHz":
        state = state & apsct.pll_160.read_lock()

apsct.frequency = "200MHz"
apsct.set_apsct()
apsct.pll_200.read_lock()
apsct.sensors.apsct_sensors()
state = state & apsct.check_apsct()

if READ_ALL:
    apsct.pll_200.read_all_regs_pll()
    apsct.pll_160.read_all_regs_pll()
    apsct.read_IO_expanderis()

if state:
    apsct_id = "APSCT-" + sys.argv[1]
    serial = sys.argv[2]
    rw_ok = apsct.eeprom.wr_rd_eeprom(apsct_id, address=0)
    if rw_ok:
        rw_ok = apsct.eeprom.wr_rd_eeprom(serial, address=0x20)
    if not rw_ok:
        print("EEPROM Error")
else:
    print("\n >>> Errors during testing <<<\n")