Search in sources :

Example 1 with SolarThingDatabase

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

the class AlterManagerActionNode method createAction.

@Override
public Action createAction(ActionEnvironment actionEnvironment) {
    SolarThingDatabaseEnvironment solarThingDatabaseEnvironment = actionEnvironment.getInjectEnvironment().get(SolarThingDatabaseEnvironment.class);
    OpenDatabaseCacheEnvironment openDatabaseCacheEnvironment = actionEnvironment.getInjectEnvironment().get(OpenDatabaseCacheEnvironment.class);
    AuthorizationEnvironment authorizationEnvironment = actionEnvironment.getInjectEnvironment().get(AuthorizationEnvironment.class);
    AlterPacketsEnvironment alterPacketsEnvironment = actionEnvironment.getInjectEnvironment().get(AlterPacketsEnvironment.class);
    SourceIdEnvironment sourceIdEnvironment = actionEnvironment.getInjectEnvironment().get(SourceIdEnvironment.class);
    TimeZoneEnvironment timeZoneEnvironment = actionEnvironment.getInjectEnvironment().get(TimeZoneEnvironment.class);
    SolarThingDatabase database = solarThingDatabaseEnvironment.getSolarThingDatabase();
    DatabaseCache openDatabaseCache = openDatabaseCacheEnvironment.getOpenDatabaseCache();
    String sourceId = sourceIdEnvironment.getSourceId();
    AlterPacketsProvider alterPacketsProvider = alterPacketsEnvironment.getAlterPacketsProvider();
    return new AlterManagerAction(new CommandManager(keyDirectory, sender), authorizationEnvironment.getPublicKeyLookUp(), database, openDatabaseCache, alterPacketsProvider, sourceId, timeZoneEnvironment.getZoneId(), fragmentId);
}
Also used : CommandManager(me.retrodaredevil.solarthing.commands.util.CommandManager) AlterPacketsProvider(me.retrodaredevil.solarthing.AlterPacketsProvider) SolarThingDatabase(me.retrodaredevil.solarthing.database.SolarThingDatabase) DatabaseCache(me.retrodaredevil.solarthing.database.cache.DatabaseCache)

Example 2 with SolarThingDatabase

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

the class PVOutputUploadMain method startPVOutputUpload.

// TODO Make this an action for the automation program
@SuppressWarnings({ "SameReturnValue", "deprecation" })
public static int startPVOutputUpload(PVOutputUploadProgramOptions options, CommandOptions commandOptions, File dataDirectory) {
    LOGGER.info(SolarThingConstants.SUMMARY_MARKER, "Starting PV Output upload program");
    ZoneId zoneId = options.getZoneId();
    // Use US local since I (retrodaredevil) am the one debugging
    LOGGER.info(SolarThingConstants.SUMMARY_MARKER, "Using time zone: {}", zoneId.getDisplayName(TextStyle.FULL, Locale.US));
    LOGGER.info("Using default instance options: " + options.getDefaultInstanceOptions());
    DatabaseConfig databaseConfig = ConfigUtil.getDatabaseConfig(options.getDatabase());
    DatabaseType databaseType = databaseConfig.getType();
    if (databaseType != CouchDbDatabaseSettings.TYPE) {
        LOGGER.error(SolarThingConstants.SUMMARY_MARKER, "(Fatal)Only CouchDb can be used for this program type right now!");
        return SolarThingConstants.EXIT_CODE_INVALID_CONFIG;
    }
    CouchDbDatabaseSettings couchDbDatabaseSettings = (CouchDbDatabaseSettings) databaseConfig.getSettings();
    SolarThingDatabase database = CouchDbSolarThingDatabase.create(CouchDbUtil.createInstance(couchDbDatabaseSettings.getCouchProperties(), couchDbDatabaseSettings.getOkHttpProperties()));
    OkHttpClient client = PVOutputOkHttpUtil.configure(new OkHttpClient.Builder(), options.getApiKey(), options.getSystemId()).addInterceptor(new HttpLoggingInterceptor(LOGGER::debug).setLevel(HttpLoggingInterceptor.Level.BASIC)).build();
    Retrofit retrofit = PVOutputRetrofitUtil.defaultBuilder().client(client).build();
    PVOutputService service = retrofit.create(PVOutputService.class);
    PVOutputHandler handler = new PVOutputHandler(zoneId, options.getRequiredIdentifierMap(), options.getVoltageIdentifierFragmentMatcher(), options.getTemperatureIdentifierFragmentMatcher());
    String fromDateString = commandOptions.getPVOutputFromDate();
    String toDateString = commandOptions.getPVOutputToDate();
    if (fromDateString != null && toDateString != null) {
        System.out.println("Starting range upload");
        final SimpleDate fromDate;
        final SimpleDate toDate;
        try {
            // TODO Don't use SimpleDateFormat anymore and remove supress warnings for deprecation
            fromDate = SimpleDate.fromDate(DATE_FORMAT.parse(fromDateString));
            toDate = SimpleDate.fromDate(DATE_FORMAT.parse(toDateString));
        } catch (ParseException e) {
            e.printStackTrace();
            System.err.println("Unable to parser either from date or to date. Use the yyyy-MM-dd format");
            return SolarThingConstants.EXIT_CODE_INVALID_OPTIONS;
        }
        return startRangeUpload(fromDate, toDate, options, database, handler, service, options.getZoneId());
    } else if ((fromDateString == null) != (toDateString == null)) {
        LOGGER.error(SolarThingConstants.SUMMARY_MARKER, "(Fatal)You need to define both from and to, or define neither to do the normal PVOutput program!");
        return SolarThingConstants.EXIT_CODE_INVALID_OPTIONS;
    }
    AnalyticsManager analyticsManager = new AnalyticsManager(options.isAnalyticsEnabled(), dataDirectory);
    analyticsManager.sendStartUp(ProgramType.PVOUTPUT_UPLOAD);
    return startRealTimeProgram(options, database, handler, service, options.getZoneId());
}
Also used : OkHttpClient(okhttp3.OkHttpClient) ZoneId(java.time.ZoneId) DatabaseType(me.retrodaredevil.solarthing.config.databases.DatabaseType) PVOutputService(me.retrodaredevil.solarthing.pvoutput.service.PVOutputService) Retrofit(retrofit2.Retrofit) CouchDbDatabaseSettings(me.retrodaredevil.solarthing.config.databases.implementations.CouchDbDatabaseSettings) SimpleDate(me.retrodaredevil.solarthing.pvoutput.SimpleDate) ParseException(java.text.ParseException) CouchDbSolarThingDatabase(me.retrodaredevil.solarthing.database.couchdb.CouchDbSolarThingDatabase) SolarThingDatabase(me.retrodaredevil.solarthing.database.SolarThingDatabase) HttpLoggingInterceptor(okhttp3.logging.HttpLoggingInterceptor) DatabaseConfig(me.retrodaredevil.solarthing.program.DatabaseConfig) AnalyticsManager(me.retrodaredevil.solarthing.analytics.AnalyticsManager)

Example 3 with SolarThingDatabase

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

the class SendEncryptedActionNode method createAction.

@Override
public Action createAction(ActionEnvironment actionEnvironment) {
    SolarThingDatabase database = actionEnvironment.getInjectEnvironment().get(SolarThingDatabaseEnvironment.class).getSolarThingDatabase();
    String sourceId = actionEnvironment.getInjectEnvironment().get(SourceIdEnvironment.class).getSourceId();
    ZoneId zoneId = actionEnvironment.getInjectEnvironment().get(TimeZoneEnvironment.class).getZoneId();
    CommandOpenPacket packet = packetProvider.get();
    requireNonNull(packet, "The supplier should have given us a packet!");
    PacketCollectionCreator creator = commandManager.makeCreator(sourceId, zoneId, InstanceTargetPackets.create(fragmentIdTargets), packet, PacketCollectionIdGenerator.Defaults.UNIQUE_GENERATOR);
    return Actions.createLinkedActionRunner(new SendPacketAction(threadFactory, database::getOpenDatabase, creator, 100, 10, // TODO allow actions to be passed in for these
    PassActionNode.getInstance().createAction(actionEnvironment), PassActionNode.getInstance().createAction(actionEnvironment)), WhenDone.BE_DONE, true);
}
Also used : SolarThingDatabaseEnvironment(me.retrodaredevil.solarthing.actions.environment.SolarThingDatabaseEnvironment) SourceIdEnvironment(me.retrodaredevil.solarthing.actions.environment.SourceIdEnvironment) TimeZoneEnvironment(me.retrodaredevil.solarthing.actions.environment.TimeZoneEnvironment) ZoneId(java.time.ZoneId) CommandOpenPacket(me.retrodaredevil.solarthing.commands.packets.open.CommandOpenPacket) SolarThingDatabase(me.retrodaredevil.solarthing.database.SolarThingDatabase) PacketCollectionCreator(me.retrodaredevil.solarthing.packets.collection.PacketCollectionCreator)

Example 4 with SolarThingDatabase

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

the class SlackChatBotActionNode method createAction.

@Override
public Action createAction(ActionEnvironment actionEnvironment) {
    LatestFragmentedPacketGroupEnvironment latestPacketGroupEnvironment = actionEnvironment.getInjectEnvironment().get(LatestFragmentedPacketGroupEnvironment.class);
    AlterPacketsEnvironment alterPacketsEnvironment = actionEnvironment.getInjectEnvironment().get(AlterPacketsEnvironment.class);
    SolarThingDatabaseEnvironment solarThingDatabaseEnvironment = actionEnvironment.getInjectEnvironment().get(SolarThingDatabaseEnvironment.class);
    SourceIdEnvironment sourceIdEnvironment = actionEnvironment.getInjectEnvironment().get(SourceIdEnvironment.class);
    TimeZoneEnvironment timeZoneEnvironment = actionEnvironment.getInjectEnvironment().get(TimeZoneEnvironment.class);
    EventDatabaseCacheEnvironment eventDatabaseCacheEnvironment = actionEnvironment.getInjectEnvironment().get(EventDatabaseCacheEnvironment.class);
    // Note that all objects listed here must be thread safe, as data will be accessed from them on a separate thread
    FragmentedPacketGroupProvider packetGroupProvider = latestPacketGroupEnvironment.getFragmentedPacketGroupProvider();
    AlterPacketsProvider alterPacketsProvider = alterPacketsEnvironment.getAlterPacketsProvider();
    SolarThingDatabase database = solarThingDatabaseEnvironment.getSolarThingDatabase();
    String sourceId = sourceIdEnvironment.getSourceId();
    ZoneId zoneId = timeZoneEnvironment.getZoneId();
    ResourceManager<? extends DatabaseCache> eventDatabaseCacheManager = eventDatabaseCacheEnvironment.getEventDatabaseCacheManager();
    Slack slack = Slack.getInstance(new SlackConfig(), new SlackHttpClient(new OkHttpClient.Builder().callTimeout(Duration.ofSeconds(10)).connectTimeout(Duration.ofSeconds(4)).build()));
    ChatBotCommandHelper commandHelper = new ChatBotCommandHelper(permissionMap, packetGroupProvider, new CommandManager(keyDirectory, sender));
    return new SlackChatBotAction(appToken, new SlackMessageSender(authToken, channelId, slack), slack, new HelpChatBotHandler(new ChatBotHandlerMultiplexer(Arrays.asList(// note: this isn't applied to "help" commands
    new StaleMessageHandler(), new ScheduleCommandChatBotHandler(commandHelper, database, sourceId, zoneId), new CancelCommandChatBotHandler(commandHelper, database, sourceId, zoneId, alterPacketsProvider), new FlagCommandChatBotHandler(commandHelper, database, sourceId, zoneId, alterPacketsProvider), new CommandChatBotHandler(commandHelper, database, sourceId, zoneId), new StatusChatBotHandler(packetGroupProvider, alterPacketsProvider), new HeartbeatCommandChatBotHandler(eventDatabaseCacheManager), (message, messageSender) -> {
        messageSender.sendMessage("Unknown command!");
        return true;
    }))));
}
Also used : EventDatabaseCacheEnvironment(me.retrodaredevil.solarthing.actions.environment.EventDatabaseCacheEnvironment) SlackHttpClient(com.slack.api.util.http.SlackHttpClient) CommandManager(me.retrodaredevil.solarthing.commands.util.CommandManager) Arrays(java.util.Arrays) Slack(com.slack.api.Slack) me.retrodaredevil.solarthing.chatbot(me.retrodaredevil.solarthing.chatbot) AlterPacketsProvider(me.retrodaredevil.solarthing.AlterPacketsProvider) SourceIdEnvironment(me.retrodaredevil.solarthing.actions.environment.SourceIdEnvironment) TimeZoneEnvironment(me.retrodaredevil.solarthing.actions.environment.TimeZoneEnvironment) LatestFragmentedPacketGroupEnvironment(me.retrodaredevil.solarthing.actions.environment.LatestFragmentedPacketGroupEnvironment) ActionEnvironment(me.retrodaredevil.action.node.environment.ActionEnvironment) SlackMessageSender(me.retrodaredevil.solarthing.message.implementations.SlackMessageSender) ResourceManager(me.retrodaredevil.solarthing.util.sync.ResourceManager) FragmentedPacketGroupProvider(me.retrodaredevil.solarthing.FragmentedPacketGroupProvider) Action(me.retrodaredevil.action.Action) Duration(java.time.Duration) Map(java.util.Map) SolarThingDatabaseEnvironment(me.retrodaredevil.solarthing.actions.environment.SolarThingDatabaseEnvironment) EventDatabaseCacheEnvironment(me.retrodaredevil.solarthing.actions.environment.EventDatabaseCacheEnvironment) SolarThingDatabase(me.retrodaredevil.solarthing.database.SolarThingDatabase) ActionNode(me.retrodaredevil.action.node.ActionNode) DatabaseCache(me.retrodaredevil.solarthing.database.cache.DatabaseCache) File(java.io.File) ZoneId(java.time.ZoneId) List(java.util.List) OkHttpClient(okhttp3.OkHttpClient) SlackConfig(com.slack.api.SlackConfig) AlterPacketsEnvironment(me.retrodaredevil.solarthing.actions.environment.AlterPacketsEnvironment) SourceIdEnvironment(me.retrodaredevil.solarthing.actions.environment.SourceIdEnvironment) TimeZoneEnvironment(me.retrodaredevil.solarthing.actions.environment.TimeZoneEnvironment) OkHttpClient(okhttp3.OkHttpClient) SlackHttpClient(com.slack.api.util.http.SlackHttpClient) FragmentedPacketGroupProvider(me.retrodaredevil.solarthing.FragmentedPacketGroupProvider) SlackMessageSender(me.retrodaredevil.solarthing.message.implementations.SlackMessageSender) LatestFragmentedPacketGroupEnvironment(me.retrodaredevil.solarthing.actions.environment.LatestFragmentedPacketGroupEnvironment) SlackConfig(com.slack.api.SlackConfig) CommandManager(me.retrodaredevil.solarthing.commands.util.CommandManager) SolarThingDatabase(me.retrodaredevil.solarthing.database.SolarThingDatabase) ZoneId(java.time.ZoneId) AlterPacketsEnvironment(me.retrodaredevil.solarthing.actions.environment.AlterPacketsEnvironment) SolarThingDatabaseEnvironment(me.retrodaredevil.solarthing.actions.environment.SolarThingDatabaseEnvironment) Slack(com.slack.api.Slack) AlterPacketsProvider(me.retrodaredevil.solarthing.AlterPacketsProvider)

Example 5 with SolarThingDatabase

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

the class CommandUtil method getCommandRequesterHandlerList.

/**
 * Gets packet handlers that will download requested commands
 * @param databaseConfigs The list of database configs
 * @param packetGroupReceiver Receives data that has been downloaded. Note that this may be called in a separate thread, so make sure it is thread safe
 * @param options The options object
 * @return A list of packet handlers that, when called, will possibly download commands and then forward those commands to {@code packetGroupReceiver}
 */
public static List<PacketHandler> getCommandRequesterHandlerList(List<DatabaseConfig> databaseConfigs, PacketGroupReceiver packetGroupReceiver, PacketHandlingOption options) {
    // Handlers to request and get new commands to send (This may block the current thread). (This doesn't actually handle packets)
    final List<PacketHandler> commandRequesterHandlerList = new ArrayList<>();
    for (DatabaseConfig config : databaseConfigs) {
        if (CouchDbDatabaseSettings.TYPE.equals(config.getType())) {
            CouchDbDatabaseSettings settings = (CouchDbDatabaseSettings) config.getSettings();
            CouchDbInstance instance = CouchDbUtil.createInstance(settings.getCouchProperties(), settings.getOkHttpProperties());
            SolarThingDatabase database = CouchDbSolarThingDatabase.create(instance);
            IndividualSettings individualSettings = config.getIndividualSettingsOrDefault(Constants.DATABASE_COMMAND_DOWNLOAD_ID, null);
            FrequencySettings frequencySettings = individualSettings != null ? individualSettings.getFrequencySettings() : FrequencySettings.NORMAL_SETTINGS;
            PacketHandler packetHandler = new PacketHandler() {

                private final SecurityPacketReceiver securityPacketReceiver = new SecurityPacketReceiver(DatabaseDocumentKeyMap.createFromDatabase(database), packetGroupReceiver, new SecurityPacketReceiver.InstanceTargetPredicate(options.getSourceId(), options.getFragmentId()), Collections.singleton(CommandOpenPacket.class), System.currentTimeMillis(), options.getFragmentId(), options.getSourceId(), database.getEventDatabase());

                @Override
                public void handle(PacketCollection packetCollection) throws PacketHandleException {
                    final List<StoredPacketGroup> packetGroups;
                    try {
                        packetGroups = database.getOpenDatabase().query(new MillisQueryBuilder().startKey(System.currentTimeMillis() - 5 * 60 * 1000).build());
                    } catch (SolarThingDatabaseException e) {
                        throw new PacketHandleException(e);
                    }
                    securityPacketReceiver.receivePacketGroups(packetGroups);
                }
            };
            commandRequesterHandlerList.add(new ThrottleFactorPacketHandler(new AsyncPacketHandlerWrapper(new PrintPacketHandleExceptionWrapper(packetHandler)), frequencySettings));
        }
    }
    return commandRequesterHandlerList;
}
Also used : PacketCollection(me.retrodaredevil.solarthing.packets.collection.PacketCollection) ArrayList(java.util.ArrayList) MillisQueryBuilder(me.retrodaredevil.solarthing.database.MillisQueryBuilder) SolarThingDatabaseException(me.retrodaredevil.solarthing.database.exception.SolarThingDatabaseException) CouchDbDatabaseSettings(me.retrodaredevil.solarthing.config.databases.implementations.CouchDbDatabaseSettings) StoredPacketGroup(me.retrodaredevil.solarthing.packets.collection.StoredPacketGroup) CouchDbInstance(me.retrodaredevil.couchdbjava.CouchDbInstance) CouchDbSolarThingDatabase(me.retrodaredevil.solarthing.database.couchdb.CouchDbSolarThingDatabase) SolarThingDatabase(me.retrodaredevil.solarthing.database.SolarThingDatabase) IndividualSettings(me.retrodaredevil.solarthing.config.databases.IndividualSettings)

Aggregations

SolarThingDatabase (me.retrodaredevil.solarthing.database.SolarThingDatabase)5 ZoneId (java.time.ZoneId)3 AlterPacketsProvider (me.retrodaredevil.solarthing.AlterPacketsProvider)2 SolarThingDatabaseEnvironment (me.retrodaredevil.solarthing.actions.environment.SolarThingDatabaseEnvironment)2 SourceIdEnvironment (me.retrodaredevil.solarthing.actions.environment.SourceIdEnvironment)2 TimeZoneEnvironment (me.retrodaredevil.solarthing.actions.environment.TimeZoneEnvironment)2 CommandManager (me.retrodaredevil.solarthing.commands.util.CommandManager)2 CouchDbDatabaseSettings (me.retrodaredevil.solarthing.config.databases.implementations.CouchDbDatabaseSettings)2 DatabaseCache (me.retrodaredevil.solarthing.database.cache.DatabaseCache)2 CouchDbSolarThingDatabase (me.retrodaredevil.solarthing.database.couchdb.CouchDbSolarThingDatabase)2 OkHttpClient (okhttp3.OkHttpClient)2 Slack (com.slack.api.Slack)1 SlackConfig (com.slack.api.SlackConfig)1 SlackHttpClient (com.slack.api.util.http.SlackHttpClient)1 File (java.io.File)1 ParseException (java.text.ParseException)1 Duration (java.time.Duration)1 ArrayList (java.util.ArrayList)1 Arrays (java.util.Arrays)1 List (java.util.List)1