Search in sources :

Example 1 with AudioListener

use of jmri.jmrit.audio.AudioListener in project JMRI by JMRI.

the class DefaultConditional method takeActionIfNeeded.

/**
     * Compares action options, and takes action if appropriate
     * <P>
     * Only get here if a change in state has occurred when calculating this
     * Conditional
     */
@SuppressWarnings({ "deprecation", "fallthrough" })
@SuppressFBWarnings(value = "SF_SWITCH_FALLTHROUGH")
private // have to apply to more than 500 lines of code - jake
void takeActionIfNeeded() {
    if (log.isTraceEnabled()) {
        log.trace("takeActionIfNeeded starts for " + getSystemName());
    }
    int actionCount = 0;
    int actionNeeded = 0;
    int act = 0;
    int state = 0;
    ArrayList<String> errorList = new ArrayList<>();
    // Use a local copy of state to guarantee the entire list of actions will be fired off
    // before a state change occurs that may block their completion.
    int currentState = _currentState;
    for (int i = 0; i < _actionList.size(); i++) {
        ConditionalAction action = _actionList.get(i);
        int neededAction = actionNeeded;
        int option = action.getOption();
        if (log.isTraceEnabled()) {
            log.trace(" takeActionIfNeeded considers action " + i + " with currentState: " + currentState + " and option: " + option);
        }
        if (((currentState == TRUE) && (option == ACTION_OPTION_ON_CHANGE_TO_TRUE)) || ((currentState == FALSE) && (option == ACTION_OPTION_ON_CHANGE_TO_FALSE)) || (option == ACTION_OPTION_ON_CHANGE)) {
            // need to take this action
            actionNeeded++;
            SignalHead h = null;
            SignalMast f = null;
            Logix x = null;
            Light lgt = null;
            Warrant w = null;
            NamedBean nb = null;
            if (action.getNamedBean() != null) {
                nb = action.getNamedBean().getBean();
            }
            int value = 0;
            Timer timer = null;
            int type = action.getType();
            String devName = getDeviceName(action);
            if (devName == null) {
                errorList.add("invalid memory name in action - " + action);
                continue;
            }
            if (log.isDebugEnabled()) {
                log.debug("getDeviceName()=" + action.getDeviceName() + " devName= " + devName);
            }
            switch(type) {
                case Conditional.ACTION_NONE:
                    break;
                case Conditional.ACTION_SET_TURNOUT:
                    Turnout t = (Turnout) nb;
                    if (t == null) {
                        errorList.add("invalid turnout name in action - " + action.getDeviceName());
                    } else {
                        act = action.getActionData();
                        if (act == Route.TOGGLE) {
                            state = t.getKnownState();
                            if (state == Turnout.CLOSED) {
                                act = Turnout.THROWN;
                            } else {
                                act = Turnout.CLOSED;
                            }
                        }
                        t.setCommandedState(act);
                        actionCount++;
                    }
                    break;
                case Conditional.ACTION_RESET_DELAYED_TURNOUT:
                    action.stopTimer();
                // fall through
                case Conditional.ACTION_DELAYED_TURNOUT:
                    if (!action.isTimerActive()) {
                        // Create a timer if one does not exist
                        timer = action.getTimer();
                        if (timer == null) {
                            action.setListener(new TimeTurnout(i));
                            timer = new Timer(2000, action.getListener());
                            timer.setRepeats(true);
                        }
                        // Start the Timer to set the turnout
                        value = getMillisecondValue(action);
                        if (value < 0) {
                            break;
                        }
                        timer.setInitialDelay(value);
                        action.setTimer(timer);
                        action.startTimer();
                        actionCount++;
                    } else {
                        log.warn("timer already active on request to start delayed turnout action - " + devName);
                    }
                    break;
                case Conditional.ACTION_CANCEL_TURNOUT_TIMERS:
                    ConditionalManager cmg = jmri.InstanceManager.getDefault(jmri.ConditionalManager.class);
                    java.util.Iterator<String> iter = cmg.getSystemNameList().iterator();
                    while (iter.hasNext()) {
                        String sname = iter.next();
                        if (sname == null) {
                            errorList.add("Conditional system name null during cancel turnout timers for " + action.getDeviceName());
                        }
                        Conditional c = cmg.getBySystemName(sname);
                        if (c == null) {
                            errorList.add("Conditional null during cancel turnout timers for " + action.getDeviceName());
                        } else {
                            c.cancelTurnoutTimer(devName);
                            actionCount++;
                        }
                    }
                    break;
                case Conditional.ACTION_LOCK_TURNOUT:
                    Turnout tl = (Turnout) nb;
                    if (tl == null) {
                        errorList.add("invalid turnout name in action - " + action.getDeviceName());
                    } else {
                        act = action.getActionData();
                        if (act == Route.TOGGLE) {
                            if (tl.getLocked(Turnout.CABLOCKOUT)) {
                                act = Turnout.UNLOCKED;
                            } else {
                                act = Turnout.LOCKED;
                            }
                        }
                        if (act == Turnout.LOCKED) {
                            tl.setLocked(Turnout.CABLOCKOUT + Turnout.PUSHBUTTONLOCKOUT, true);
                        } else if (act == Turnout.UNLOCKED) {
                            tl.setLocked(Turnout.CABLOCKOUT + Turnout.PUSHBUTTONLOCKOUT, false);
                        }
                        actionCount++;
                    }
                    break;
                case Conditional.ACTION_SET_SIGNAL_APPEARANCE:
                    h = (SignalHead) nb;
                    if (h == null) {
                        errorList.add("invalid Signal Head name in action - " + action.getDeviceName());
                    } else {
                        h.setAppearance(action.getActionData());
                        actionCount++;
                    }
                    break;
                case Conditional.ACTION_SET_SIGNAL_HELD:
                    h = (SignalHead) nb;
                    if (h == null) {
                        errorList.add("invalid Signal Head name in action - " + action.getDeviceName());
                    } else {
                        h.setHeld(true);
                        actionCount++;
                    }
                    break;
                case Conditional.ACTION_CLEAR_SIGNAL_HELD:
                    h = (SignalHead) nb;
                    if (h == null) {
                        errorList.add("invalid Signal Head name in action - " + action.getDeviceName());
                    } else {
                        h.setHeld(false);
                        actionCount++;
                    }
                    break;
                case Conditional.ACTION_SET_SIGNAL_DARK:
                    h = (SignalHead) nb;
                    if (h == null) {
                        errorList.add("invalid Signal Head name in action - " + action.getDeviceName());
                    } else {
                        h.setLit(false);
                        actionCount++;
                    }
                    break;
                case Conditional.ACTION_SET_SIGNAL_LIT:
                    h = (SignalHead) nb;
                    if (h == null) {
                        errorList.add("invalid Signal Head name in action - " + action.getDeviceName());
                    } else {
                        h.setLit(true);
                        actionCount++;
                    }
                    break;
                case Conditional.ACTION_TRIGGER_ROUTE:
                    Route r = (Route) nb;
                    if (r == null) {
                        errorList.add("invalid Route name in action - " + action.getDeviceName());
                    } else {
                        r.setRoute();
                        actionCount++;
                    }
                    break;
                case Conditional.ACTION_SET_SENSOR:
                    Sensor sn = (Sensor) nb;
                    if (sn == null) {
                        errorList.add("invalid Sensor name in action - " + action.getDeviceName());
                    } else {
                        act = action.getActionData();
                        if (act == Route.TOGGLE) {
                            state = sn.getState();
                            if (state == Sensor.ACTIVE) {
                                act = Sensor.INACTIVE;
                            } else {
                                act = Sensor.ACTIVE;
                            }
                        }
                        try {
                            sn.setKnownState(act);
                            actionCount++;
                        } catch (JmriException e) {
                            log.warn("Exception setting Sensor " + devName + " in action");
                        }
                    }
                    break;
                case Conditional.ACTION_RESET_DELAYED_SENSOR:
                    action.stopTimer();
                // fall through
                case Conditional.ACTION_DELAYED_SENSOR:
                    if (!action.isTimerActive()) {
                        // Create a timer if one does not exist
                        timer = action.getTimer();
                        if (timer == null) {
                            action.setListener(new TimeSensor(i));
                            timer = new Timer(2000, action.getListener());
                            timer.setRepeats(true);
                        }
                        // Start the Timer to set the turnout
                        value = getMillisecondValue(action);
                        if (value < 0) {
                            break;
                        }
                        timer.setInitialDelay(value);
                        action.setTimer(timer);
                        action.startTimer();
                        actionCount++;
                    } else {
                        log.warn("timer already active on request to start delayed sensor action - " + devName);
                    }
                    break;
                case Conditional.ACTION_CANCEL_SENSOR_TIMERS:
                    ConditionalManager cm = jmri.InstanceManager.getDefault(jmri.ConditionalManager.class);
                    java.util.Iterator<String> itr = cm.getSystemNameList().iterator();
                    while (itr.hasNext()) {
                        String sname = itr.next();
                        if (sname == null) {
                            errorList.add("Conditional system name null during cancel sensor timers for " + action.getDeviceName());
                        }
                        Conditional c = cm.getBySystemName(sname);
                        if (c == null) {
                            errorList.add("Conditional null during cancel sensor timers for " + action.getDeviceName());
                        } else {
                            c.cancelSensorTimer(devName);
                            actionCount++;
                        }
                    }
                    break;
                case Conditional.ACTION_SET_LIGHT:
                    lgt = (Light) nb;
                    if (lgt == null) {
                        errorList.add("invalid light name in action - " + action.getDeviceName());
                    } else {
                        act = action.getActionData();
                        if (act == Route.TOGGLE) {
                            state = lgt.getState();
                            if (state == Light.ON) {
                                act = Light.OFF;
                            } else {
                                act = Light.ON;
                            }
                        }
                        lgt.setState(act);
                        actionCount++;
                    }
                    break;
                case Conditional.ACTION_SET_LIGHT_INTENSITY:
                    lgt = (Light) nb;
                    if (lgt == null) {
                        errorList.add("invalid light name in action - " + action.getDeviceName());
                    } else {
                        try {
                            value = getIntegerValue(action);
                            if (value < 0) {
                                break;
                            }
                            lgt.setTargetIntensity((value) / 100.0);
                            actionCount++;
                        } catch (IllegalArgumentException e) {
                            errorList.add("Exception in set light intensity action - " + action.getDeviceName());
                        }
                    }
                    break;
                case Conditional.ACTION_SET_LIGHT_TRANSITION_TIME:
                    lgt = (Light) nb;
                    if (lgt == null) {
                        errorList.add("invalid light name in action - " + action.getDeviceName());
                    } else {
                        try {
                            value = getIntegerValue(action);
                            if (value < 0) {
                                break;
                            }
                            lgt.setTransitionTime(value);
                            actionCount++;
                        } catch (IllegalArgumentException e) {
                            errorList.add("Exception in set light transition time action - " + action.getDeviceName());
                        }
                    }
                    break;
                case Conditional.ACTION_SET_MEMORY:
                    Memory m = (Memory) nb;
                    if (m == null) {
                        errorList.add("invalid memory name in action - " + action.getDeviceName());
                    } else {
                        m.setValue(action.getActionString());
                        actionCount++;
                    }
                    break;
                case Conditional.ACTION_COPY_MEMORY:
                    Memory mFrom = (Memory) nb;
                    if (mFrom == null) {
                        errorList.add("invalid memory name in action - " + action.getDeviceName());
                    } else {
                        Memory mTo = getMemory(action.getActionString());
                        if (mTo == null) {
                            errorList.add("invalid memory name in action - " + action.getActionString());
                        } else {
                            mTo.setValue(mFrom.getValue());
                            actionCount++;
                        }
                    }
                    break;
                case Conditional.ACTION_ENABLE_LOGIX:
                    x = InstanceManager.getDefault(jmri.LogixManager.class).getLogix(devName);
                    if (x == null) {
                        errorList.add("invalid logix name in action - " + action.getDeviceName());
                    } else {
                        x.setEnabled(true);
                        actionCount++;
                    }
                    break;
                case Conditional.ACTION_DISABLE_LOGIX:
                    x = InstanceManager.getDefault(jmri.LogixManager.class).getLogix(devName);
                    if (x == null) {
                        errorList.add("invalid logix name in action - " + action.getDeviceName());
                    } else {
                        x.setEnabled(false);
                        actionCount++;
                    }
                    break;
                case Conditional.ACTION_PLAY_SOUND:
                    String path = getActionString(action);
                    if (!path.equals("")) {
                        Sound sound = action.getSound();
                        if (sound == null) {
                            try {
                                sound = new Sound(path);
                            } catch (NullPointerException ex) {
                                errorList.add("invalid path to sound: " + path);
                            }
                        }
                        if (sound != null) {
                            sound.play();
                        }
                        actionCount++;
                    }
                    break;
                case Conditional.ACTION_RUN_SCRIPT:
                    if (!(getActionString(action).equals(""))) {
                        JmriScriptEngineManager.getDefault().runScript(new File(jmri.util.FileUtil.getExternalFilename(getActionString(action))));
                        actionCount++;
                    }
                    break;
                case Conditional.ACTION_SET_FAST_CLOCK_TIME:
                    Date date = InstanceManager.getDefault(jmri.Timebase.class).getTime();
                    date.setHours(action.getActionData() / 60);
                    date.setMinutes(action.getActionData() - ((action.getActionData() / 60) * 60));
                    date.setSeconds(0);
                    InstanceManager.getDefault(jmri.Timebase.class).userSetTime(date);
                    actionCount++;
                    break;
                case Conditional.ACTION_START_FAST_CLOCK:
                    InstanceManager.getDefault(jmri.Timebase.class).setRun(true);
                    actionCount++;
                    break;
                case Conditional.ACTION_STOP_FAST_CLOCK:
                    InstanceManager.getDefault(jmri.Timebase.class).setRun(false);
                    actionCount++;
                    break;
                case Conditional.ACTION_CONTROL_AUDIO:
                    Audio audio = InstanceManager.getDefault(jmri.AudioManager.class).getAudio(devName);
                    if (audio.getSubType() == Audio.SOURCE) {
                        AudioSource audioSource = (AudioSource) audio;
                        switch(action.getActionData()) {
                            case Audio.CMD_PLAY:
                                audioSource.play();
                                break;
                            case Audio.CMD_STOP:
                                audioSource.stop();
                                break;
                            case Audio.CMD_PLAY_TOGGLE:
                                audioSource.togglePlay();
                                break;
                            case Audio.CMD_PAUSE:
                                audioSource.pause();
                                break;
                            case Audio.CMD_RESUME:
                                audioSource.resume();
                                break;
                            case Audio.CMD_PAUSE_TOGGLE:
                                audioSource.togglePause();
                                break;
                            case Audio.CMD_REWIND:
                                audioSource.rewind();
                                break;
                            case Audio.CMD_FADE_IN:
                                audioSource.fadeIn();
                                break;
                            case Audio.CMD_FADE_OUT:
                                audioSource.fadeOut();
                                break;
                            case Audio.CMD_RESET_POSITION:
                                audioSource.resetCurrentPosition();
                                break;
                            default:
                                break;
                        }
                    } else if (audio.getSubType() == Audio.LISTENER) {
                        AudioListener audioListener = (AudioListener) audio;
                        switch(action.getActionData()) {
                            case Audio.CMD_RESET_POSITION:
                                audioListener.resetCurrentPosition();
                                break;
                            default:
                                // nothing needed for others
                                break;
                        }
                    }
                    break;
                case Conditional.ACTION_JYTHON_COMMAND:
                    if (!(getActionString(action).isEmpty())) {
                        // add the text to the output frame
                        ScriptOutput.writeScript(getActionString(action));
                        // and execute
                        try {
                            JmriScriptEngineManager.getDefault().eval(getActionString(action), JmriScriptEngineManager.getDefault().getEngine(JmriScriptEngineManager.PYTHON));
                        } catch (ScriptException ex) {
                            log.error("Error executing script:", ex);
                        }
                        actionCount++;
                    }
                    break;
                case Conditional.ACTION_ALLOCATE_WARRANT_ROUTE:
                    w = (Warrant) nb;
                    if (w == null) {
                        errorList.add("invalid Warrant name in action - " + action.getDeviceName());
                    } else {
                        String msg = w.allocateRoute(null);
                        if (msg != null) {
                            log.info("Warrant " + action.getDeviceName() + " - " + msg);
                        }
                        actionCount++;
                    }
                    break;
                case Conditional.ACTION_DEALLOCATE_WARRANT_ROUTE:
                    w = (Warrant) nb;
                    if (w == null) {
                        errorList.add("invalid Warrant name in action - " + action.getDeviceName());
                    } else {
                        w.deAllocate();
                        actionCount++;
                    }
                    break;
                case Conditional.ACTION_SET_ROUTE_TURNOUTS:
                    w = (Warrant) nb;
                    if (w == null) {
                        errorList.add("invalid Warrant name in action - " + action.getDeviceName());
                    } else {
                        String msg = w.setRoute(0, null);
                        if (msg != null) {
                            log.info("Warrant " + action.getDeviceName() + " unable to Set Route - " + msg);
                        }
                        actionCount++;
                    }
                    break;
                case Conditional.ACTION_THROTTLE_FACTOR:
                    log.info("Set warrant Throttle Factor deprecated - Use Warrrant Preferences");
                    break;
                case Conditional.ACTION_SET_TRAIN_ID:
                    w = (Warrant) nb;
                    if (w == null) {
                        errorList.add("invalid Warrant name in action - " + action.getDeviceName());
                    } else {
                        if (!w.setTrainId(getActionString(action))) {
                            String s = "Unable to find train Id " + getActionString(action) + " in Roster  - " + action.getDeviceName();
                            log.info(s);
                            // could be serious - display error to UI
                            errorList.add(s);
                        }
                        actionCount++;
                    }
                    break;
                case Conditional.ACTION_SET_TRAIN_NAME:
                    w = (Warrant) nb;
                    if (w == null) {
                        errorList.add("invalid Warrant name in action - " + action.getDeviceName());
                    } else {
                        w.setTrainName(getActionString(action));
                        actionCount++;
                    }
                    break;
                case Conditional.ACTION_AUTO_RUN_WARRANT:
                    w = (Warrant) nb;
                    if (w == null) {
                        errorList.add("invalid Warrant name in action - " + action.getDeviceName());
                    } else {
                        jmri.jmrit.logix.WarrantTableFrame frame = jmri.jmrit.logix.WarrantTableFrame.getDefault();
                        String err = frame.runTrain(w, Warrant.MODE_RUN);
                        if (err != null) {
                            w.stopWarrant(true);
                        }
                        if (err != null) {
                            errorList.add("runAutoTrain error - " + err);
                            w.stopWarrant(true);
                        }
                        actionCount++;
                    }
                    break;
                case Conditional.ACTION_MANUAL_RUN_WARRANT:
                    w = (Warrant) nb;
                    if (w == null) {
                        errorList.add("invalid Warrant name in action - " + action.getDeviceName());
                    } else {
                        String err = w.setRoute(0, null);
                        if (err == null) {
                            err = w.setRunMode(Warrant.MODE_MANUAL, null, null, null, false);
                        }
                        if (err != null) {
                            errorList.add("runManualTrain error - " + err);
                        }
                        actionCount++;
                    }
                    break;
                case Conditional.ACTION_CONTROL_TRAIN:
                    w = (Warrant) nb;
                    if (w == null) {
                        errorList.add("invalid Warrant name in action - " + action.getDeviceName());
                    } else {
                        if (!w.controlRunTrain(action.getActionData())) {
                            log.info("Train " + w.getTrainId() + " not running  - " + devName);
                        }
                        actionCount++;
                    }
                    break;
                case Conditional.ACTION_SET_SIGNALMAST_ASPECT:
                    f = (SignalMast) nb;
                    if (f == null) {
                        errorList.add("invalid Signal Mast name in action - " + action.getDeviceName());
                    } else {
                        f.setAspect(getActionString(action));
                        actionCount++;
                    }
                    break;
                case Conditional.ACTION_SET_SIGNALMAST_HELD:
                    f = (SignalMast) nb;
                    if (f == null) {
                        errorList.add("invalid Signal Mast name in action - " + action.getDeviceName());
                    } else {
                        f.setHeld(true);
                        actionCount++;
                    }
                    break;
                case Conditional.ACTION_CLEAR_SIGNALMAST_HELD:
                    f = (SignalMast) nb;
                    if (f == null) {
                        errorList.add("invalid Signal Mast name in action - " + action.getDeviceName());
                    } else {
                        f.setHeld(false);
                        actionCount++;
                    }
                    break;
                case Conditional.ACTION_SET_SIGNALMAST_DARK:
                    f = (SignalMast) nb;
                    if (f == null) {
                        errorList.add("invalid Signal Head name in action - " + action.getDeviceName());
                    } else {
                        f.setLit(false);
                        actionCount++;
                    }
                    break;
                case Conditional.ACTION_SET_SIGNALMAST_LIT:
                    f = (SignalMast) nb;
                    if (f == null) {
                        errorList.add("invalid Signal Head name in action - " + action.getDeviceName());
                    } else {
                        f.setLit(true);
                        actionCount++;
                    }
                    break;
                case Conditional.ACTION_SET_BLOCK_VALUE:
                    OBlock b = (OBlock) nb;
                    if (b == null) {
                        errorList.add("invalid Block name in action - " + action.getDeviceName());
                    } else {
                        b.setValue(getActionString(action));
                        actionCount++;
                    }
                    break;
                case Conditional.ACTION_SET_BLOCK_ERROR:
                    b = (OBlock) nb;
                    if (b == null) {
                        errorList.add("invalid Block name in action - " + action.getDeviceName());
                    } else {
                        b.setError(true);
                        actionCount++;
                    }
                    break;
                case Conditional.ACTION_CLEAR_BLOCK_ERROR:
                    b = (OBlock) nb;
                    if (b == null) {
                        errorList.add("invalid Block name in action - " + action.getDeviceName());
                    } else {
                        b.setError(false);
                    }
                    break;
                case ACTION_DEALLOCATE_BLOCK:
                    b = (OBlock) nb;
                    if (b == null) {
                        errorList.add("invalid Block name in action - " + action.getDeviceName());
                    } else {
                        b.deAllocate(null);
                        actionCount++;
                    }
                    break;
                case ACTION_SET_BLOCK_OUT_OF_SERVICE:
                    b = (OBlock) nb;
                    if (b == null) {
                        errorList.add("invalid Block name in action - " + action.getDeviceName());
                    } else {
                        b.setOutOfService(true);
                        actionCount++;
                    }
                    break;
                case ACTION_SET_BLOCK_IN_SERVICE:
                    b = (OBlock) nb;
                    if (b == null) {
                        errorList.add("invalid Block name in action - " + action.getDeviceName());
                    } else {
                        b.setOutOfService(false);
                        actionCount++;
                    }
                    break;
                default:
                    log.warn("takeActionIfNeeded drops through switch statement for action " + i + " of " + getSystemName());
                    break;
            }
        }
        if (PARKS_DEBUG) {
            System.out.println("Global state= " + _currentState + " Local state= " + currentState + " - Action " + (actionNeeded > neededAction ? "WAS" : "NOT") + " taken for action = " + action.getTypeString() + " " + action.getActionString() + " for device " + action.getDeviceName());
        }
    }
    if (errorList.size() > 0) {
        for (int i = 0; i < errorList.size(); i++) {
            log.error(getDisplayName() + " - " + errorList.get(i));
        }
        if (!GraphicsEnvironment.isHeadless()) {
            java.awt.Toolkit.getDefaultToolkit().beep();
            if (!_skipErrorDialog) {
                new ErrorDialog(errorList, this);
            }
        }
    }
    if (log.isDebugEnabled()) {
        log.debug("Conditional \"" + getUserName() + "\" (" + getSystemName() + " has " + _actionList.size() + " actions and has executed " + actionCount + " actions of " + actionNeeded + " actions needed on state change to " + currentState);
    }
    if (PARKS_DEBUG) {
        System.out.println("Conditional \"" + getUserName() + "\" (" + getSystemName() + " has " + _actionList.size() + " actions and has executed " + actionCount + " actions of " + actionNeeded + " actions needed on state change to " + currentState);
    }
}
Also used : Warrant(jmri.jmrit.logix.Warrant) NamedBean(jmri.NamedBean) Memory(jmri.Memory) ArrayList(java.util.ArrayList) SignalHead(jmri.SignalHead) Conditional(jmri.Conditional) ScriptException(javax.script.ScriptException) ConditionalAction(jmri.ConditionalAction) Light(jmri.Light) SignalMast(jmri.SignalMast) OBlock(jmri.jmrit.logix.OBlock) Route(jmri.Route) AudioListener(jmri.jmrit.audio.AudioListener) JmriException(jmri.JmriException) Sound(jmri.jmrit.Sound) Date(java.util.Date) AudioSource(jmri.jmrit.audio.AudioSource) Logix(jmri.Logix) Timer(javax.swing.Timer) ConditionalManager(jmri.ConditionalManager) Audio(jmri.Audio) Turnout(jmri.Turnout) File(java.io.File) Sensor(jmri.Sensor) SuppressFBWarnings(edu.umd.cs.findbugs.annotations.SuppressFBWarnings)

Example 2 with AudioListener

use of jmri.jmrit.audio.AudioListener in project JMRI by JMRI.

the class AudioListenerFrame method applyPressed.

void applyPressed(ActionEvent e) {
    String user = userName.getText();
    if (user.equals("")) {
        user = null;
    }
    String sName = sysName.getText().toUpperCase();
    AudioListener l;
    try {
        l = (AudioListener) InstanceManager.getDefault(jmri.AudioManager.class).provideAudio(sName);
        l.setUserName(user);
        l.setPosition(position.getValue());
        l.setVelocity(velocity.getValue());
        l.setOrientation(oriAt.getValue(), oriUp.getValue());
        l.setGain(gain.getValue());
        l.setMetersPerUnit(AbstractAudio.roundDecimal((Float) metersPerUnit.getValue(), 4d));
        // Notify changes
        model.fireTableDataChanged();
    } catch (AudioException | IllegalArgumentException ex) {
        JOptionPane.showMessageDialog(null, ex.getMessage(), Bundle.getMessage("AudioCreateErrorTitle"), JOptionPane.ERROR_MESSAGE);
    }
}
Also used : AudioListener(jmri.jmrit.audio.AudioListener) AudioException(jmri.AudioException)

Example 3 with AudioListener

use of jmri.jmrit.audio.AudioListener in project JMRI by JMRI.

the class AbstractAudioManagerConfigXML method store.

/**
     * Default implementation for storing the contents of a AudioManager
     *
     * @param o Object to store, of type AudioManager
     * @return Element containing the complete info
     */
@Override
public Element store(Object o) {
    Element audio = new Element("audio");
    setStoreElementClass(audio);
    AudioManager am = (AudioManager) o;
    if (am != null) {
        java.util.Iterator<String> iter = am.getSystemNameList().iterator();
        // don't return an element if there are not any audios to include
        if (!iter.hasNext()) {
            return null;
        }
        // (no need to store the automatically created Listener object by itself)
        if (am.getSystemNameList(Audio.SOURCE).isEmpty() && am.getSystemNameList(Audio.BUFFER).isEmpty()) {
            return null;
        }
        // finally, don't store if the only Sources and Buffers are for the
        // virtual sound decoder (VSD)
        int vsdObjectCount = 0;
        // count all VSD objects
        for (String sname : am.getSystemNameList()) {
            if (log.isDebugEnabled()) {
                log.debug("Check if " + sname + " is a VSD object");
            }
            if (sname.length() >= 8 && sname.substring(3, 8).equalsIgnoreCase("$VSD:")) {
                log.debug("...yes");
                vsdObjectCount++;
            }
        }
        if (log.isDebugEnabled()) {
            log.debug("Found " + vsdObjectCount + " VSD objects of " + am.getSystemNameList(Audio.SOURCE).size() + am.getSystemNameList(Audio.BUFFER).size() + " objects");
        }
        // the number of VSD objects - if so, exit.
        if (am.getSystemNameList(Audio.SOURCE).size() + am.getSystemNameList(Audio.BUFFER).size() == vsdObjectCount) {
            log.debug("Only VSD objects - nothing to store");
            return null;
        }
        // store global information
        audio.setAttribute("distanceattenuated", am.getActiveAudioFactory().isDistanceAttenuated() ? "yes" : "no");
        // store the audios
        while (iter.hasNext()) {
            String sname = iter.next();
            if (sname == null) {
                log.error("System name null during store");
                continue;
            }
            if (log.isDebugEnabled()) {
                log.debug("system name is " + sname);
            }
            if (sname.length() >= 8 && sname.substring(3, 8).equalsIgnoreCase("$VSD:")) {
                if (log.isDebugEnabled()) {
                    log.debug("Skipping storage of VSD object " + sname);
                }
                continue;
            }
            Audio a = am.getBySystemName(sname);
            // Transient objects for current element and any children
            Element e = null;
            Element ce = null;
            int type = a.getSubType();
            if (type == Audio.BUFFER) {
                AudioBuffer ab = (AudioBuffer) a;
                e = new Element("audiobuffer").setAttribute("systemName", sname);
                e.addContent(new Element("systemName").addContent(sname));
                // store common part
                storeCommon(ab, e);
                // store sub-type specific data
                String url = ab.getURL();
                ce = new Element("url").addContent("" + (url.isEmpty() ? "" : FileUtil.getPortableFilename(url)));
                e.addContent(ce);
                ce = new Element("looppoint");
                ce.setAttribute("start", "" + ab.getStartLoopPoint());
                ce.setAttribute("end", "" + ab.getEndLoopPoint());
                e.addContent(ce);
                ce = new Element("streamed");
                ce.addContent("" + (ab.isStreamed() ? "yes" : "no"));
                e.addContent(ce);
            } else if (type == Audio.LISTENER) {
                AudioListener al = (AudioListener) a;
                e = new Element("audiolistener").setAttribute("systemName", sname);
                e.addContent(new Element("systemName").addContent(sname));
                // store common part
                storeCommon(al, e);
                // store sub-type specific data
                ce = new Element("position");
                ce.setAttribute("x", "" + al.getPosition().x);
                ce.setAttribute("y", "" + al.getPosition().y);
                ce.setAttribute("z", "" + al.getPosition().z);
                e.addContent(ce);
                ce = new Element("velocity");
                ce.setAttribute("x", "" + al.getVelocity().x);
                ce.setAttribute("y", "" + al.getVelocity().y);
                ce.setAttribute("z", "" + al.getVelocity().z);
                e.addContent(ce);
                ce = new Element("orientation");
                ce.setAttribute("atX", "" + al.getOrientation(Audio.AT).x);
                ce.setAttribute("atY", "" + al.getOrientation(Audio.AT).y);
                ce.setAttribute("atZ", "" + al.getOrientation(Audio.AT).z);
                ce.setAttribute("upX", "" + al.getOrientation(Audio.UP).x);
                ce.setAttribute("upY", "" + al.getOrientation(Audio.UP).y);
                ce.setAttribute("upZ", "" + al.getOrientation(Audio.UP).z);
                e.addContent(ce);
                ce = new Element("gain");
                ce.addContent("" + al.getGain());
                e.addContent(ce);
                ce = new Element("metersperunit");
                ce.addContent("" + al.getMetersPerUnit());
                e.addContent(ce);
            } else if (type == Audio.SOURCE) {
                AudioSource as = (AudioSource) a;
                e = new Element("audiosource").setAttribute("systemName", sname);
                e.addContent(new Element("systemName").addContent(sname));
                // store common part
                storeCommon(as, e);
                // store sub-type specific data
                ce = new Element("position");
                ce.setAttribute("x", "" + as.getPosition().x);
                ce.setAttribute("y", "" + as.getPosition().y);
                ce.setAttribute("z", "" + as.getPosition().z);
                e.addContent(ce);
                ce = new Element("velocity");
                ce.setAttribute("x", "" + as.getVelocity().x);
                ce.setAttribute("y", "" + as.getVelocity().y);
                ce.setAttribute("z", "" + as.getVelocity().z);
                e.addContent(ce);
                ce = new Element("assignedbuffer");
                if (as.getAssignedBuffer() != null) {
                    ce.addContent("" + as.getAssignedBufferName());
                }
                e.addContent(ce);
                ce = new Element("gain");
                ce.addContent("" + as.getGain());
                e.addContent(ce);
                ce = new Element("pitch");
                ce.addContent("" + as.getPitch());
                e.addContent(ce);
                ce = new Element("distances");
                ce.setAttribute("ref", "" + as.getReferenceDistance());
                float f = as.getMaximumDistance();
                ce.setAttribute("max", "" + f);
                e.addContent(ce);
                ce = new Element("loops");
                ce.setAttribute("min", "" + as.getMinLoops());
                ce.setAttribute("max", "" + as.getMaxLoops());
                //                    ce.setAttribute("mindelay", ""+as.getMinLoopDelay());
                //                    ce.setAttribute("maxdelay", ""+as.getMaxLoopDelay());
                e.addContent(ce);
                ce = new Element("fadetimes");
                ce.setAttribute("in", "" + as.getFadeIn());
                ce.setAttribute("out", "" + as.getFadeOut());
                e.addContent(ce);
                ce = new Element("dopplerfactor");
                ce.addContent("" + as.getDopplerFactor());
                e.addContent(ce);
                ce = new Element("positionrelative");
                ce.addContent("" + (as.isPositionRelative() ? "yes" : "no"));
                e.addContent(ce);
            }
            log.debug("store Audio " + sname);
            audio.addContent(e);
        }
    }
    return audio;
}
Also used : AudioSource(jmri.jmrit.audio.AudioSource) AudioManager(jmri.AudioManager) Element(org.jdom2.Element) AudioListener(jmri.jmrit.audio.AudioListener) AudioBuffer(jmri.jmrit.audio.AudioBuffer) Audio(jmri.Audio)

Example 4 with AudioListener

use of jmri.jmrit.audio.AudioListener in project JMRI by JMRI.

the class AbstractAudioManagerConfigXML method loadAudio.

/**
     * Utility method to load the individual Audio objects. If there's no
     * additional info needed for a specific Audio type, invoke this with the
     * parent of the set of Audio elements.
     *
     * @param audio Element containing the Audio elements to load.
     */
@SuppressWarnings("unchecked")
public void loadAudio(Element audio) {
    AudioManager am = InstanceManager.getDefault(jmri.AudioManager.class);
    // Count number of loaded Audio objects
    int loadedObjects = 0;
    // Load buffers first
    List<Element> audioList = audio.getChildren("audiobuffer");
    if (log.isDebugEnabled()) {
        log.debug("Found " + audioList.size() + " Audio Buffer objects");
    }
    for (int i = 0; i < audioList.size(); i++) {
        Element e = audioList.get(i);
        String sysName = getSystemName(e);
        if (sysName == null) {
            log.warn("unexpected null in systemName " + (e) + " " + (e).getAttributes());
            break;
        }
        String userName = getUserName(e);
        if (log.isDebugEnabled()) {
            log.debug("create Audio: (" + sysName + ")(" + (userName == null ? "<null>" : userName) + ")");
        }
        try {
            AudioBuffer ab = (AudioBuffer) am.newAudio(sysName, userName);
            // load common parts
            loadCommon(ab, e);
            // load sub-type specific parts
            // Transient objects for reading child elements
            Element ce;
            String value;
            if ((ce = e.getChild("url")) != null) {
                ab.setURL(ce.getValue());
            }
            if ((ce = e.getChild("looppoint")) != null) {
                if ((value = ce.getAttributeValue("start")) != null) {
                    ab.setStartLoopPoint(Integer.parseInt(value));
                }
                if ((value = ce.getAttributeValue("end")) != null) {
                    ab.setEndLoopPoint(Integer.parseInt(value));
                }
            }
            if ((ce = e.getChild("streamed")) != null) {
                ab.setStreamed(ce.getValue().equals("yes"));
            }
        } catch (AudioException ex) {
            log.error("Error loading AudioBuffer (" + sysName + "): " + ex);
        }
    }
    loadedObjects += audioList.size();
    // Now load sources
    audioList = audio.getChildren("audiosource");
    if (log.isDebugEnabled()) {
        log.debug("Found " + audioList.size() + " Audio Source objects");
    }
    for (int i = 0; i < audioList.size(); i++) {
        Element e = audioList.get(i);
        String sysName = getSystemName(e);
        if (sysName == null) {
            log.warn("unexpected null in systemName " + (e) + " " + (e).getAttributes());
            break;
        }
        String userName = getUserName(e);
        if (log.isDebugEnabled()) {
            log.debug("create Audio: (" + sysName + ")(" + (userName == null ? "<null>" : userName) + ")");
        }
        try {
            AudioSource as = (AudioSource) am.newAudio(sysName, userName);
            // load common parts
            loadCommon(as, e);
            // load sub-type specific parts
            // Transient objects for reading child elements
            Element ce;
            String value;
            if ((ce = e.getChild("position")) != null) {
                as.setPosition(new Vector3f(Float.parseFloat(ce.getAttributeValue("x")), Float.parseFloat(ce.getAttributeValue("y")), Float.parseFloat(ce.getAttributeValue("z"))));
            }
            if ((ce = e.getChild("velocity")) != null) {
                as.setVelocity(new Vector3f(Float.parseFloat(ce.getAttributeValue("x")), Float.parseFloat(ce.getAttributeValue("y")), Float.parseFloat(ce.getAttributeValue("z"))));
            }
            if ((ce = e.getChild("assignedbuffer")) != null) {
                if (ce.getValue().length() != 0 && !ce.getValue().equals("null")) {
                    as.setAssignedBuffer(ce.getValue());
                }
            }
            if ((ce = e.getChild("gain")) != null && ce.getValue().length() != 0) {
                as.setGain(Float.parseFloat(ce.getValue()));
            }
            if ((ce = e.getChild("pitch")) != null && ce.getValue().length() != 0) {
                as.setPitch(Float.parseFloat(ce.getValue()));
            }
            if ((ce = e.getChild("distances")) != null) {
                if ((value = ce.getAttributeValue("ref")) != null) {
                    as.setReferenceDistance(Float.parseFloat(value));
                }
                if ((value = ce.getAttributeValue("max")) != null) {
                    as.setMaximumDistance(Float.parseFloat(value));
                }
            }
            if ((ce = e.getChild("loops")) != null) {
                if ((value = ce.getAttributeValue("min")) != null) {
                    as.setMinLoops(Integer.parseInt(value));
                }
                if ((value = ce.getAttributeValue("max")) != null) {
                    as.setMaxLoops(Integer.parseInt(value));
                }
            //                    if ((value = ce.getAttributeValue("mindelay"))!=null)
            //                        as.setMinLoopDelay(Integer.parseInt(value));
            //                    if ((value = ce.getAttributeValue("maxdelay"))!=null)
            //                        as.setMaxLoopDelay(Integer.parseInt(value));
            }
            if ((ce = e.getChild("fadetimes")) != null) {
                if ((value = ce.getAttributeValue("in")) != null) {
                    as.setFadeIn(Integer.parseInt(value));
                }
                if ((value = ce.getAttributeValue("out")) != null) {
                    as.setFadeOut(Integer.parseInt(value));
                }
            }
            if ((ce = e.getChild("dopplerfactor")) != null && ce.getValue().length() != 0) {
                as.setDopplerFactor(Float.parseFloat(ce.getValue()));
            }
            if ((ce = e.getChild("positionrelative")) != null) {
                as.setPositionRelative(ce.getValue().equals("yes"));
            }
        } catch (AudioException ex) {
            log.error("Error loading AudioSource (" + sysName + "): " + ex);
        }
    }
    loadedObjects += audioList.size();
    // Finally, load Listeners if needed
    if (loadedObjects > 0) {
        audioList = audio.getChildren("audiolistener");
        if (log.isDebugEnabled()) {
            log.debug("Found " + audioList.size() + " Audio Listener objects");
        }
        for (int i = 0; i < audioList.size(); i++) {
            Element e = audioList.get(i);
            String sysName = getSystemName(e);
            if (sysName == null) {
                log.warn("unexpected null in systemName " + (e) + " " + (e).getAttributes());
                break;
            }
            String userName = getUserName(e);
            if (log.isDebugEnabled()) {
                log.debug("create Audio: (" + sysName + ")(" + (userName == null ? "<null>" : userName) + ")");
            }
            try {
                AudioListener al = (AudioListener) am.newAudio(sysName, userName);
                // load common parts
                loadCommon(al, e);
                // load sub-type specific parts
                // Transient object for reading child elements
                Element ce;
                if ((ce = e.getChild("position")) != null) {
                    al.setPosition(new Vector3f(Float.parseFloat(ce.getAttributeValue("x")), Float.parseFloat(ce.getAttributeValue("y")), Float.parseFloat(ce.getAttributeValue("z"))));
                }
                if ((ce = e.getChild("velocity")) != null) {
                    al.setVelocity(new Vector3f(Float.parseFloat(ce.getAttributeValue("x")), Float.parseFloat(ce.getAttributeValue("y")), Float.parseFloat(ce.getAttributeValue("z"))));
                }
                if ((ce = e.getChild("orientation")) != null) {
                    al.setOrientation(new Vector3f(Float.parseFloat(ce.getAttributeValue("atX")), Float.parseFloat(ce.getAttributeValue("atY")), Float.parseFloat(ce.getAttributeValue("atZ"))), new Vector3f(Float.parseFloat(ce.getAttributeValue("upX")), Float.parseFloat(ce.getAttributeValue("upY")), Float.parseFloat(ce.getAttributeValue("upZ"))));
                }
                if ((ce = e.getChild("gain")) != null) {
                    al.setGain(Float.parseFloat(ce.getValue()));
                }
                if ((ce = e.getChild("metersperunit")) != null) {
                    al.setMetersPerUnit(Float.parseFloat((ce.getValue())));
                }
            } catch (AudioException ex) {
                log.error("Error loading AudioListener (" + sysName + "): " + ex);
            }
        }
        Attribute a;
        if ((a = audio.getAttribute("distanceattenuated")) != null) {
            am.getActiveAudioFactory().setDistanceAttenuated(a.getValue().equals("yes"));
        }
    }
}
Also used : AudioSource(jmri.jmrit.audio.AudioSource) AudioManager(jmri.AudioManager) Attribute(org.jdom2.Attribute) Element(org.jdom2.Element) AudioException(jmri.AudioException) Vector3f(javax.vecmath.Vector3f) AudioListener(jmri.jmrit.audio.AudioListener) AudioBuffer(jmri.jmrit.audio.AudioBuffer)

Example 5 with AudioListener

use of jmri.jmrit.audio.AudioListener in project JMRI by JMRI.

the class AudioListenerFrame method populateFrame.

/**
     * Method to populate the Edit Listener frame with current values
     */
@Override
public void populateFrame(Audio a) {
    if (!(a instanceof AudioListener)) {
        throw new IllegalArgumentException(a.getSystemName() + " is not an AudioListener object");
    }
    super.populateFrame(a);
    AudioListener l = (AudioListener) a;
    position.setValue(l.getPosition());
    velocity.setValue(l.getVelocity());
    oriAt.setValue(l.getOrientation(Audio.AT));
    oriUp.setValue(l.getOrientation(Audio.UP));
    gain.setValue(l.getGain());
    metersPerUnit.setValue(l.getMetersPerUnit());
}
Also used : AudioListener(jmri.jmrit.audio.AudioListener)

Aggregations

AudioListener (jmri.jmrit.audio.AudioListener)5 AudioSource (jmri.jmrit.audio.AudioSource)3 Audio (jmri.Audio)2 AudioException (jmri.AudioException)2 AudioManager (jmri.AudioManager)2 AudioBuffer (jmri.jmrit.audio.AudioBuffer)2 Element (org.jdom2.Element)2 SuppressFBWarnings (edu.umd.cs.findbugs.annotations.SuppressFBWarnings)1 File (java.io.File)1 ArrayList (java.util.ArrayList)1 Date (java.util.Date)1 ScriptException (javax.script.ScriptException)1 Timer (javax.swing.Timer)1 Vector3f (javax.vecmath.Vector3f)1 Conditional (jmri.Conditional)1 ConditionalAction (jmri.ConditionalAction)1 ConditionalManager (jmri.ConditionalManager)1 JmriException (jmri.JmriException)1 Light (jmri.Light)1 Logix (jmri.Logix)1