Search in sources :

Example 6 with VersionedPacket

use of me.retrodaredevil.solarthing.database.VersionedPacket in project solarthing by wildmountainfarms.

the class CouchDbSolarThingDatabase method queryAuthorized.

@Override
@Nullable
public VersionedPacket<AuthorizationPacket> queryAuthorized(UpdateToken updateToken) throws SolarThingDatabaseException {
    DocumentData data = queryDocument(closedDatabase, AuthorizationPacket.DOCUMENT_ID, updateToken);
    if (data == null) {
        return null;
    }
    JsonData jsonData = data.getJsonData();
    try {
        AuthorizationPacket packet = CouchDbJacksonUtil.readValue(simpleObjectMapper, jsonData, AuthorizationPacket.class);
        return new VersionedPacket<>(packet, new RevisionUpdateToken(data.getRevision()));
    } catch (JsonProcessingException e) {
        throw new SolarThingDatabaseException("Invalid authorization packet! Failed to parse!", e);
    }
}
Also used : DocumentData(me.retrodaredevil.couchdbjava.response.DocumentData) AuthorizationPacket(me.retrodaredevil.solarthing.type.closed.authorization.AuthorizationPacket) VersionedPacket(me.retrodaredevil.solarthing.database.VersionedPacket) JsonProcessingException(com.fasterxml.jackson.core.JsonProcessingException) JsonData(me.retrodaredevil.couchdbjava.json.JsonData) SolarThingDatabaseException(me.retrodaredevil.solarthing.database.exception.SolarThingDatabaseException) Nullable(me.retrodaredevil.solarthing.annotations.Nullable)

Example 7 with VersionedPacket

use of me.retrodaredevil.solarthing.database.VersionedPacket in project solarthing by wildmountainfarms.

the class CouchDbAlterDatabase method queryAll.

@Override
@NotNull
public List<VersionedPacket<StoredAlterPacket>> queryAll(String sourceId) throws SolarThingDatabaseException {
    final ViewResponse allDocs;
    try {
        allDocs = database.allDocs(new ViewQueryParamsBuilder().includeDocs(true).build());
    } catch (CouchDbException e) {
        throw ExceptionUtil.createFromCouchDbException(e);
    }
    List<ViewResponse.DocumentEntry> rows = allDocs.getRows();
    List<VersionedPacket<StoredAlterPacket>> r = new ArrayList<>(rows.size());
    for (ViewResponse.DocumentEntry row : rows) {
        if (row.getId().startsWith("_")) {
            // ignore design documents
            continue;
        }
        // Since we're using _all_docs with include_docs=true, we have to use the doc, since the value is just the ID for _all_docs
        JsonData jsonData = row.getDoc();
        final JsonNode jsonNode;
        try {
            jsonNode = CouchDbJacksonUtil.getNodeFrom(jsonData);
        } catch (JsonProcessingException e) {
            throw new SolarThingDatabaseException("We couldn't parse some of the data into JSON. This should never happen", e);
        }
        if (!jsonNode.isObject()) {
            throw new SolarThingDatabaseException("Something must be wrong with _all_docs!");
        }
        ObjectNode objectNode = (ObjectNode) jsonNode;
        final StoredAlterPacket storedAlterPacket;
        try {
            storedAlterPacket = mapper.treeToValue(objectNode, StoredAlterPacket.class);
            ;
        } catch (JsonProcessingException e) {
            throw new SolarThingDatabaseException("Could not parse. JsonData: " + jsonData.getJson(), e);
        }
        // String documentId = objectNode.get("_id").asText();
        String documentRevision = objectNode.get("_rev").asText();
        VersionedPacket<StoredAlterPacket> versionedPacket = new VersionedPacket<>(storedAlterPacket, new RevisionUpdateToken(documentRevision));
        r.add(versionedPacket);
    }
    return r;
}
Also used : CouchDbException(me.retrodaredevil.couchdbjava.exception.CouchDbException) ObjectNode(com.fasterxml.jackson.databind.node.ObjectNode) StoredAlterPacket(me.retrodaredevil.solarthing.type.alter.StoredAlterPacket) VersionedPacket(me.retrodaredevil.solarthing.database.VersionedPacket) ArrayList(java.util.ArrayList) JsonNode(com.fasterxml.jackson.databind.JsonNode) JsonData(me.retrodaredevil.couchdbjava.json.JsonData) StringJsonData(me.retrodaredevil.couchdbjava.json.StringJsonData) NotFoundSolarThingDatabaseException(me.retrodaredevil.solarthing.database.exception.NotFoundSolarThingDatabaseException) UnauthorizedSolarThingDatabaseException(me.retrodaredevil.solarthing.database.exception.UnauthorizedSolarThingDatabaseException) UpdateConflictSolarThingDatabaseException(me.retrodaredevil.solarthing.database.exception.UpdateConflictSolarThingDatabaseException) SolarThingDatabaseException(me.retrodaredevil.solarthing.database.exception.SolarThingDatabaseException) ViewResponse(me.retrodaredevil.couchdbjava.response.ViewResponse) ViewQueryParamsBuilder(me.retrodaredevil.couchdbjava.request.ViewQueryParamsBuilder) JsonProcessingException(com.fasterxml.jackson.core.JsonProcessingException) NotNull(me.retrodaredevil.solarthing.annotations.NotNull)

Example 8 with VersionedPacket

use of me.retrodaredevil.solarthing.database.VersionedPacket in project solarthing by wildmountainfarms.

the class FlagCommandChatBotHandler method clearFlag.

private void clearFlag(MessageSender messageSender, String flagName) {
    List<VersionedPacket<StoredAlterPacket>> packets = getPacketsWithFlagName(flagName);
    if (packets == null) {
        messageSender.sendMessage("Could not get flags. Please try again.");
        return;
    }
    Instant now = Instant.now();
    if (packets.isEmpty()) {
        messageSender.sendMessage("Flag: '" + flagName + "' is not set!");
        return;
    }
    List<VersionedPacket<StoredAlterPacket>> activePackets = packets.stream().filter(versionedPacket -> {
        FlagPacket flagPacket = (FlagPacket) versionedPacket.getPacket().getPacket();
        return flagPacket.getFlagData().getActivePeriod().isActive(now);
    }).collect(Collectors.toList());
    if (activePackets.isEmpty()) {
        messageSender.sendMessage("Flag: '" + flagName + "' is not currently active. In a future update we may allow you to clear inactive flags.");
        return;
    }
    // We know that the user wants this flag cleared, so let's delete all the packets that are active.
    for (VersionedPacket<StoredAlterPacket> packetToRequestDeleteFor : activePackets) {
        DeleteAlterPacket deleteAlterPacket = new ImmutableDeleteAlterPacket(packetToRequestDeleteFor.getPacket().getDbId(), packetToRequestDeleteFor.getUpdateToken());
        PacketCollectionCreator creator = commandHelper.getCommandManager().makeCreator(sourceId, zoneId, null, deleteAlterPacket, PacketCollectionIdGenerator.Defaults.UNIQUE_GENERATOR);
        PacketCollection packetCollection = creator.create(now);
        boolean success = false;
        try {
            database.getOpenDatabase().uploadPacketCollection(packetCollection, null);
            success = true;
        } catch (SolarThingDatabaseException e) {
            LOGGER.error("Could not upload request to delete alter packet for ID: " + packetToRequestDeleteFor.getPacket().getDbId(), e);
        }
        if (success) {
            messageSender.sendMessage("Requested delete for flag: '" + flagName + "' under ID: " + packetToRequestDeleteFor.getPacket().getDbId());
        } else {
            messageSender.sendMessage("Could not request delete for flag: '" + flagName + "' under ID: " + packetToRequestDeleteFor.getPacket().getDbId() + ". See logs for details.");
        }
    }
}
Also used : Arrays(java.util.Arrays) AlterPacketsProvider(me.retrodaredevil.solarthing.AlterPacketsProvider) LoggerFactory(org.slf4j.LoggerFactory) NotNull(me.retrodaredevil.solarthing.annotations.NotNull) MessageSender(me.retrodaredevil.solarthing.message.MessageSender) VersionedPacket(me.retrodaredevil.solarthing.database.VersionedPacket) RequestFlagPacket(me.retrodaredevil.solarthing.commands.packets.open.RequestFlagPacket) FlagData(me.retrodaredevil.solarthing.type.alter.flag.FlagData) Nullable(me.retrodaredevil.solarthing.annotations.Nullable) DeleteAlterPacket(me.retrodaredevil.solarthing.commands.packets.open.DeleteAlterPacket) FlagPacket(me.retrodaredevil.solarthing.type.alter.packets.FlagPacket) ExecutorService(java.util.concurrent.ExecutorService) Logger(org.slf4j.Logger) PacketCollectionCreator(me.retrodaredevil.solarthing.packets.collection.PacketCollectionCreator) SolarThingDatabase(me.retrodaredevil.solarthing.database.SolarThingDatabase) Instant(java.time.Instant) StoredAlterPacket(me.retrodaredevil.solarthing.type.alter.StoredAlterPacket) Collectors(java.util.stream.Collectors) PacketCollectionIdGenerator(me.retrodaredevil.solarthing.packets.collection.PacketCollectionIdGenerator) ZoneId(java.time.ZoneId) Executors(java.util.concurrent.Executors) AlterPacket(me.retrodaredevil.solarthing.type.alter.AlterPacket) List(java.util.List) TimeRange(me.retrodaredevil.solarthing.util.TimeRange) TimeRangeActivePeriod(me.retrodaredevil.solarthing.type.alter.flag.TimeRangeActivePeriod) ImmutableRequestFlagPacket(me.retrodaredevil.solarthing.commands.packets.open.ImmutableRequestFlagPacket) Collections(java.util.Collections) ImmutableDeleteAlterPacket(me.retrodaredevil.solarthing.commands.packets.open.ImmutableDeleteAlterPacket) PacketCollection(me.retrodaredevil.solarthing.packets.collection.PacketCollection) SolarThingDatabaseException(me.retrodaredevil.solarthing.database.exception.SolarThingDatabaseException) RequestFlagPacket(me.retrodaredevil.solarthing.commands.packets.open.RequestFlagPacket) FlagPacket(me.retrodaredevil.solarthing.type.alter.packets.FlagPacket) ImmutableRequestFlagPacket(me.retrodaredevil.solarthing.commands.packets.open.ImmutableRequestFlagPacket) StoredAlterPacket(me.retrodaredevil.solarthing.type.alter.StoredAlterPacket) ImmutableDeleteAlterPacket(me.retrodaredevil.solarthing.commands.packets.open.ImmutableDeleteAlterPacket) PacketCollection(me.retrodaredevil.solarthing.packets.collection.PacketCollection) VersionedPacket(me.retrodaredevil.solarthing.database.VersionedPacket) Instant(java.time.Instant) SolarThingDatabaseException(me.retrodaredevil.solarthing.database.exception.SolarThingDatabaseException) DeleteAlterPacket(me.retrodaredevil.solarthing.commands.packets.open.DeleteAlterPacket) ImmutableDeleteAlterPacket(me.retrodaredevil.solarthing.commands.packets.open.ImmutableDeleteAlterPacket) PacketCollectionCreator(me.retrodaredevil.solarthing.packets.collection.PacketCollectionCreator)

Example 9 with VersionedPacket

use of me.retrodaredevil.solarthing.database.VersionedPacket in project solarthing by wildmountainfarms.

the class StatusChatBotHandler method handleMessage.

@Override
public boolean handleMessage(Message message, MessageSender messageSender) {
    if (ChatBotUtil.isSimilar("battery voltage", message.getText())) {
        FragmentedPacketGroup packetGroup = packetGroupProvider.getPacketGroup();
        Float batteryVoltageAverage = BatteryUtil.getBatteryVoltageAverage(packetGroup);
        if (batteryVoltageAverage == null) {
            messageSender.sendMessage("Battery voltage unavailable from latest data. Sorry!");
        } else {
            messageSender.sendMessage("Battery voltage: " + Formatting.HUNDREDTHS_FORMAT.format(batteryVoltageAverage));
        }
        return true;
    } else if (ChatBotUtil.isSimilar("battery temperature", message.getText()) || ChatBotUtil.isSimilar("battery temp", message.getText())) {
        FragmentedPacketGroup packetGroup = packetGroupProvider.getPacketGroup();
        List<String> lines = new ArrayList<>();
        for (Packet packet : packetGroup.getPackets()) {
            int fragmentId = packetGroup.getFragmentId(packet);
            if (packet instanceof BatteryTemperature && packet instanceof Identifiable) {
                float temperature = ((BatteryTemperature) packet).getBatteryTemperatureFahrenheit();
                IdentityInfo identityInfo = ((Identifiable) packet).getIdentityInfo();
                lines.add(identityInfo.getDisplayName() + " (" + fragmentId + "): " + temperature + "F");
            }
        }
        if (lines.isEmpty()) {
            messageSender.sendMessage("No devices to read temperature!");
        } else {
            messageSender.sendMessage(String.join("\n", lines));
        }
        return true;
    } else if (ChatBotUtil.isSimilar("alter", message.getText())) {
        List<VersionedPacket<StoredAlterPacket>> alterPackets = alterPacketsProvider.getPackets();
        if (alterPackets == null) {
            messageSender.sendMessage("Error - Must have failed to query alter database");
        } else {
            List<String> scheduledCommandLines = new ArrayList<>();
            for (VersionedPacket<StoredAlterPacket> versionedPacket : alterPackets) {
                StoredAlterPacket storedAlterPacket = versionedPacket.getPacket();
                AlterPacket alterPacket = storedAlterPacket.getPacket();
                if (alterPacket instanceof ScheduledCommandPacket) {
                    ScheduledCommandData data = ((ScheduledCommandPacket) alterPacket).getData();
                    // ExecutionReason executionReason = ((ScheduledCommandPacket) alterPacket).getExecutionReason();
                    String timeString = TimeUtil.instantToSlackDateSeconds(Instant.ofEpochMilli(data.getScheduledTimeMillis()));
                    scheduledCommandLines.add(data.getCommandName() + " - " + timeString);
                }
            }
            if (scheduledCommandLines.isEmpty()) {
                messageSender.sendMessage("No scheduled commands (from " + alterPackets.size() + " alter packets)");
            } else {
                messageSender.sendMessage("Scheduled commands:\n\t" + String.join("\n\t", scheduledCommandLines));
            }
        }
        return true;
    }
    return false;
}
Also used : FragmentedPacketGroup(me.retrodaredevil.solarthing.packets.collection.FragmentedPacketGroup) Packet(me.retrodaredevil.solarthing.packets.Packet) VersionedPacket(me.retrodaredevil.solarthing.database.VersionedPacket) StoredAlterPacket(me.retrodaredevil.solarthing.type.alter.StoredAlterPacket) AlterPacket(me.retrodaredevil.solarthing.type.alter.AlterPacket) ScheduledCommandPacket(me.retrodaredevil.solarthing.type.alter.packets.ScheduledCommandPacket) BatteryTemperature(me.retrodaredevil.solarthing.solar.common.BatteryTemperature) StoredAlterPacket(me.retrodaredevil.solarthing.type.alter.StoredAlterPacket) VersionedPacket(me.retrodaredevil.solarthing.database.VersionedPacket) ArrayList(java.util.ArrayList) StoredAlterPacket(me.retrodaredevil.solarthing.type.alter.StoredAlterPacket) AlterPacket(me.retrodaredevil.solarthing.type.alter.AlterPacket) Identifiable(me.retrodaredevil.solarthing.packets.identification.Identifiable) ScheduledCommandPacket(me.retrodaredevil.solarthing.type.alter.packets.ScheduledCommandPacket) IdentityInfo(me.retrodaredevil.solarthing.packets.identification.IdentityInfo) ArrayList(java.util.ArrayList) List(java.util.List) ScheduledCommandData(me.retrodaredevil.solarthing.type.alter.packets.ScheduledCommandData)

Example 10 with VersionedPacket

use of me.retrodaredevil.solarthing.database.VersionedPacket in project solarthing by wildmountainfarms.

the class CancelCommandChatBotHandler method cancelCommand.

private void cancelCommand(MessageSender messageSender, UUID schedulingId) {
    List<VersionedPacket<StoredAlterPacket>> packets = alterPacketsProvider.getPackets();
    if (packets == null) {
        messageSender.sendMessage("Unable to cancel commands, as we are unable to reach the alter database.");
        return;
    }
    List<VersionedPacket<StoredAlterPacket>> targets = findStoredPacketsWithSchedulingIdOrNull(packets.stream(), schedulingId);
    if (targets.isEmpty()) {
        messageSender.sendMessage("Unable to find a scheduled command that was scheduled with the ID of " + schedulingId);
    } else if (targets.size() > 1) {
        messageSender.sendMessage("Multiple packets corresponded to ID: " + schedulingId + ". Please report this error.");
    } else {
        VersionedPacket<StoredAlterPacket> target = targets.get(0);
        messageSender.sendMessage("Going request cancel of " + target.getPacket().getDbId());
        CommandOpenPacket packet = new ImmutableDeleteAlterPacket(target.getPacket().getDbId(), target.getUpdateToken());
        PacketCollectionCreator creator = commandHelper.getCommandManager().makeCreator(sourceId, zoneId, null, packet, PacketCollectionIdGenerator.Defaults.UNIQUE_GENERATOR);
        executorService.execute(() -> {
            Instant now = Instant.now();
            PacketCollection packetCollection = creator.create(now);
            boolean success = true;
            try {
                database.getOpenDatabase().uploadPacketCollection(packetCollection, null);
            } catch (SolarThingDatabaseException e) {
                LOGGER.error("Could not upload alter delete request", e);
                success = false;
            }
            if (success) {
                messageSender.sendMessage("Sent request to delete the scheduled command");
            } else {
                messageSender.sendMessage("Could not upload request to delete scheduled command. You can try again.");
            }
        });
    }
}
Also used : ImmutableDeleteAlterPacket(me.retrodaredevil.solarthing.commands.packets.open.ImmutableDeleteAlterPacket) PacketCollection(me.retrodaredevil.solarthing.packets.collection.PacketCollection) VersionedPacket(me.retrodaredevil.solarthing.database.VersionedPacket) Instant(java.time.Instant) CommandOpenPacket(me.retrodaredevil.solarthing.commands.packets.open.CommandOpenPacket) PacketCollectionCreator(me.retrodaredevil.solarthing.packets.collection.PacketCollectionCreator) SolarThingDatabaseException(me.retrodaredevil.solarthing.database.exception.SolarThingDatabaseException)

Aggregations

VersionedPacket (me.retrodaredevil.solarthing.database.VersionedPacket)10 SolarThingDatabaseException (me.retrodaredevil.solarthing.database.exception.SolarThingDatabaseException)8 Instant (java.time.Instant)5 JsonProcessingException (com.fasterxml.jackson.core.JsonProcessingException)4 StoredAlterPacket (me.retrodaredevil.solarthing.type.alter.StoredAlterPacket)4 JsonData (me.retrodaredevil.couchdbjava.json.JsonData)3 Nullable (me.retrodaredevil.solarthing.annotations.Nullable)3 UpdateConflictSolarThingDatabaseException (me.retrodaredevil.solarthing.database.exception.UpdateConflictSolarThingDatabaseException)3 PacketCollection (me.retrodaredevil.solarthing.packets.collection.PacketCollection)3 PacketCollectionCreator (me.retrodaredevil.solarthing.packets.collection.PacketCollectionCreator)3 AlterPacket (me.retrodaredevil.solarthing.type.alter.AlterPacket)3 ScheduledCommandData (me.retrodaredevil.solarthing.type.alter.packets.ScheduledCommandData)3 JsonNode (com.fasterxml.jackson.databind.JsonNode)2 ObjectNode (com.fasterxml.jackson.databind.node.ObjectNode)2 ArrayList (java.util.ArrayList)2 List (java.util.List)2 DocumentData (me.retrodaredevil.couchdbjava.response.DocumentData)2 AlterPacketsProvider (me.retrodaredevil.solarthing.AlterPacketsProvider)2 NotNull (me.retrodaredevil.solarthing.annotations.NotNull)2 DeleteAlterPacket (me.retrodaredevil.solarthing.commands.packets.open.DeleteAlterPacket)2