001package jmri.jmrix.ipocs;
002
003import org.slf4j.Logger;
004import org.slf4j.LoggerFactory;
005
006import jmri.Sensor;
007import jmri.implementation.AbstractSensor;
008
009import jmri.jmrix.ipocs.protocol.Message;
010import jmri.jmrix.ipocs.protocol.packets.InputStatusPacket;
011import jmri.jmrix.ipocs.protocol.packets.Packet;
012import jmri.jmrix.ipocs.protocol.packets.RequestStatusPacket;
013
014/**
015 *
016 * @author Fredrik Elestedt Copyright (C) 2020
017 * @since 4.21.2
018 */
019public class IpocsSensor extends AbstractSensor implements IpocsClientListener {
020  private final static Logger log = LoggerFactory.getLogger(IpocsSensor.class);
021  private final IpocsPortController portController;
022
023  public IpocsSensor(IpocsPortController portController, String systemName, String userName) {
024    super(systemName, userName);
025    this.portController = portController;
026    this.portController.addListener(this);
027  }
028
029  @Override
030  public void requestUpdateFromLayout() {
031    Message order = new Message();
032    order.setObjectName(getUserName());
033    RequestStatusPacket packet = new RequestStatusPacket();
034    order.getPackets().add(packet);
035    portController.send(order);
036  }
037
038  @Override
039  public void clientConnected(IpocsClientHandler client) {
040  }
041
042  @Override
043  public void clientDisconnected(IpocsClientHandler client) {
044    setOwnState(Sensor.UNKNOWN);
045  }
046
047  @Override
048  public void onMessage(IpocsClientHandler client, Message msg) {
049    if (!msg.getObjectName().equals(super.getUserName())) {
050      return;
051    }
052    // We have a status, let's interpret it.
053    for (Packet packet : msg.getPackets()) {
054      switch (packet.getId()) {
055        case InputStatusPacket.IDENT:
056          switch (((InputStatusPacket) packet).getState()) {
057            case On:
058              setOwnState(Sensor.ON);
059              break;
060            case Off:
061              setOwnState(Sensor.OFF);
062              break;
063            case Undefined:
064              setOwnState(Sensor.UNKNOWN);
065              break;
066            default:
067              log.error("Unknown sensor state {}", ((InputStatusPacket)packet).getState().toString());
068              break;
069          }
070          break;
071        default:
072          break;
073      }
074    }
075  }
076}