forked from FarmMaps/FarmMapsApiClient
Update appsettings, included the three environments test, acceptance and production. + update the NBS sample code to the newest flow (backwards compatible
This commit is contained in:
@@ -12,10 +12,8 @@ using Newtonsoft.Json;
|
||||
using Newtonsoft.Json.Linq;
|
||||
using static FarmmapsApiSamples.Constants;
|
||||
|
||||
namespace FarmmapsNbs
|
||||
{
|
||||
public class NbsApplication : IApplication
|
||||
{
|
||||
namespace FarmmapsNbs {
|
||||
public class NbsApplication : IApplication {
|
||||
private const string DownloadFolder = "Downloads";
|
||||
private const string SettingsFile = "settings.json";
|
||||
|
||||
@@ -27,16 +25,14 @@ namespace FarmmapsNbs
|
||||
private Settings _settings;
|
||||
|
||||
public NbsApplication(ILogger<NbsApplication> logger, FarmmapsApiService farmmapsApiService,
|
||||
GeneralService generalService, NitrogenService nitrogenService)
|
||||
{
|
||||
GeneralService generalService, NitrogenService nitrogenService) {
|
||||
_logger = logger;
|
||||
_farmmapsApiService = farmmapsApiService;
|
||||
_generalService = generalService;
|
||||
_nitrogenService = nitrogenService;
|
||||
}
|
||||
|
||||
public async Task RunAsync()
|
||||
{
|
||||
public async Task RunAsync() {
|
||||
var nitrogenInputJson = File.ReadAllText("NitrogenInput.json");
|
||||
List<NitrogenInput> nitrogenInputs = JsonConvert.DeserializeObject<List<NitrogenInput>>(nitrogenInputJson);
|
||||
|
||||
@@ -47,21 +43,16 @@ namespace FarmmapsNbs
|
||||
await _farmmapsApiService.GetCurrentUserCodeAsync();
|
||||
var roots = await _farmmapsApiService.GetCurrentUserRootsAsync();
|
||||
|
||||
foreach (var input in nitrogenInputs)
|
||||
{
|
||||
try
|
||||
{
|
||||
foreach (var input in nitrogenInputs) {
|
||||
try {
|
||||
await Process(roots, input);
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
} catch (Exception ex) {
|
||||
_logger.LogError(ex.Message);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private async Task Process(List<UserRoot> roots, NitrogenInput input)
|
||||
{
|
||||
private async Task Process(List<UserRoot> roots, NitrogenInput input) {
|
||||
|
||||
// !!specify if you are using an already created cropfield:
|
||||
bool useCreatedCropfield = input.UseCreatedCropfield;
|
||||
@@ -74,45 +65,39 @@ namespace FarmmapsNbs
|
||||
LoadSettings(settingsfile);
|
||||
|
||||
var uploadedRoot = roots.SingleOrDefault(r => r.Name == "Uploaded");
|
||||
if (uploadedRoot == null)
|
||||
{
|
||||
if (uploadedRoot == null) {
|
||||
_logger.LogError("Could not find a needed root item");
|
||||
return;
|
||||
}
|
||||
|
||||
var myDriveRoot = roots.SingleOrDefault(r => r.Name == "My drive");
|
||||
if (myDriveRoot == null)
|
||||
{
|
||||
if (myDriveRoot == null) {
|
||||
_logger.LogError("Could not find a needed root item");
|
||||
return;
|
||||
}
|
||||
|
||||
// Use already created cropfield or create new one
|
||||
Item cropfieldItem;
|
||||
if (useCreatedCropfield == false || string.IsNullOrEmpty(_settings.CropfieldItemCode))
|
||||
{
|
||||
if (useCreatedCropfield == false || string.IsNullOrEmpty(_settings.CropfieldItemCode)) {
|
||||
_logger.LogInformation("Creating cropfield");
|
||||
cropfieldItem = await _generalService.CreateCropfieldItemAsync(myDriveRoot.Code,
|
||||
$"VRA NBS cropfield {input.OutputFileName}", plantingDate.Year, input.GeometryJson.ToString(Formatting.None));
|
||||
_settings.CropfieldItemCode = cropfieldItem.Code;
|
||||
SaveSettings(settingsfile);
|
||||
}
|
||||
else
|
||||
{
|
||||
} else {
|
||||
_logger.LogInformation("Cropfield already exists, trying to get it");
|
||||
cropfieldItem = await _farmmapsApiService.GetItemAsync(_settings.CropfieldItemCode);
|
||||
}
|
||||
|
||||
var inputItem = (Item)null;
|
||||
var geotiffItem = (Item)null;
|
||||
|
||||
// If no input file is specified, use most recent satellite image
|
||||
if (string.IsNullOrEmpty(input.File))
|
||||
{
|
||||
if (string.IsNullOrEmpty(input.File)) {
|
||||
_logger.LogInformation("No specific data given, retrieving most recent satellite image");
|
||||
|
||||
// check if satellite task not yet done, do here and save taskcode
|
||||
if (useCreatedCropfield == false || string.IsNullOrEmpty(_settings.SatelliteTaskCode))
|
||||
{
|
||||
if (useCreatedCropfield == false || string.IsNullOrEmpty(_settings.SatelliteTaskCode)) {
|
||||
var satelliteTaskCode = await _generalService.RunSatelliteTask(cropfieldItem);
|
||||
_settings.SatelliteTaskCode = satelliteTaskCode;
|
||||
SaveSettings(settingsfile);
|
||||
@@ -120,96 +105,87 @@ namespace FarmmapsNbs
|
||||
|
||||
|
||||
// Select a particular satellite item from satelliteTask
|
||||
Item satalliteItem = await _generalService.FindSatelliteItem(cropfieldItem, _settings.SatelliteTaskCode);
|
||||
Item satelliteItem = await _generalService.FindSatelliteItem(cropfieldItem, _settings.SatelliteTaskCode);
|
||||
|
||||
var satelliteBand = satalliteItem.Data["layers"][0]["name"];
|
||||
var satelliteStatistics = satalliteItem.Data["layers"][0]["renderer"]["band"]["statistics"];
|
||||
Console.WriteLine($"Satellite image date: {satalliteItem.DataDate}");
|
||||
var satelliteBand = satelliteItem.Data["layers"][0]["name"];
|
||||
var satelliteStatistics = satelliteItem.Data["layers"][0]["renderer"]["band"]["statistics"];
|
||||
Console.WriteLine($"Satellite image date: {satelliteItem.DataDate}");
|
||||
//Console.WriteLine($"Satellite image statistics for band {satelliteBand}: {satelliteStatistics}");
|
||||
|
||||
//Store data to csv
|
||||
if (StoreStatistics == true)
|
||||
{
|
||||
if (StoreStatistics == true) {
|
||||
|
||||
var SatelliteStatsFile = $"{DownloadFolder}/SatelliteDataStatistics_{FieldName}_{satalliteItem.DataDate.Value:yyyy-MM-dd}.csv";
|
||||
var SatelliteStatsFile = $"{DownloadFolder}/SatelliteDataStatistics_{FieldName}_{satelliteItem.DataDate.Value:yyyy-MM-dd}.csv";
|
||||
using var w = new StreamWriter(SatelliteStatsFile);
|
||||
{
|
||||
foreach (var item in satelliteStatistics)
|
||||
{
|
||||
foreach (var item in satelliteStatistics) {
|
||||
var line = string.Format("{0}", item);
|
||||
w.WriteLine(line);
|
||||
w.Flush();
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
|
||||
// must be wdvi[1]
|
||||
var inputType = (satalliteItem.Data["layers"] as JArray)?[1]["name"].ToString();
|
||||
if (string.IsNullOrEmpty(inputType))
|
||||
{
|
||||
var inputType = (satelliteItem.Data["layers"] as JArray)?[1]["name"].ToString();
|
||||
if (string.IsNullOrEmpty(inputType)) {
|
||||
_logger.LogError("Could not get the input type name from the satellite item");
|
||||
return;
|
||||
}
|
||||
|
||||
// download the geotiff
|
||||
var SatelliteImageDate = (DateTime)satalliteItem.DataDate;
|
||||
var SatelliteImageDate = (DateTime)satelliteItem.DataDate;
|
||||
var SatelliteDate = SatelliteImageDate.ToString("yyyyMMdd");
|
||||
_logger.LogInformation("Downloading geotiff file");
|
||||
await _farmmapsApiService.DownloadItemAsync(satalliteItem.Code,
|
||||
await _farmmapsApiService.DownloadItemAsync(satelliteItem.Code,
|
||||
Path.Combine(DownloadFolder, $"nbs_inputSatelliteGeotiff_{input.OutputFileName}_{inputType}_{SatelliteDate}.zip"));
|
||||
|
||||
// overwrite measurement date by date of satellite item
|
||||
measurementDate = satalliteItem.DataDate.Value;
|
||||
|
||||
geotiffItem = satalliteItem;
|
||||
|
||||
|
||||
measurementDate = satelliteItem.DataDate.Value;
|
||||
inputItem = satelliteItem;
|
||||
}
|
||||
|
||||
|
||||
// (geo)tiff input:
|
||||
else if (input.File.Contains(".tif") || input.File.Contains(".geotiff"))
|
||||
{
|
||||
else if (input.File.Contains(".tif") || input.File.Contains(".geotiff")) {
|
||||
_logger.LogInformation("input = tiff data");
|
||||
var dataPath = Path.Combine("Data", input.File);
|
||||
geotiffItem = await _generalService.UploadDataAsync(uploadedRoot, GEOTIFF_PROCESSED_ITEMTYPE, dataPath,
|
||||
inputItem = await _generalService.UploadDataAsync(uploadedRoot, GEOTIFF_PROCESSED_ITEMTYPE, dataPath,
|
||||
Path.GetFileNameWithoutExtension(input.File));
|
||||
|
||||
if (geotiffItem == null)
|
||||
{
|
||||
if (geotiffItem == null) {
|
||||
_logger.LogError("Could not find item for uploaded data");
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
// json/shape input
|
||||
else
|
||||
{
|
||||
else {
|
||||
var isGeoJson = input.File.Contains("json");
|
||||
var dataPath = Path.Combine("Data", input.File);
|
||||
var shapeItem = isGeoJson ?
|
||||
await _generalService.UploadDataAsync(uploadedRoot, SHAPE_PROCESSED_ITEMTYPE, dataPath, Path.GetFileNameWithoutExtension(input.File), input.GeometryJson.ToString(Formatting.None)) :
|
||||
await _generalService.UploadZipWithShapeAsync(uploadedRoot, dataPath, Path.GetFileNameWithoutExtension(input.File), input.GeometryJson.ToString(Formatting.None));
|
||||
|
||||
if (shapeItem == null)
|
||||
{
|
||||
if (shapeItem == null) {
|
||||
_logger.LogError("Could not find item for uploaded data");
|
||||
return;
|
||||
}
|
||||
inputItem = shapeItem;
|
||||
////convert shape to geotiff, not necessary anymore. However can still be done
|
||||
//_logger.LogInformation($"Converting shape to geotiff");
|
||||
//geotiffItem = await _generalService.ShapeToGeotiff(shapeItem, 1, input.InputLayerName);
|
||||
//if (geotiffItem == null)
|
||||
//{
|
||||
// _logger.LogError("Something went wrong with shape to geotiff transformation");
|
||||
// return;
|
||||
//}
|
||||
|
||||
_logger.LogInformation($"Converting shape to geotiff");
|
||||
geotiffItem = await _generalService.ShapeToGeotiff(shapeItem, 1, input.InputLayerName);
|
||||
if (geotiffItem == null)
|
||||
{
|
||||
_logger.LogError("Something went wrong with shape to geotiff transformation");
|
||||
return;
|
||||
}
|
||||
|
||||
_logger.LogInformation("Downloading geotiff file");
|
||||
await _farmmapsApiService.DownloadItemAsync(geotiffItem.Code,
|
||||
Path.Combine(DownloadFolder, $"{input.OutputFileName}.input_geotiff.zip"));
|
||||
//_logger.LogInformation("Downloading geotiff file");
|
||||
//await _farmmapsApiService.DownloadItemAsync(geotiffItem.Code,
|
||||
// Path.Combine(DownloadFolder, $"{input.OutputFileName}.input_geotiff.zip"));
|
||||
//inputItem = geotiffItem;
|
||||
////End shape to geotiff transformation
|
||||
}
|
||||
|
||||
|
||||
@@ -218,16 +194,12 @@ namespace FarmmapsNbs
|
||||
var targetNData = await _nitrogenService.CalculateTargetN(cropfieldItem, targetNItem, plantingDate,
|
||||
measurementDate, input.PotatoPurposeType, input.TargetYield);
|
||||
|
||||
if (targetNData == null)
|
||||
{
|
||||
if (targetNData == null) {
|
||||
_logger.LogError("Something went wrong with TargetN calculation");
|
||||
return;
|
||||
}
|
||||
|
||||
_logger.LogInformation($"TargetN: {targetNData.TargetN}");
|
||||
////Option to manually adjust the Target N, for test purposes only!
|
||||
//targetNData.TargetN = 225;
|
||||
//_logger.LogInformation($"TargetN adjusted: {targetNData.TargetN}");
|
||||
|
||||
var targetNDataPath = Path.Combine(DownloadFolder, $"{input.OutputFileName}.targetn.json");
|
||||
|
||||
@@ -235,10 +207,9 @@ namespace FarmmapsNbs
|
||||
|
||||
_logger.LogInformation("Calculating uptake map");
|
||||
var uptakeMapItem =
|
||||
await _nitrogenService.CalculateUptakeMap(cropfieldItem, geotiffItem, plantingDate,
|
||||
await _nitrogenService.CalculateUptakeMap(cropfieldItem, inputItem, plantingDate,
|
||||
measurementDate, input.InputVariable, input.InputLayerName);
|
||||
if (uptakeMapItem == null)
|
||||
{
|
||||
if (uptakeMapItem == null) {
|
||||
_logger.LogError("Something went wrong with creating the uptakeMap");
|
||||
return;
|
||||
}
|
||||
@@ -250,11 +221,10 @@ namespace FarmmapsNbs
|
||||
|
||||
_logger.LogInformation("Calculating application map");
|
||||
var applianceMapItem =
|
||||
await _nitrogenService.CalculateApplicationMap(cropfieldItem, geotiffItem, plantingDate,
|
||||
await _nitrogenService.CalculateApplicationMap(cropfieldItem, inputItem, plantingDate,
|
||||
measurementDate, input.InputVariable, targetNData.TargetN, input.InputLayerName);
|
||||
|
||||
if (applianceMapItem == null)
|
||||
{
|
||||
if (applianceMapItem == null) {
|
||||
_logger.LogError("Something went wrong with creating the applicationMap");
|
||||
return;
|
||||
}
|
||||
@@ -266,24 +236,20 @@ namespace FarmmapsNbs
|
||||
//transforming tiff to shape
|
||||
var tiffItem = applianceMapItem;
|
||||
|
||||
if (tiffItem == null)
|
||||
{
|
||||
if (tiffItem == null) {
|
||||
_logger.LogError("Could not find item for uploaded data");
|
||||
return;
|
||||
}
|
||||
|
||||
//ApplicationMap (GEOTIFF) To Taskmap
|
||||
if (input.GenerateTaskmap)
|
||||
{
|
||||
if (input.GenerateTaskmap) {
|
||||
//GEOTIFF TO Taskmap
|
||||
_logger.LogInformation($"Converting geotiff to taskmap");
|
||||
|
||||
var taskmap = (Item)null;
|
||||
if (input.OutputType == "isoxml")
|
||||
{
|
||||
if (input.OutputType == "isoxml") {
|
||||
|
||||
if (input.DdiCode == null)
|
||||
{
|
||||
if (input.DdiCode == null) {
|
||||
_logger.LogInformation("DDi not given. Using expected identifiers");
|
||||
input.DdiCode = input.DdiCode = "0006";
|
||||
|
||||
@@ -293,9 +259,7 @@ namespace FarmmapsNbs
|
||||
endPoint: input.EndPoint.ToString(Formatting.None), angle: input.Angle, precision: input.Precision,
|
||||
cropTypeName: null, costumerName: null, ProductGroupName: null, productName: null, resolution: null, unitScale: null, maximumClasses: input.MaximumClasses);
|
||||
|
||||
}
|
||||
else
|
||||
{
|
||||
} else {
|
||||
taskmap = await _generalService.CreateTaskmap(cropfieldItem: cropfieldItem, tiffItem: applianceMapItem, outputType: input.OutputType, cellWidth: input.CellWidth,
|
||||
cellHeight: input.CellHeight, startPoint: input.StartPoint.ToString(Formatting.None), inputLayerName: input.InputLayerName, centered: input.Centered,
|
||||
endPoint: input.EndPoint.ToString(Formatting.None), angle: input.Angle, precision: input.Precision, maximumClasses: input.MaximumClasses);
|
||||
@@ -303,8 +267,7 @@ namespace FarmmapsNbs
|
||||
|
||||
|
||||
|
||||
if (taskmap == null)
|
||||
{
|
||||
if (taskmap == null) {
|
||||
_logger.LogError("Something went wrong with geotiff to taskmap transformation");
|
||||
return;
|
||||
}
|
||||
@@ -320,29 +283,23 @@ namespace FarmmapsNbs
|
||||
}
|
||||
|
||||
// Functions to save previously created cropfields
|
||||
private void LoadSettings(string file)
|
||||
{
|
||||
if (File.Exists(file))
|
||||
{
|
||||
private void LoadSettings(string file) {
|
||||
if (File.Exists(file)) {
|
||||
var jsonText = File.ReadAllText(file);
|
||||
_settings = JsonConvert.DeserializeObject<Settings>(jsonText);
|
||||
}
|
||||
else
|
||||
{
|
||||
} else {
|
||||
_settings = new Settings();
|
||||
}
|
||||
}
|
||||
|
||||
private void SaveSettings(string file)
|
||||
{
|
||||
private void SaveSettings(string file) {
|
||||
if (_settings == null)
|
||||
return;
|
||||
|
||||
var json = JsonConvert.SerializeObject(_settings);
|
||||
File.WriteAllText(file, json);
|
||||
}
|
||||
private void SaveInfo(string file)
|
||||
{
|
||||
private void SaveInfo(string file) {
|
||||
if (_settings == null)
|
||||
return;
|
||||
|
||||
@@ -352,4 +309,4 @@ namespace FarmmapsNbs
|
||||
}
|
||||
|
||||
}
|
||||
}
|
||||
}
|
||||
|
Reference in New Issue
Block a user