001package jmri.jmrix.rfid.generic.standalone;
002
003import javax.annotation.Nonnull;
004import jmri.IdTag;
005import jmri.IdTagManager;
006import jmri.InstanceManager;
007import jmri.Reporter;
008import jmri.implementation.decorators.TimeoutReporter;
009import jmri.jmrix.rfid.*;
010import org.slf4j.Logger;
011import org.slf4j.LoggerFactory;
012
013/**
014 * Rfid implementation of a ReporterManager.
015 * <p>
016 * System names are "FRpppp", where ppp is a representation of the RFID reader.
017 *
018 * @author Bob Jacobsen Copyright (C) 2008
019 * @author Matthew Harris Copyright (C) 2011
020 * @since 2.11.4
021 */
022public class StandaloneReporterManager extends RfidReporterManager {
023
024    private final RfidTrafficController tc;
025
026    public StandaloneReporterManager(RfidSystemConnectionMemo memo) {
027        super(memo);
028        this.tc = memo.getTrafficController();
029        attach();
030    }
031
032    private void attach() {
033        tc.addRfidListener(this);
034    }
035
036    @Override
037    @Nonnull
038    protected Reporter createNewReporter(@Nonnull String systemName, String userName) throws IllegalArgumentException {
039        log.debug("Create new Reporter: {}", systemName);
040        if (!systemName.matches(getSystemNamePrefix() + "[" + tc.getRange() + "]")) {
041            log.warn("Invalid Reporter name: {} - out of supported range {}", systemName, tc.getRange());
042            throw new IllegalArgumentException("Invalid Reporter name: " + systemName + " - out of supported range " + tc.getRange());
043        }
044        Reporter r;
045        r = new TimeoutReporter( new RfidReporter(systemName, userName));
046        r.addPropertyChangeListener(this);
047        return r;
048    }
049
050    @Override
051    public void message(RfidMessage m) {
052        if (m.toString().equals(new StandaloneMessage(tc.getAdapterMemo().getProtocol().initString(), 0).toString())) {
053            log.info("Sent init string: {}", m);
054        } else {
055            super.message(m);
056        }
057    }
058
059    @Override
060    public synchronized void reply(RfidReply r) {
061        if (r instanceof StandaloneReply) {
062            processReply((StandaloneReply) r);
063        }
064    }
065
066    private void processReply(StandaloneReply r) {
067        if (!tc.getAdapterMemo().getProtocol().isValid(r)) {
068            log.warn("Invalid message - skipping {}", r);
069            return;
070        }
071        IdTag idTag = InstanceManager.getDefault(IdTagManager.class).provideIdTag(tc.getAdapterMemo().getProtocol().getTag(r));
072        TimeoutReporter report = (TimeoutReporter) provideReporter(getSystemNamePrefix() + "1");
073        report.notify(idTag);
074    }
075
076    private static final Logger log = LoggerFactory.getLogger(StandaloneReporterManager.class);
077
078}