Search in sources :

Example 11 with Packet

use of me.retrodaredevil.solarthing.packets.Packet in project solarthing by wildmountainfarms.

the class TracerEventUpdaterListReceiver method useData.

private void useData(@NotNull TracerStatusPacket tracer, @Nullable TracerStatusPacket previous) {
    final Integer lastChargingEquipmentStatusValue;
    if (previous == null) {
        lastChargingEquipmentStatusValue = null;
    } else {
        lastChargingEquipmentStatusValue = previous.getChargingEquipmentStatus();
    }
    int currentChargingEquipmentStatusValue = tracer.getChargingEquipmentStatus();
    List<Packet> packets = new ArrayList<>();
    if (lastChargingEquipmentStatusValue == null || lastChargingEquipmentStatusValue != currentChargingEquipmentStatusValue) {
        packets.add(new ImmutableTracerChargingEquipmentStatusChangePacket(tracer.getIdentifier(), currentChargingEquipmentStatusValue, lastChargingEquipmentStatusValue));
    }
    if (!packets.isEmpty()) {
        eventReceiver.receive(packets);
    }
}
Also used : Packet(me.retrodaredevil.solarthing.packets.Packet) TracerStatusPacket(me.retrodaredevil.solarthing.solar.tracer.TracerStatusPacket) ImmutableTracerChargingEquipmentStatusChangePacket(me.retrodaredevil.solarthing.solar.tracer.event.ImmutableTracerChargingEquipmentStatusChangePacket) ImmutableTracerChargingEquipmentStatusChangePacket(me.retrodaredevil.solarthing.solar.tracer.event.ImmutableTracerChargingEquipmentStatusChangePacket) ArrayList(java.util.ArrayList)

Example 12 with Packet

use of me.retrodaredevil.solarthing.packets.Packet in project solarthing by wildmountainfarms.

the class TracerEventUpdaterListReceiver method receive.

@Override
public void receive(List<Packet> packets) {
    for (Packet packet : packets) {
        if (packet instanceof TracerStatusPacket) {
            TracerStatusPacket tracer = (TracerStatusPacket) packet;
            TracerStatusPacket previous = previousPacketMap.get(tracer.getIdentifier());
            previousPacketMap.put(tracer.getIdentifier(), tracer);
            useData(tracer, previous);
        }
    }
}
Also used : Packet(me.retrodaredevil.solarthing.packets.Packet) TracerStatusPacket(me.retrodaredevil.solarthing.solar.tracer.TracerStatusPacket) ImmutableTracerChargingEquipmentStatusChangePacket(me.retrodaredevil.solarthing.solar.tracer.event.ImmutableTracerChargingEquipmentStatusChangePacket) TracerStatusPacket(me.retrodaredevil.solarthing.solar.tracer.TracerStatusPacket)

Example 13 with Packet

use of me.retrodaredevil.solarthing.packets.Packet in project solarthing by wildmountainfarms.

the class SecurityPacketReceiver method receivePacketGroup.

private void receivePacketGroup(StoredPacketGroup storedPacketGroup, TargetPacketGroup packetGroup) {
    LOGGER.debug("Receiving packet group: " + storedPacketGroup.getStoredIdentifier());
    long packetGroupDateMillis = packetGroup.getDateMillis();
    List<? extends Packet> packetGroupPackets = packetGroup.getPackets();
    if (packetGroupPackets.stream().noneMatch(packet -> packet instanceof SecurityPacket && !(packet instanceof AuthNewSenderPacket))) {
        LOGGER.debug("This packet group has no useful SecurityPackets. Ignoring. identifier: " + storedPacketGroup.getStoredIdentifier());
        return;
    }
    if (packetGroupPackets.size() != 1) {
        /*
			In any "millis database" we have the documents inside follow the packet collection format.
			Packet collections can have many packets inside them. When we are dealing with security packets,
			we want to be able to easily refer to a single security packet. Because no one should ever need
			to contain multiple security packets in a given packet collection, we will only process
			packet collections with a single security packet. This allows things like SecurityEventPackets to work nicely,
			and doesn't have any real drawbacks except for some (possible) future use case that we don't know of.
			 */
        LOGGER.warn("This packetGroup targeting us had a packetGroup.size != 1! stored identifier: " + storedPacketGroup.getStoredIdentifier());
        reject(storedPacketGroup, SecurityRejectPacket.Reason.INVALID_DATA, "You cannot have more than one packet (besides source and target)");
        return;
    }
    Packet packet = packetGroupPackets.stream().findFirst().orElseThrow(() -> new AssertionError("size should be 1! This should not fail"));
    if (!(packet instanceof LargeIntegrityPacket)) {
        if (packet instanceof IntegrityPacket) {
            LOGGER.warn(SolarThingConstants.SUMMARY_MARKER, "Got an IntegrityPacket! This is no longer supported!");
            reject(storedPacketGroup, SecurityRejectPacket.Reason.LEGACY_REQUEST, "IntegrityPacket is no longer supported");
        } else if (packet instanceof AuthNewSenderPacket) {
            LOGGER.warn("Got an AuthNewSenderPacket. Ignoring.");
            reject(storedPacketGroup, SecurityRejectPacket.Reason.UNKNOWN_ERROR, "Got auth new sender packet");
        } else {
            LOGGER.warn("Unknown packet: " + packet);
            reject(storedPacketGroup, SecurityRejectPacket.Reason.UNKNOWN_ERROR, "Got unknown packet");
        }
        return;
    }
    LargeIntegrityPacket largeIntegrityPacket = (LargeIntegrityPacket) packet;
    String sender = largeIntegrityPacket.getSender();
    final String invalidSenderReason = sender == null ? "sender is null!" : SenderUtil.getInvalidSenderNameReason(sender);
    if (invalidSenderReason != null) {
        LOGGER.warn(SolarThingConstants.SUMMARY_MARKER, invalidSenderReason);
        reject(storedPacketGroup, SecurityRejectPacket.Reason.INVALID_DATA, invalidSenderReason);
        return;
    }
    String encodedHash = decryptData(storedPacketGroup, sender, largeIntegrityPacket.getEncryptedHash(), packetGroupDateMillis);
    if (encodedHash == null) {
        // If encodedHash is null, then decryptData should have already called reject()
        return;
    }
    byte[] decodedHash;
    try {
        decodedHash = Base64Variants.getDefaultVariant().decode(encodedHash);
    } catch (IllegalArgumentException e) {
        LOGGER.error("Not base64 data!", e);
        reject(storedPacketGroup, SecurityRejectPacket.Reason.INVALID_DATA, "Not base64 data!");
        return;
    }
    String payload = largeIntegrityPacket.getPayload();
    byte[] payloadHash = HashUtil.hash(payload);
    if (!Arrays.equals(decodedHash, payloadHash)) {
        LOGGER.warn("Unsuccessfully compared hashes! The data may have been tampered with!");
        reject(storedPacketGroup, SecurityRejectPacket.Reason.DIFFERENT_PAYLOAD, "Unsuccessfully compared hashes");
        return;
    }
    LOGGER.debug("Successfully compared hashes!");
    handleMessage(storedPacketGroup, payload, sender);
}
Also used : Packet(me.retrodaredevil.solarthing.packets.Packet) IntegrityPacket(me.retrodaredevil.solarthing.packets.security.IntegrityPacket) SecurityRejectPacket(me.retrodaredevil.solarthing.commands.event.SecurityRejectPacket) LargeIntegrityPacket(me.retrodaredevil.solarthing.packets.security.LargeIntegrityPacket) InstanceSourcePacket(me.retrodaredevil.solarthing.packets.instance.InstanceSourcePacket) DocumentedPacket(me.retrodaredevil.solarthing.packets.DocumentedPacket) SecurityPacket(me.retrodaredevil.solarthing.packets.security.SecurityPacket) ImmutableSecurityRejectPacket(me.retrodaredevil.solarthing.commands.event.ImmutableSecurityRejectPacket) ImmutableSecurityAcceptPacket(me.retrodaredevil.solarthing.commands.event.ImmutableSecurityAcceptPacket) SecurityAcceptPacket(me.retrodaredevil.solarthing.commands.event.SecurityAcceptPacket) InstancePacket(me.retrodaredevil.solarthing.packets.instance.InstancePacket) AuthNewSenderPacket(me.retrodaredevil.solarthing.packets.security.AuthNewSenderPacket) SecurityEventPacket(me.retrodaredevil.solarthing.commands.event.SecurityEventPacket) SecurityPacket(me.retrodaredevil.solarthing.packets.security.SecurityPacket) AuthNewSenderPacket(me.retrodaredevil.solarthing.packets.security.AuthNewSenderPacket) IntegrityPacket(me.retrodaredevil.solarthing.packets.security.IntegrityPacket) LargeIntegrityPacket(me.retrodaredevil.solarthing.packets.security.LargeIntegrityPacket) LargeIntegrityPacket(me.retrodaredevil.solarthing.packets.security.LargeIntegrityPacket)

Example 14 with Packet

use of me.retrodaredevil.solarthing.packets.Packet 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 15 with Packet

use of me.retrodaredevil.solarthing.packets.Packet in project solarthing by wildmountainfarms.

the class RequireFullOutputActionNode method isFullOutput.

private boolean isFullOutput(FragmentedPacketGroup latestPacketGroup) {
    for (Map.Entry<Integer, List<String>> entry : requiredIdentifierMap.entrySet()) {
        int desiredFragmentId = entry.getKey();
        if (!latestPacketGroup.hasFragmentId(desiredFragmentId)) {
            continue;
        }
        for (String desiredIdentifierRepresentation : entry.getValue()) {
            for (Packet packet : latestPacketGroup.getPackets()) {
                int fragmentId = latestPacketGroup.getFragmentId(packet);
                if (fragmentId != desiredFragmentId) {
                    continue;
                }
                if (packet instanceof Identifiable) {
                    Identifier identifier = ((Identifiable) packet).getIdentifier();
                    if (desiredIdentifierRepresentation.equals(identifier.getRepresentation())) {
                        if (packet instanceof MXStatusPacket) {
                            MXStatusPacket mx = (MXStatusPacket) packet;
                            ChargerMode mode = mx.getChargingMode();
                            // Some old MX firmwares consistently report being in float mode after a full absorb cycle even after the daily reset.
                            // This configuration option allows us to treat float as full output for a given MX
                            boolean canIgnoreFloatMode = ignoreReportedMXFloatMap.getOrDefault(fragmentId, Collections.emptyList()).contains(desiredIdentifierRepresentation);
                            if (mode != ChargerMode.SILENT && mode != ChargerMode.BULK && (!canIgnoreFloatMode || mode != ChargerMode.FLOAT)) {
                                if (log) {
                                    LOGGER.info(identifier.getRepresentation() + " on fragment " + fragmentId + " is in mode " + mode.getModeName());
                                }
                                return false;
                            }
                        } else if (packet instanceof RoverStatusPacket) {
                            RoverStatusPacket rover = (RoverStatusPacket) packet;
                            ChargingState state = rover.getChargingMode();
                            if (state != ChargingState.ACTIVATED && state != ChargingState.DEACTIVATED && state != ChargingState.MPPT) {
                                if (log) {
                                    LOGGER.info(identifier.getRepresentation() + " on fragment " + fragmentId + " is in mode " + state.getModeName());
                                }
                                return false;
                            }
                        } else if (packet instanceof TracerStatusPacket) {
                            TracerStatusPacket tracer = (TracerStatusPacket) packet;
                            ChargingStatus status = tracer.getChargingMode();
                            // we currently cannot tell if while in BOOST or EQUALIZE if the controller is actually in Bulk, so float is the only mode we know that isn't at full output
                            if (status == ChargingStatus.FLOAT) {
                                if (log) {
                                    LOGGER.info(identifier.getRepresentation() + " on fragment " + fragmentId + " is in mode " + status.getModeName());
                                }
                                return false;
                            }
                        }
                    }
                }
            }
        }
    }
    return true;
}
Also used : Packet(me.retrodaredevil.solarthing.packets.Packet) MXStatusPacket(me.retrodaredevil.solarthing.solar.outback.mx.MXStatusPacket) TracerStatusPacket(me.retrodaredevil.solarthing.solar.tracer.TracerStatusPacket) RoverStatusPacket(me.retrodaredevil.solarthing.solar.renogy.rover.RoverStatusPacket) ChargingStatus(me.retrodaredevil.solarthing.solar.tracer.mode.ChargingStatus) MXStatusPacket(me.retrodaredevil.solarthing.solar.outback.mx.MXStatusPacket) ChargerMode(me.retrodaredevil.solarthing.solar.outback.mx.ChargerMode) TracerStatusPacket(me.retrodaredevil.solarthing.solar.tracer.TracerStatusPacket) ChargingState(me.retrodaredevil.solarthing.solar.renogy.rover.ChargingState) Identifiable(me.retrodaredevil.solarthing.packets.identification.Identifiable) Identifier(me.retrodaredevil.solarthing.packets.identification.Identifier) RoverStatusPacket(me.retrodaredevil.solarthing.solar.renogy.rover.RoverStatusPacket) List(java.util.List) Map(java.util.Map)

Aggregations

Packet (me.retrodaredevil.solarthing.packets.Packet)45 ArrayList (java.util.ArrayList)17 Instant (java.time.Instant)7 List (java.util.List)7 FragmentedPacketGroup (me.retrodaredevil.solarthing.packets.collection.FragmentedPacketGroup)6 FXStatusPacket (me.retrodaredevil.solarthing.solar.outback.fx.FXStatusPacket)6 Identifiable (me.retrodaredevil.solarthing.packets.identification.Identifiable)5 IdentifierFragment (me.retrodaredevil.solarthing.packets.identification.IdentifierFragment)5 RoverStatusPacket (me.retrodaredevil.solarthing.solar.renogy.rover.RoverStatusPacket)5 OpenSource (me.retrodaredevil.solarthing.type.open.OpenSource)5 Map (java.util.Map)4 CommandOpenPacket (me.retrodaredevil.solarthing.commands.packets.open.CommandOpenPacket)4 InstancePacketGroup (me.retrodaredevil.solarthing.packets.collection.InstancePacketGroup)4 InstanceSourcePacket (me.retrodaredevil.solarthing.packets.instance.InstanceSourcePacket)4 ExecutionReason (me.retrodaredevil.solarthing.reason.ExecutionReason)4 OpenSourceExecutionReason (me.retrodaredevil.solarthing.reason.OpenSourceExecutionReason)4 ObjectNode (com.fasterxml.jackson.databind.node.ObjectNode)3 ValueNode (com.fasterxml.jackson.databind.node.ValueNode)3 RequestCommandPacket (me.retrodaredevil.solarthing.commands.packets.open.RequestCommandPacket)3 VersionedPacket (me.retrodaredevil.solarthing.database.VersionedPacket)3