Search in sources :

Example 1 with PacketCollection

use of me.retrodaredevil.solarthing.packets.collection.PacketCollection in project solarthing by wildmountainfarms.

the class FlagCommandChatBotHandler method setFlag.

private void setFlag(MessageSender messageSender, String flagName) {
    TimeRange timeRange = TimeRange.createAfter(Instant.now());
    FlagData data = new FlagData(flagName, new TimeRangeActivePeriod(timeRange));
    RequestFlagPacket requestFlagPacket = new ImmutableRequestFlagPacket(data);
    PacketCollectionCreator creator = commandHelper.getCommandManager().makeCreator(sourceId, zoneId, null, requestFlagPacket, PacketCollectionIdGenerator.Defaults.UNIQUE_GENERATOR);
    // TODO We should check if the flag being requested is already active.
    executorService.execute(() -> {
        PacketCollection packetCollection = creator.create(Instant.now());
        boolean success = false;
        try {
            database.getOpenDatabase().uploadPacketCollection(packetCollection, null);
            success = true;
        } catch (SolarThingDatabaseException e) {
            LOGGER.error("Could not upload request flag packet", e);
        }
        if (success) {
            messageSender.sendMessage("Successfully requested flag: '" + flagName + "' to be set.");
        } else {
            messageSender.sendMessage("Was unable to request flag set. See logs for details or try again.");
        }
    });
}
Also used : TimeRange(me.retrodaredevil.solarthing.util.TimeRange) FlagData(me.retrodaredevil.solarthing.type.alter.flag.FlagData) PacketCollection(me.retrodaredevil.solarthing.packets.collection.PacketCollection) TimeRangeActivePeriod(me.retrodaredevil.solarthing.type.alter.flag.TimeRangeActivePeriod) ImmutableRequestFlagPacket(me.retrodaredevil.solarthing.commands.packets.open.ImmutableRequestFlagPacket) RequestFlagPacket(me.retrodaredevil.solarthing.commands.packets.open.RequestFlagPacket) ImmutableRequestFlagPacket(me.retrodaredevil.solarthing.commands.packets.open.ImmutableRequestFlagPacket) PacketCollectionCreator(me.retrodaredevil.solarthing.packets.collection.PacketCollectionCreator) SolarThingDatabaseException(me.retrodaredevil.solarthing.database.exception.SolarThingDatabaseException)

Example 2 with PacketCollection

use of me.retrodaredevil.solarthing.packets.collection.PacketCollection in project solarthing by wildmountainfarms.

the class ScheduleCommandChatBotHandler method schedule.

private void schedule(MessageSender messageSender, Instant now, Instant targetTime, AvailableCommand availableCommand) {
    if (now.plus(Duration.ofMinutes(1)).isAfter(targetTime)) {
        messageSender.sendMessage("Cannot schedule a command less than one minute from now.");
        return;
    }
    if (now.plus(Duration.ofHours(72)).isBefore(targetTime)) {
        messageSender.sendMessage("Cannot schedule a command more than 72 hours from now.");
        return;
    }
    UUID uniqueId = UUID.randomUUID();
    PacketCollectionCreator creator = commandHelper.getCommandManager().makeCreator(sourceId, zoneId, // We don't have an InstanceTargetPacket because scheduling commands is not handled by a program with a fragment ID // also look at PacketGroups.parseToTargetPacketGroup() for interpretation without a TargetInstancePacket
    null, new ImmutableScheduleCommandPacket(new ScheduledCommandData(targetTime.toEpochMilli(), availableCommand.getCommandInfo().getName(), Collections.singleton(availableCommand.getFragmentId())), uniqueId), PacketCollectionIdGenerator.Defaults.UNIQUE_GENERATOR);
    PacketCollection packetCollection = creator.create(now);
    messageSender.sendMessage("Scheduling " + availableCommand.getCommandInfo().getDisplayName() + " at " + TimeUtil.instantToSlackDateSeconds(targetTime));
    executorService.execute(() -> {
        boolean success = false;
        try {
            database.getOpenDatabase().uploadPacketCollection(packetCollection, null);
            success = true;
        } catch (SolarThingDatabaseException e) {
            LOGGER.error("Could not upload schedule command packet collection", e);
        }
        if (success) {
            messageSender.sendMessage("Successfully requested schedule. ID: " + uniqueId);
        } else {
            messageSender.sendMessage("Could not upload schedule command request.");
        }
    });
}
Also used : PacketCollection(me.retrodaredevil.solarthing.packets.collection.PacketCollection) UUID(java.util.UUID) PacketCollectionCreator(me.retrodaredevil.solarthing.packets.collection.PacketCollectionCreator) ImmutableScheduleCommandPacket(me.retrodaredevil.solarthing.commands.packets.open.ImmutableScheduleCommandPacket) ScheduledCommandData(me.retrodaredevil.solarthing.type.alter.packets.ScheduledCommandData) SolarThingDatabaseException(me.retrodaredevil.solarthing.database.exception.SolarThingDatabaseException)

Example 3 with PacketCollection

use of me.retrodaredevil.solarthing.packets.collection.PacketCollection in project solarthing by wildmountainfarms.

the class SendPacketAction method onStart.

@Override
protected void onStart() {
    super.onStart();
    Instant now = Instant.now();
    MillisDatabase millisDatabase = millisDatabaseSupplier.get();
    PacketCollection packetCollection = packetCollectionCreator.create(now);
    executorService.execute(() -> {
        int retryCounter = 0;
        while (true) {
            boolean success = upload(millisDatabase, packetCollection);
            if (success) {
                nextAction = onSuccessAction;
                break;
            }
            if (retryCounter == maxRetries) {
                nextAction = onMaxRetriesAction;
                LOGGER.info("Reached max retries for packet id: " + packetCollection.getDbId() + " will not try again.");
                break;
            }
            retryCounter++;
            if (retryWaitMillis > 0) {
                try {
                    Thread.sleep(retryWaitMillis);
                } catch (InterruptedException e) {
                    Thread.currentThread().interrupt();
                    LOGGER.info("A SendPacketAction's sleep was interrupted.");
                    // We don't set nextAction to something because we assume someone just called end() on us and won't be using our next action
                    break;
                }
            }
        }
        setDone(true);
    });
}
Also used : MillisDatabase(me.retrodaredevil.solarthing.database.MillisDatabase) PacketCollection(me.retrodaredevil.solarthing.packets.collection.PacketCollection) Instant(java.time.Instant)

Example 4 with PacketCollection

use of me.retrodaredevil.solarthing.packets.collection.PacketCollection in project solarthing by wildmountainfarms.

the class AlterManagerAction method doSendCommand.

private void doSendCommand(VersionedPacket<StoredAlterPacket> versionedPacket, ScheduledCommandPacket scheduledCommandPacket) {
    LOGGER.info(SolarThingConstants.SUMMARY_MARKER, "Sending command from data: " + scheduledCommandPacket.getData());
    ScheduledCommandData data = scheduledCommandPacket.getData();
    RequestCommandPacket requestCommandPacket = new ImmutableRequestCommandPacket(data.getCommandName());
    // Having a document ID based off of the StoredAlterPacket's _id helps make sure we don't process it twice in case we are unable to delete it.
    // -- if there's an update conflict while uploading, we know we already processed it
    String documentId = "scheduled-request-" + versionedPacket.getPacket().getDbId();
    PacketCollectionCreator creator = commandManager.makeCreator(sourceId, zoneId, InstanceTargetPackets.create(data.getTargetFragmentIds()), requestCommandPacket, zonedDateTime -> documentId);
    executorService.execute(() -> {
        Instant uploadingNow = Instant.now();
        PacketCollection packetCollection = creator.create(uploadingNow);
        boolean shouldDeleteAlter = false;
        try {
            database.getOpenDatabase().uploadPacketCollection(packetCollection, null);
            LOGGER.info(SolarThingConstants.SUMMARY_MARKER, "Successfully uploaded packet collection that schedules command from data: " + scheduledCommandPacket.getData() + " document ID: " + documentId);
            shouldDeleteAlter = true;
        } catch (UpdateConflictSolarThingDatabaseException e) {
            LOGGER.error("Got update conflict exception while uploading document ID: " + documentId + ". Will inspect existing document and overwrite if it's a malicious actor...", e);
            VersionedPacket<StoredPacketGroup> existingDocument = null;
            try {
                existingDocument = database.getOpenDatabase().getPacketCollection(documentId);
            } catch (SolarThingDatabaseException ex) {
                LOGGER.error("Could not retrieve document with document ID: " + documentId, ex);
            }
            if (existingDocument != null) {
                if (isDocumentMadeByUs(uploadingNow, data, existingDocument.getPacket())) {
                    LOGGER.info(SolarThingConstants.SUMMARY_MARKER, "False alarm everyone. The packet in the database was made by us and its timestamp is reasonable. document ID: " + documentId);
                    shouldDeleteAlter = true;
                } else {
                    LOGGER.warn(SolarThingConstants.SUMMARY_MARKER, "The packet in the database with document ID: " + documentId + " was not made by us. Could be a malicious actor. We will overwrite that packet.");
                    try {
                        database.getOpenDatabase().uploadPacketCollection(packetCollection, existingDocument.getUpdateToken());
                        shouldDeleteAlter = true;
                    } catch (SolarThingDatabaseException ex) {
                        LOGGER.error("Could not overwrite malicious packet. Will likely try again. document ID: " + documentId, ex);
                    }
                }
            }
        } catch (SolarThingDatabaseException e) {
            LOGGER.error("Failed to upload our request command packet. documentId: " + documentId, e);
        }
        if (shouldDeleteAlter) {
            try {
                database.getAlterDatabase().delete(versionedPacket);
            } catch (SolarThingDatabaseException e) {
                LOGGER.error("Error while deleting an alter document. document ID: " + versionedPacket.getPacket().getDbId() + " update token: " + versionedPacket.getUpdateToken(), e);
            }
        }
    });
}
Also used : RequestCommandPacket(me.retrodaredevil.solarthing.commands.packets.open.RequestCommandPacket) ImmutableRequestCommandPacket(me.retrodaredevil.solarthing.commands.packets.open.ImmutableRequestCommandPacket) PacketCollection(me.retrodaredevil.solarthing.packets.collection.PacketCollection) Instant(java.time.Instant) UpdateConflictSolarThingDatabaseException(me.retrodaredevil.solarthing.database.exception.UpdateConflictSolarThingDatabaseException) VersionedPacket(me.retrodaredevil.solarthing.database.VersionedPacket) ImmutableRequestCommandPacket(me.retrodaredevil.solarthing.commands.packets.open.ImmutableRequestCommandPacket) ScheduledCommandData(me.retrodaredevil.solarthing.type.alter.packets.ScheduledCommandData) PacketCollectionCreator(me.retrodaredevil.solarthing.packets.collection.PacketCollectionCreator) UpdateConflictSolarThingDatabaseException(me.retrodaredevil.solarthing.database.exception.UpdateConflictSolarThingDatabaseException) SolarThingDatabaseException(me.retrodaredevil.solarthing.database.exception.SolarThingDatabaseException)

Example 5 with PacketCollection

use of me.retrodaredevil.solarthing.packets.collection.PacketCollection in project solarthing by wildmountainfarms.

the class CommandChatBotHandler method handleMessage.

@Override
public boolean handleMessage(Message message, MessageSender messageSender) {
    AvailableCommand best = commandHelper.getBestCommand(message, message.getText());
    if (best == null) {
        return false;
    }
    CommandInfo info = best.getCommandInfo();
    messageSender.sendMessage("Sending command: " + info.getDisplayName());
    PacketCollectionCreator creator = commandHelper.getCommandManager().makeCreator(sourceId, zoneId, InstanceTargetPackets.create(Collections.singleton(best.getFragmentId())), new ImmutableRequestCommandPacket(info.getName()), PacketCollectionIdGenerator.Defaults.UNIQUE_GENERATOR);
    Instant now = Instant.now();
    PacketCollection packetCollection = creator.create(now);
    executorService.execute(() -> {
        try {
            database.getOpenDatabase().uploadPacketCollection(packetCollection, null);
            LOGGER.info("Uploaded command request document");
        } catch (SolarThingDatabaseException e) {
            LOGGER.error("Error while uploading document.", e);
            messageSender.sendMessage("Failed to upload command: " + info.getDisplayName());
        }
    });
    return true;
}
Also used : CommandInfo(me.retrodaredevil.solarthing.commands.CommandInfo) PacketCollection(me.retrodaredevil.solarthing.packets.collection.PacketCollection) Instant(java.time.Instant) ImmutableRequestCommandPacket(me.retrodaredevil.solarthing.commands.packets.open.ImmutableRequestCommandPacket) PacketCollectionCreator(me.retrodaredevil.solarthing.packets.collection.PacketCollectionCreator) SolarThingDatabaseException(me.retrodaredevil.solarthing.database.exception.SolarThingDatabaseException)

Aggregations

PacketCollection (me.retrodaredevil.solarthing.packets.collection.PacketCollection)11 Instant (java.time.Instant)7 SolarThingDatabaseException (me.retrodaredevil.solarthing.database.exception.SolarThingDatabaseException)7 PacketCollectionCreator (me.retrodaredevil.solarthing.packets.collection.PacketCollectionCreator)7 ArrayList (java.util.ArrayList)3 VersionedPacket (me.retrodaredevil.solarthing.database.VersionedPacket)3 ZoneId (java.time.ZoneId)2 Arrays (java.util.Arrays)2 List (java.util.List)2 Nullable (me.retrodaredevil.solarthing.annotations.Nullable)2 CommandOpenPacket (me.retrodaredevil.solarthing.commands.packets.open.CommandOpenPacket)2 ImmutableDeleteAlterPacket (me.retrodaredevil.solarthing.commands.packets.open.ImmutableDeleteAlterPacket)2 ImmutableRequestCommandPacket (me.retrodaredevil.solarthing.commands.packets.open.ImmutableRequestCommandPacket)2 SolarThingDatabase (me.retrodaredevil.solarthing.database.SolarThingDatabase)2 Packet (me.retrodaredevil.solarthing.packets.Packet)2 PacketCollectionIdGenerator (me.retrodaredevil.solarthing.packets.collection.PacketCollectionIdGenerator)2 Logger (org.slf4j.Logger)2 LoggerFactory (org.slf4j.LoggerFactory)2 JsonProcessingException (com.fasterxml.jackson.core.JsonProcessingException)1 ObjectMapper (com.fasterxml.jackson.databind.ObjectMapper)1