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);
}
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());
}
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);
}
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;
}))));
}
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;
}
Aggregations