001/*
002 * Copyright (C) Cross The Road Electronics.  All rights reserved.
003 * License information can be found in CTRE_LICENSE.txt
004 * For support and suggestions contact support@ctr-electronics.com or file
005 * an issue tracker at https://github.com/CrossTheRoadElec/Phoenix-Releases
006 */
007package com.ctre.phoenixpro.configs;
008
009import java.util.concurrent.locks.Lock;
010import java.util.concurrent.locks.ReentrantLock;
011
012import com.ctre.phoenixpro.StatusCode;
013import com.ctre.phoenixpro.configs.jni.ConfigJNI;
014import com.ctre.phoenixpro.hardware.DeviceIdentifier;
015import com.ctre.phoenixpro.jni.ErrorReportingJNI;
016
017public class ParentConfigurator {
018    /**
019     * The most amount of time to wait for a config.
020     */
021    public double defaultTimeoutSeconds = 0.050;
022
023    private final DeviceIdentifier deviceIdentifier;
024    private final Lock _lck = new ReentrantLock();
025
026    private final ConfigJNI jni = new ConfigJNI();
027
028    protected ParentConfigurator(DeviceIdentifier deviceIdentifier) {
029        this.deviceIdentifier = deviceIdentifier;
030    }
031
032    protected StatusCode setConfigsPrivate(String serialString, double timeoutSeconds, boolean futureProofConfigs,
033            boolean overrideIfDuplicate) {
034        StatusCode status;
035        _lck.lock();
036        /* make sure we always unlock */
037        try {
038            jni.serializedString = serialString;
039            status = StatusCode.valueOf(
040                jni.SetConfigs(
041                    deviceIdentifier.getNetwork(),
042                    deviceIdentifier.getDeviceHash(),
043                    timeoutSeconds,
044                    futureProofConfigs,
045                    overrideIfDuplicate));
046        } finally {
047            _lck.unlock();
048        }
049
050        if (!status.isOK()) {
051            String location = this.deviceIdentifier.toString() + " Apply Config";
052            ErrorReportingJNI.reportStatusCode(status.value, location);
053        }
054        return status;
055    }
056
057    protected StatusCode getConfigsPrivate(StringBuilder serialString, double timeoutSeconds) {
058        StatusCode status;
059        _lck.lock();
060        /* make sure we always unlock */
061        try {
062            status = StatusCode.valueOf(
063                jni.GetConfigs(
064                    deviceIdentifier.getNetwork(),
065                    deviceIdentifier.getDeviceHash(),
066                    timeoutSeconds));
067            serialString.append(jni.serializedString);
068        } finally {
069            _lck.unlock();
070        }
071
072        if (!status.isOK()) {
073            String location = this.deviceIdentifier.toString() + " Refresh Config";
074            ErrorReportingJNI.reportStatusCode(status.value, location);
075        }
076        return status;
077    }
078}