001package jmri.jmrix.loconet;
002
003import jmri.implementation.AbstractLight;
004import org.slf4j.Logger;
005import org.slf4j.LoggerFactory;
006
007/**
008 * Implementation of the Light Object for LocoNet
009 * <p>
010 * Based in part on SerialLight.java
011 *
012 * @author Dave Duchamp Copyright (C) 2006
013 */
014public class LnLight extends AbstractLight {
015
016    /**
017     * Create a Light object, with only system name.
018     * <p>
019     * 'systemName' was previously validated in LnLightManager
020     * 
021     * @param systemName for the new bean
022     * @param tc the LnTrafficController which handles the messaging
023     * @param mgr the LnLightManager which manages this type of object bean
024     */
025    public LnLight(String systemName, LnTrafficController tc, LnLightManager mgr) {
026        super(systemName);
027        this.tc = tc;
028        this.mgr = mgr;
029        // Initialize the Light
030        initializeLight(systemName);
031    }
032
033    /**
034     * Create a Light object, with both system and user names.
035     * <p>
036     * 'systemName' was previously validated in LnLightManager
037     * 
038     * @param systemName for the new bean
039     * @param userName for the new bean
040     * @param tc the LnTrafficController which handles the messaging
041     * @param mgr the LnLightManager which manages this type of object bean
042     */
043    public LnLight(String systemName, String userName, LnTrafficController tc, LnLightManager mgr) {
044        super(systemName, userName);
045        this.tc = tc;
046        this.mgr = mgr;
047        initializeLight(systemName);
048    }
049
050    LnTrafficController tc;
051    LnLightManager mgr;
052
053    private void initializeLight(String systemName) {
054        // Extract the Bit from the name
055        mBit = mgr.getBitFromSystemName(systemName);
056        // Set initial state
057        setState(OFF);
058    }
059
060    int mBit = 0;                // address bit
061
062    /**
063     * Set the current state of this Light This routine requests the hardware to
064     * change.
065     */
066    @Override
067    protected void doNewState(int oldState, int newState) {
068        LocoNetMessage l = new LocoNetMessage(4);
069        l.setOpCode(LnConstants.OPC_SW_REQ);
070        // compute address fields
071        int hiadr = (mBit - 1) / 128;
072        int loadr = (mBit - 1) - hiadr * 128;
073        // set bits for ON/OFF
074        if (newState == ON) {
075            hiadr |= 0x30;
076        } else if (newState == OFF) {
077            hiadr |= 0x10;
078        } else {
079            log.warn("illegal state requested for Light: {}", getSystemName());
080            hiadr |= 0x10;
081        }
082        // store and send
083        l.setElement(1, loadr);
084        l.setElement(2, hiadr);
085        tc.sendLocoNetMessage(l);
086    }
087
088    private final static Logger log = LoggerFactory.getLogger(LnLight.class);
089
090}