Search in sources :

Example 1 with PacketListReceiver

use of me.retrodaredevil.solarthing.packets.handling.PacketListReceiver in project solarthing by wildmountainfarms.

the class CheckMain method scanForMate.

/*
	Useful command when testing this:
	socat -d -d pty,raw,echo=0 pty,raw,echo=0
	 */
private static boolean scanForMate(String port) throws SerialPortException {
    System.out.println("Going to open serial port using MATE's default serial configuration...");
    try (JSerialIOBundle ioBundle = JSerialIOBundle.createPort(port, OutbackConstants.MATE_CONFIG)) {
        System.out.println("Successfully opened serial port...");
        boolean[] gotAnyData = new boolean[] { false };
        boolean[] parsedData = new boolean[] { false };
        PacketListReceiver receiver = (packets) -> {
            System.out.println("Got " + packets.size() + " packets");
            parsedData[0] = true;
        };
        // Note that lots of this code logs. Users don't see much of the debug logs because they run the solarthing command, which does INFO logging by default
        SolarReader solarReader = new SolarReader(ioBundle.getInputStream(), // we are testing a lot, so we don't care if the checksum is wrong
        new MatePacketCreator49(IgnoreCheckSum.IGNORE_AND_USE_CALCULATED), new TimedPacketReceiver(Duration.ofMillis(250), receiver, (firstData, stale) -> gotAnyData[0] = true));
        try {
            for (int i = 0; i < 40; i++) {
                // do this for about 4 seconds
                try {
                    solarReader.update();
                } catch (EOFException e) {
                    // This should never happen
                    System.err.println("The serial port gave us an EOF. This is unexpected");
                    return false;
                } catch (IOException e) {
                    System.err.println("Error reading from serial port");
                    return false;
                }
                Thread.sleep(100);
            }
        } catch (InterruptedException e) {
            Thread.currentThread().interrupt();
            e.printStackTrace();
            return false;
        }
        if (parsedData[0]) {
            System.out.println("Got data from mate!");
        } else if (gotAnyData[0]) {
            System.out.println("Got some data, but was unable to parse it.");
        } else {
            System.out.println("Got no data from mate!");
        }
        return parsedData[0];
    }
}
Also used : RoverReadTable(me.retrodaredevil.solarthing.solar.renogy.rover.RoverReadTable) TracerModbusSlaveRead(me.retrodaredevil.solarthing.solar.tracer.modbus.TracerModbusSlaveRead) ModbusRuntimeException(me.retrodaredevil.io.modbus.ModbusRuntimeException) NotNull(me.retrodaredevil.solarthing.annotations.NotNull) HelpRequestedException(com.lexicalscope.jewel.cli.HelpRequestedException) Function(java.util.function.Function) IOModbusSlaveBus(me.retrodaredevil.io.modbus.IOModbusSlaveBus) Nullable(me.retrodaredevil.solarthing.annotations.Nullable) ModbusSlave(me.retrodaredevil.io.modbus.ModbusSlave) RoverModbusSlaveRead(me.retrodaredevil.solarthing.solar.renogy.rover.modbus.RoverModbusSlaveRead) Duration(java.time.Duration) ModbusTimeoutException(me.retrodaredevil.io.modbus.ModbusTimeoutException) JSerialIOBundle(me.retrodaredevil.io.serial.JSerialIOBundle) SerialPortException(me.retrodaredevil.io.serial.SerialPortException) MutableAddressModbusSlave(me.retrodaredevil.solarthing.program.modbus.MutableAddressModbusSlave) ArgumentValidationException(com.lexicalscope.jewel.cli.ArgumentValidationException) TimedPacketReceiver(me.retrodaredevil.solarthing.packets.handling.implementations.TimedPacketReceiver) SerialConfig(me.retrodaredevil.io.serial.SerialConfig) OutbackConstants(me.retrodaredevil.solarthing.solar.outback.OutbackConstants) BatteryVoltage(me.retrodaredevil.solarthing.solar.common.BatteryVoltage) Cli(com.lexicalscope.jewel.cli.Cli) ModbusSlaveBus(me.retrodaredevil.io.modbus.ModbusSlaveBus) IOException(java.io.IOException) EOFException(java.io.EOFException) IgnoreCheckSum(me.retrodaredevil.solarthing.util.IgnoreCheckSum) SolarThingConstants(me.retrodaredevil.solarthing.SolarThingConstants) CliFactory(com.lexicalscope.jewel.cli.CliFactory) SolarReader(me.retrodaredevil.solarthing.program.SolarReader) TracerReadTable(me.retrodaredevil.solarthing.solar.tracer.TracerReadTable) MatePacketCreator49(me.retrodaredevil.solarthing.solar.outback.MatePacketCreator49) UtilityClass(me.retrodaredevil.solarthing.annotations.UtilityClass) PacketListReceiver(me.retrodaredevil.solarthing.packets.handling.PacketListReceiver) RtuDataEncoder(me.retrodaredevil.io.modbus.RtuDataEncoder) MatePacketCreator49(me.retrodaredevil.solarthing.solar.outback.MatePacketCreator49) PacketListReceiver(me.retrodaredevil.solarthing.packets.handling.PacketListReceiver) EOFException(java.io.EOFException) SolarReader(me.retrodaredevil.solarthing.program.SolarReader) IOException(java.io.IOException) TimedPacketReceiver(me.retrodaredevil.solarthing.packets.handling.implementations.TimedPacketReceiver) JSerialIOBundle(me.retrodaredevil.io.serial.JSerialIOBundle)

Example 2 with PacketListReceiver

use of me.retrodaredevil.solarthing.packets.handling.PacketListReceiver in project solarthing by wildmountainfarms.

the class PacketListReceiverHandlerBundle method createFrom.

public static <T extends PacketHandlingOption & CommandOption> PacketListReceiverHandlerBundle createFrom(T options, PacketHandlerBundle packetHandlerBundle, List<PacketHandler> statusPacketHandlers) {
    PacketListReceiver sourceAndFragmentUpdater = SolarMain.getSourceAndFragmentUpdater(options);
    PacketListReceiverHandler eventPacketListReceiverHandler = createEventPacketListReceiverHandler(sourceAndFragmentUpdater, options.getZoneId(), packetHandlerBundle);
    PacketListReceiverHandler statusPacketListReceiverHandler = new PacketListReceiverHandler(new PacketListReceiverMultiplexer(sourceAndFragmentUpdater, (packets) -> {
        LOGGER.debug("Debugging all packets");
        try {
            LOGGER.debug(MAPPER.writerWithDefaultPrettyPrinter().writeValueAsString(packets));
        } catch (JsonProcessingException e) {
            LOGGER.debug("Never mind about that...", e);
        }
    }), new PacketHandlerMultiplexer(statusPacketHandlers), SolarMain.createIdGenerator(options.getUniqueIdsInOneHour(), options.isDocumentIdShort()), options.getZoneId());
    return new PacketListReceiverHandlerBundle(statusPacketListReceiverHandler, eventPacketListReceiverHandler);
}
Also used : CommandOption(me.retrodaredevil.solarthing.config.options.CommandOption) Arrays(java.util.Arrays) Logger(org.slf4j.Logger) PacketHandlingOption(me.retrodaredevil.solarthing.config.options.PacketHandlingOption) ObjectMapper(com.fasterxml.jackson.databind.ObjectMapper) LoggerFactory(org.slf4j.LoggerFactory) JsonProcessingException(com.fasterxml.jackson.core.JsonProcessingException) PacketHandler(me.retrodaredevil.solarthing.packets.handling.PacketHandler) PacketCollectionIdGenerator(me.retrodaredevil.solarthing.packets.collection.PacketCollectionIdGenerator) ZoneId(java.time.ZoneId) List(java.util.List) SolarThingConstants(me.retrodaredevil.solarthing.SolarThingConstants) PacketHandlerMultiplexer(me.retrodaredevil.solarthing.packets.handling.PacketHandlerMultiplexer) PacketListReceiverMultiplexer(me.retrodaredevil.solarthing.packets.handling.PacketListReceiverMultiplexer) PacketListReceiver(me.retrodaredevil.solarthing.packets.handling.PacketListReceiver) JacksonUtil(me.retrodaredevil.solarthing.util.JacksonUtil) PacketListReceiverMultiplexer(me.retrodaredevil.solarthing.packets.handling.PacketListReceiverMultiplexer) PacketHandlerMultiplexer(me.retrodaredevil.solarthing.packets.handling.PacketHandlerMultiplexer) PacketListReceiver(me.retrodaredevil.solarthing.packets.handling.PacketListReceiver) JsonProcessingException(com.fasterxml.jackson.core.JsonProcessingException)

Example 3 with PacketListReceiver

use of me.retrodaredevil.solarthing.packets.handling.PacketListReceiver in project solarthing by wildmountainfarms.

the class SolarMain method getSourceAndFragmentUpdater.

public static PacketListReceiver getSourceAndFragmentUpdater(PacketHandlingOption options) {
    String source = options.getSourceId();
    int fragment = options.getFragmentId();
    requireNonNull(source);
    Packet sourcePacket = InstanceSourcePackets.create(source);
    Packet fragmentPacket = InstanceFragmentIndicatorPackets.create(fragment);
    return (list) -> {
        list.add(sourcePacket);
        list.add(fragmentPacket);
    };
}
Also used : Packet(me.retrodaredevil.solarthing.packets.Packet) LoggerFactory(org.slf4j.LoggerFactory) CouchDbCodeException(me.retrodaredevil.couchdbjava.exception.CouchDbCodeException) Random(java.util.Random) HelpRequestedException(com.lexicalscope.jewel.cli.HelpRequestedException) me.retrodaredevil.solarthing.config.options(me.retrodaredevil.solarthing.config.options) DatabaseSettings(me.retrodaredevil.solarthing.config.databases.DatabaseSettings) Objects.requireNonNull(java.util.Objects.requireNonNull) CouchDbException(me.retrodaredevil.couchdbjava.exception.CouchDbException) JsonParseException(com.fasterxml.jackson.core.JsonParseException) ArgumentValidationException(com.lexicalscope.jewel.cli.ArgumentValidationException) Logger(org.slf4j.Logger) ErrorResponse(me.retrodaredevil.couchdbjava.response.ErrorResponse) CouchDbDatabaseSettings(me.retrodaredevil.solarthing.config.databases.implementations.CouchDbDatabaseSettings) HourIntervalPacketCollectionIdGenerator(me.retrodaredevil.solarthing.packets.collection.HourIntervalPacketCollectionIdGenerator) Cli(com.lexicalscope.jewel.cli.Cli) Instant(java.time.Instant) PacketCollectionIdGenerator(me.retrodaredevil.solarthing.packets.collection.PacketCollectionIdGenerator) InstanceFragmentIndicatorPackets(me.retrodaredevil.solarthing.packets.instance.InstanceFragmentIndicatorPackets) InstanceSourcePackets(me.retrodaredevil.solarthing.packets.instance.InstanceSourcePackets) TextPacketCreator(me.retrodaredevil.solarthing.packets.creation.TextPacketCreator) List(java.util.List) SolarThingConstants(me.retrodaredevil.solarthing.SolarThingConstants) RawPacketReceiver(me.retrodaredevil.solarthing.packets.handling.RawPacketReceiver) java.io(java.io) CliFactory(com.lexicalscope.jewel.cli.CliFactory) CheckMain(me.retrodaredevil.solarthing.program.check.CheckMain) UtilityClass(me.retrodaredevil.solarthing.annotations.UtilityClass) PacketListReceiver(me.retrodaredevil.solarthing.packets.handling.PacketListReceiver) PVOutputUploadMain(me.retrodaredevil.solarthing.program.pvoutput.PVOutputUploadMain) LogManager(org.apache.logging.log4j.LogManager) Packet(me.retrodaredevil.solarthing.packets.Packet)

Example 4 with PacketListReceiver

use of me.retrodaredevil.solarthing.packets.handling.PacketListReceiver in project solarthing by wildmountainfarms.

the class RequestMain method startRequestProgram.

public static <T extends PacketHandlingOption & CommandOption> int startRequestProgram(T options, AnalyticsManager analyticsManager, List<DataRequester> dataRequesterList, long period, long minimumWait) throws Exception {
    EnvironmentUpdater[] environmentUpdaterReference = new EnvironmentUpdater[1];
    PacketHandlerInit.Result handlersResult = PacketHandlerInit.initHandlers(options, () -> environmentUpdaterReference[0], Collections.singleton(new RoverAnalyticsHandler(analyticsManager)));
    PacketListReceiverHandlerBundle bundle = handlersResult.getBundle();
    List<PacketListReceiver> packetListReceiverList = new ArrayList<>();
    List<EnvironmentUpdater> environmentUpdaters = new ArrayList<>();
    for (DataRequester dataRequester : dataRequesterList) {
        DataRequesterResult result = dataRequester.create(new RequestObject(bundle.getEventHandler().getPacketListReceiverAccepter()));
        packetListReceiverList.add(result.getStatusPacketListReceiver());
        environmentUpdaters.add(result.getEnvironmentUpdater());
    }
    // will add events for each rover packet if there are any to add
    packetListReceiverList.add(new RoverEventUpdaterListReceiver(bundle.getEventHandler().getPacketListReceiverAccepter()));
    // will add events for each tracer packet if there are any to add
    packetListReceiverList.add(new TracerEventUpdaterListReceiver(bundle.getEventHandler().getPacketListReceiverAccepter()));
    if (options.hasCommands()) {
        packetListReceiverList.add(new AvailableCommandsListUpdater(options.getCommandInfoList(), false));
    }
    environmentUpdaterReference[0] = new EnvironmentUpdaterMultiplexer(environmentUpdaters);
    packetListReceiverList.add(new DataIdentifiablePacketListChecker());
    packetListReceiverList.add(new DaySummaryLogListReceiver());
    packetListReceiverList.addAll(bundle.createDefaultPacketListReceivers());
    return doRequest(new PacketListReceiverMultiplexer(packetListReceiverList), Duration.ofMillis(period), Duration.ofMillis(minimumWait));
}
Also used : EnvironmentUpdaterMultiplexer(me.retrodaredevil.solarthing.actions.command.EnvironmentUpdaterMultiplexer) AvailableCommandsListUpdater(me.retrodaredevil.solarthing.commands.packets.status.AvailableCommandsListUpdater) ArrayList(java.util.ArrayList) EnvironmentUpdater(me.retrodaredevil.solarthing.actions.command.EnvironmentUpdater) RoverAnalyticsHandler(me.retrodaredevil.solarthing.analytics.RoverAnalyticsHandler) RoverEventUpdaterListReceiver(me.retrodaredevil.solarthing.program.receiver.RoverEventUpdaterListReceiver) DataIdentifiablePacketListChecker(me.retrodaredevil.solarthing.misc.common.DataIdentifiablePacketListChecker) DaySummaryLogListReceiver(me.retrodaredevil.solarthing.solar.DaySummaryLogListReceiver) DataRequesterResult(me.retrodaredevil.solarthing.config.request.DataRequesterResult) PacketListReceiverMultiplexer(me.retrodaredevil.solarthing.packets.handling.PacketListReceiverMultiplexer) DataRequester(me.retrodaredevil.solarthing.config.request.DataRequester) PacketListReceiver(me.retrodaredevil.solarthing.packets.handling.PacketListReceiver) TracerEventUpdaterListReceiver(me.retrodaredevil.solarthing.program.receiver.TracerEventUpdaterListReceiver) RequestObject(me.retrodaredevil.solarthing.config.request.RequestObject)

Example 5 with PacketListReceiver

use of me.retrodaredevil.solarthing.packets.handling.PacketListReceiver in project solarthing by wildmountainfarms.

the class OutbackMateMain method connectMate.

@SuppressWarnings("SameReturnValue")
public static int connectMate(MateProgramOptions options, File dataDirectory) throws Exception {
    LOGGER.info(SolarThingConstants.SUMMARY_MARKER, "Beginning mate program");
    AnalyticsManager analyticsManager = new AnalyticsManager(options.isAnalyticsEnabled(), dataDirectory);
    analyticsManager.sendStartUp(ProgramType.MATE);
    LOGGER.debug("IO Bundle File: " + options.getIOBundleFile());
    IOConfig ioConfig = ConfigUtil.parseIOConfig(options.getIOBundleFile(), OutbackConstants.MATE_CONFIG);
    try (ReloadableIOBundle ioBundle = new ReloadableIOBundle(ioConfig::createIOBundle)) {
        EnvironmentUpdater[] environmentUpdaterReference = new EnvironmentUpdater[1];
        PacketHandlerInit.Result handlersResult = PacketHandlerInit.initHandlers(options, () -> environmentUpdaterReference[0], Collections.singleton(new MateAnalyticsHandler(analyticsManager)));
        PacketListReceiverHandlerBundle bundle = handlersResult.getBundle();
        List<PacketListReceiver> packetListReceiverList = new ArrayList<>(Arrays.asList(OutbackDuplicatePacketRemover.INSTANCE, new FXEventUpdaterListReceiver(bundle.getEventHandler().getPacketListReceiverAccepter(), options.getFXWarningIgnoreMap()), new MXEventUpdaterListReceiver(bundle.getEventHandler().getPacketListReceiverAccepter()), new FXStatusListUpdater(new DailyIdentifier(options.getZoneId()))));
        List<EnvironmentUpdater> environmentUpdaters = new ArrayList<>();
        for (DataRequester dataRequester : options.getDataRequesterList()) {
            DataRequesterResult result = dataRequester.create(new RequestObject(bundle.getEventHandler().getPacketListReceiverAccepter()));
            packetListReceiverList.add(result.getStatusPacketListReceiver());
            environmentUpdaters.add(result.getEnvironmentUpdater());
        }
        final List<CommandProvider<MateCommand>> commandProviders;
        if (options.hasCommands()) {
            packetListReceiverList.add(new AvailableCommandsListUpdater(options.getCommandInfoList(), false));
            Queue<SourcedCommand<MateCommand>> queue = new LinkedList<>();
            // if there are no commands, this should remain empty
            commandProviders = new ArrayList<>();
            final CommandProvider<MateCommand> commandProvider = () -> {
                handlersResult.getUpdateCommandActions().run();
                return queue.poll();
            };
            commandProviders.add(commandProvider);
            environmentUpdaters.add((source, injectEnvironmentBuilder) -> {
                injectEnvironmentBuilder.add(new MateCommandEnvironment(queue));
            });
        } else {
            commandProviders = Collections.emptyList();
        }
        environmentUpdaterReference[0] = new EnvironmentUpdaterMultiplexer(environmentUpdaters);
        packetListReceiverList.add(new DataIdentifiablePacketListChecker());
        packetListReceiverList.add(new DaySummaryLogListReceiver());
        packetListReceiverList.addAll(bundle.createDefaultPacketListReceivers());
        return SolarMain.initReader(requireNonNull(ioBundle.getInputStream()), ioBundle::reload, new MatePacketCreator49(MateProgramOptions.getIgnoreCheckSum(options)), new TimedPacketReceiver(Duration.ofMillis(250), new PacketListReceiverMultiplexer(packetListReceiverList), new MateCommandSender(// if commands aren't allowed, commandProviders will be empty, so this will do nothing
        new CommandProviderMultiplexer<>(commandProviders), ioBundle.getOutputStream(), ALLOWED_COMMANDS, new OnMateCommandSent(new PacketListReceiverMultiplexer(bundle.getEventHandler().getPacketListReceiverAccepter(), bundle.getEventHandler().getPacketListReceiverPacker(), bundle.getEventHandler().getPacketListReceiverHandler())))));
    }
}
Also used : FXStatusListUpdater(me.retrodaredevil.solarthing.solar.outback.FXStatusListUpdater) CommandProvider(me.retrodaredevil.solarthing.commands.command.CommandProvider) DataIdentifiablePacketListChecker(me.retrodaredevil.solarthing.misc.common.DataIdentifiablePacketListChecker) DaySummaryLogListReceiver(me.retrodaredevil.solarthing.solar.DaySummaryLogListReceiver) DataRequesterResult(me.retrodaredevil.solarthing.config.request.DataRequesterResult) MatePacketCreator49(me.retrodaredevil.solarthing.solar.outback.MatePacketCreator49) FXEventUpdaterListReceiver(me.retrodaredevil.solarthing.solar.outback.fx.FXEventUpdaterListReceiver) MateCommandEnvironment(me.retrodaredevil.solarthing.actions.environment.MateCommandEnvironment) PacketListReceiver(me.retrodaredevil.solarthing.packets.handling.PacketListReceiver) ReloadableIOBundle(me.retrodaredevil.solarthing.io.ReloadableIOBundle) AnalyticsManager(me.retrodaredevil.solarthing.analytics.AnalyticsManager) EnvironmentUpdaterMultiplexer(me.retrodaredevil.solarthing.actions.command.EnvironmentUpdaterMultiplexer) AvailableCommandsListUpdater(me.retrodaredevil.solarthing.commands.packets.status.AvailableCommandsListUpdater) EnvironmentUpdater(me.retrodaredevil.solarthing.actions.command.EnvironmentUpdater) MXEventUpdaterListReceiver(me.retrodaredevil.solarthing.solar.outback.mx.MXEventUpdaterListReceiver) IOConfig(me.retrodaredevil.solarthing.config.io.IOConfig) PacketListReceiverMultiplexer(me.retrodaredevil.solarthing.packets.handling.PacketListReceiverMultiplexer) DataRequester(me.retrodaredevil.solarthing.config.request.DataRequester) MateCommand(me.retrodaredevil.solarthing.solar.outback.command.MateCommand) DailyIdentifier(me.retrodaredevil.solarthing.util.time.DailyIdentifier) SourcedCommand(me.retrodaredevil.solarthing.commands.command.SourcedCommand) TimedPacketReceiver(me.retrodaredevil.solarthing.packets.handling.implementations.TimedPacketReceiver) MateAnalyticsHandler(me.retrodaredevil.solarthing.analytics.MateAnalyticsHandler) RequestObject(me.retrodaredevil.solarthing.config.request.RequestObject)

Aggregations

PacketListReceiver (me.retrodaredevil.solarthing.packets.handling.PacketListReceiver)6 SolarThingConstants (me.retrodaredevil.solarthing.SolarThingConstants)3 EnvironmentUpdater (me.retrodaredevil.solarthing.actions.command.EnvironmentUpdater)3 EnvironmentUpdaterMultiplexer (me.retrodaredevil.solarthing.actions.command.EnvironmentUpdaterMultiplexer)3 DataRequesterResult (me.retrodaredevil.solarthing.config.request.DataRequesterResult)3 PacketListReceiverMultiplexer (me.retrodaredevil.solarthing.packets.handling.PacketListReceiverMultiplexer)3 ArgumentValidationException (com.lexicalscope.jewel.cli.ArgumentValidationException)2 Cli (com.lexicalscope.jewel.cli.Cli)2 CliFactory (com.lexicalscope.jewel.cli.CliFactory)2 HelpRequestedException (com.lexicalscope.jewel.cli.HelpRequestedException)2 ArrayList (java.util.ArrayList)2 List (java.util.List)2 UtilityClass (me.retrodaredevil.solarthing.annotations.UtilityClass)2 AvailableCommandsListUpdater (me.retrodaredevil.solarthing.commands.packets.status.AvailableCommandsListUpdater)2 IOConfig (me.retrodaredevil.solarthing.config.io.IOConfig)2 DataRequester (me.retrodaredevil.solarthing.config.request.DataRequester)2 RequestObject (me.retrodaredevil.solarthing.config.request.RequestObject)2 ReloadableIOBundle (me.retrodaredevil.solarthing.io.ReloadableIOBundle)2 DataIdentifiablePacketListChecker (me.retrodaredevil.solarthing.misc.common.DataIdentifiablePacketListChecker)2 PacketCollectionIdGenerator (me.retrodaredevil.solarthing.packets.collection.PacketCollectionIdGenerator)2