FarmMapsApiClient_WURtest/FarmmapsZonering/ZoneringApplication.cs

213 lines
8.3 KiB
C#
Raw Permalink Normal View History

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
using FarmmapsApi;
using FarmmapsApi.Models;
using FarmmapsApi.Services;
using FarmmapsHaulmkilling.Models;
2020-11-12 14:49:17 +00:00
using FarmmapsZonering.Models;
using FarmmapsZonering.Services;
using Microsoft.Extensions.Logging;
using Newtonsoft.Json;
using static FarmmapsApiSamples.Constants;
namespace FarmmapsZonering
{
public class ZoneringApplication : IApplication
{
private const string DownloadFolder = "Downloads";
private const string SettingsFile = "settings.json";
private readonly ILogger<ZoneringApplication> _logger;
private readonly FarmmapsApiService _farmmapsApiService;
private readonly GeneralService _generalService;
private readonly ZoneringService _zoneringService;
private Settings _settings;
public ZoneringApplication(ILogger<ZoneringApplication> logger, FarmmapsApiService farmmapsApiService,
GeneralService generalService, ZoneringService zoneringService)
{
_logger = logger;
_farmmapsApiService = farmmapsApiService;
_generalService = generalService;
_zoneringService = zoneringService;
}
public async Task RunAsync()
{
if (!Directory.Exists(DownloadFolder))
Directory.CreateDirectory(DownloadFolder);
// Read input data from separate file
var zoneringInputJson = File.ReadAllText("ZoneringInput.json");
List<ZoneringInput> zoneringInputs = JsonConvert.DeserializeObject<List<ZoneringInput>>(zoneringInputJson);
// !! this call is needed the first time an api is called with a fresh clientid and secret !!
await _farmmapsApiService.GetCurrentUserCodeAsync();
var roots = await _farmmapsApiService.GetCurrentUserRootsAsync();
2020-11-17 15:37:13 +00:00
2020-11-12 14:49:17 +00:00
foreach (var input in zoneringInputs)
{
try
2020-11-17 15:37:13 +00:00
{
await ZoningAsync(roots, input);
}
catch (Exception ex)
2020-11-17 15:37:13 +00:00
{
_logger.LogError(ex.Message);
}
}
}
private async Task ZoningAsync(List<UserRoot> roots, ZoneringInput input)
{
2022-02-28 13:29:56 +00:00
var myDrive = roots.SingleOrDefault(r => r.Name == "USER_FILES");
if (myDrive == null)
{
_logger.LogError("Could not find a needed root item");
return;
}
2021-03-01 13:04:18 +00:00
bool useCreatedCropfield = false;
2021-01-28 14:08:32 +00:00
bool GetWatBal = input.GetWatBal;
bool getVanDerSat = input.GetVanDerSat;
bool StoreVanDerSatStatistics = input.storeVanDerSatStatistics;
var FieldName = input.CropFieldName;
2021-01-28 14:08:32 +00:00
string settingsfile = $"Settings_{FieldName}.json";
// Load settings from previous cropfield
LoadSettings(settingsfile);
2022-02-28 13:29:56 +00:00
var uploadedRoot = roots.SingleOrDefault(r => r.Name == "USER_IN");
if (uploadedRoot == null)
{
_logger.LogError("Could not find a needed root item");
return;
}
Item cropfieldItem;
if (input.CreateNewCropfield == true) // || string.IsNullOrEmpty(_settings.CropfieldItemCode) ## CHECK IT!!
{
_logger.LogInformation("Creating cropfield");
2020-12-18 09:22:23 +00:00
cropfieldItem = await _generalService.CreateCropfieldItemAsync(myDrive.Code, input.CropFieldName, input.CropYear,
input.GeometryJson.ToString(Formatting.None));
_settings.CropfieldName = cropfieldItem.Name;
_settings.CropfieldItemCode = cropfieldItem.Code;
2021-01-28 14:08:32 +00:00
SaveSettings(settingsfile);
}
else
{
_logger.LogInformation("Cropfield already exists trying to get");
cropfieldItem = await _farmmapsApiService.GetItemAsync(_settings.CropfieldItemCode);
}
2021-01-28 14:08:32 +00:00
if (GetWatBal==true) {
////Run watbal
//if (useCreatedCropfield == false || string.IsNullOrEmpty(_settings.WatBalTaskCode)) {
// var WatBalTaskCode = await _generalService.RunWatBalTask(cropfieldItem);
// _settings.WatBalTaskCode = WatBalTaskCode;
// SaveSettings(settingsfile);
//}
//// Get watbal data
//Item WatBalItem = await _generalService.FindWatBalItem(cropfieldItem, _settings.WatBalTaskCode, FieldName, StoreStatistics);
}
if (getVanDerSat==true) {
// check if vandersat task not yet done, do here and save taskcode
if (useCreatedCropfield == false || string.IsNullOrEmpty(_settings.VanDerSatTaskCode)) {
var VanDerSatTaskCode = await _generalService.RunVanDerSatTask(cropfieldItem);
_settings.VanDerSatTaskCode = VanDerSatTaskCode;
SaveSettings(settingsfile);
}
// Select a particular image item from VanDerSat
Item VanDerSatItem = await _generalService.FindVanDerSatItem(cropfieldItem, _settings.VanDerSatTaskCode, FieldName, StoreVanDerSatStatistics);
// download the geotiff
_logger.LogInformation("Downloading geotiff file");
await _farmmapsApiService.DownloadItemAsync(VanDerSatItem.Code,
Path.Combine(DownloadFolder, $"nbs_VanDerSatGeotiff_{input.OutputFileName}.zip"));
}
var inputOneItem = await _generalService.UploadDataAsync(uploadedRoot, GEOTIFF_PROCESSED_ITEMTYPE,
Path.Combine("Data", $"{input.InputItemOne}"), Path.GetFileNameWithoutExtension($"{input.InputItemOne}"));
if (inputOneItem == null)
{
_logger.LogError("Could not find item for uploaded data");
return;
}
2021-01-28 14:08:32 +00:00
//var inputTwoItem = await _generalService.UploadDataAsync(uploadedRoot, GEOTIFF_PROCESSED_ITEMTYPE,
// Path.Combine("Data", $"{input.InputItemTwo}"), Path.GetFileNameWithoutExtension($"{input.InputItemTwo}"));
2021-03-01 14:56:15 +00:00
//if (inputTwoItem == null) {
// _logger.LogError("Could not find item for uploaded data");
// return;
//}
2020-12-18 09:22:23 +00:00
var outputItem = await _zoneringService.CreateApplicationMapAsync(cropfieldItem, input.Formula, new Output()
{
2021-03-01 13:04:18 +00:00
Name = input.CalculatedLayerName,
2020-12-18 09:22:23 +00:00
Quantity = input.CalculatedQuantity,
Unit = input.CalculatedUnit,
}, new InputParameter()
{
ItemCode = inputOneItem.Code,
LayerName = inputOneItem.Data["layers"][0]["name"].ToString()
2021-03-01 14:56:15 +00:00
//},
//new InputParameter()
//{
2021-03-01 14:56:15 +00:00
// ItemCode = inputTwoItem.Code,
// LayerName = inputTwoItem.Data["layers"][0]["name"].ToString()
});
2021-03-01 13:04:18 +00:00
_logger.LogInformation("Downloading output");
_logger.LogInformation($"outputitem: {outputItem} with code {outputItem.Code} and date {outputItem.DataDate}");
await _farmmapsApiService.DownloadItemAsync(outputItem.Code,
2021-03-01 13:04:18 +00:00
Path.Combine(DownloadFolder, $"{input.OutputFileName}.zoning.zip"));
}
2021-01-28 14:08:32 +00:00
// Functions to save previously created cropfields
private void LoadSettings(string file) {
if (File.Exists(file)) {
var jsonText = File.ReadAllText(file);
_settings = JsonConvert.DeserializeObject<Settings>(jsonText);
2021-01-28 14:08:32 +00:00
} else {
_settings = new Settings();
}
}
2021-01-28 14:08:32 +00:00
private void SaveSettings(string file) {
if (_settings == null)
return;
var json = JsonConvert.SerializeObject(_settings);
2021-01-28 14:08:32 +00:00
File.WriteAllText(file, json);
}
private void SaveInfo(string file) {
if (_settings == null)
return;
var json = JsonConvert.SerializeObject(_settings);
File.WriteAllText(file, json);
}
}
}