Merge remote-tracking branch 'fedde/master'

This commit is contained in:
Mark van der Wal 2020-09-14 08:51:12 +02:00
commit 67af431140
20 changed files with 864 additions and 28 deletions

View File

@ -0,0 +1,111 @@
using FarmmapsApi;
using FarmmapsApi.Models;
using FarmmapsApi.Services;
using FarmMapsBlight.Models;
using Microsoft.Extensions.Logging;
using Newtonsoft.Json;
using System;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
namespace FarmMapsBlight
{
public class BlightApplication : IApplication
{
private const string DownloadFolder = "Downloads";
private const string SettingsFile = "settings.json";
private readonly ILogger<BlightApplication> _logger;
private readonly FarmmapsApiService _farmmapsApiService;
private readonly BlightService _blightService;
private readonly GeneralService _generalService;
private Settings _settings;
public BlightApplication(ILogger<BlightApplication> logger, FarmmapsApiService farmmapsApiService,
GeneralService generalService, BlightService haulmkillingService)
{
_logger = logger;
_farmmapsApiService = farmmapsApiService;
_generalService = generalService;
_blightService = haulmkillingService;
}
public async Task RunAsync()
{
if (!Directory.Exists(DownloadFolder))
Directory.CreateDirectory(DownloadFolder);
LoadSettings();
// !! 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();
var myDrive = roots.SingleOrDefault(r => r.Name == "My drive");
if (myDrive == null)
{
_logger.LogError("Could not find a needed root item");
return;
}
var uploadedRoot = roots.SingleOrDefault(r => r.Name == "Uploaded");
if (uploadedRoot == null)
{
_logger.LogError("Could not find a needed root item");
return;
}
Item cropfieldItem;
if (string.IsNullOrEmpty(_settings.CropfieldItemCode))
{
_logger.LogInformation("Creating cropfield");
cropfieldItem = await _generalService.CreateCropfieldItemAsync(myDrive.Code, "Cropfield Blight", 2020,
@"{""type"":""Polygon"",""coordinates"":[[[4.617786844284247,52.22533706956424],[4.618642601314543,52.225938364585989],[4.6192153806397,52.22563988897754],[4.619192414656403,52.2256242822442],[4.620306732153958,52.225031745661528],[4.620542019225217,52.22519855319158],[4.621157509147853,52.22487436515405],[4.623387917230182,52.22367660757213],[4.624563444939009,52.22304740241544],[4.624562779355982,52.223046635247019],[4.624534908813479,52.22302596787506],[4.627873021330343,52.221240670658399],[4.627504935938338,52.220104419135129],[4.627324878706837,52.22020569669098],[4.627320696113512,52.22020660117888],[4.626707169518044,52.22053923770041],[4.624700376420229,52.221619047547488],[4.623471571183885,52.22227447969577],[4.623471511010673,52.22227500174403],[4.623468838689317,52.22228052566992],[4.617786844284247,52.22533706956424]]]}");
_settings.CropfieldItemCode = cropfieldItem.Code;
SaveSettings();
}
else
{
_logger.LogInformation("Cropfield already exists trying to get");
cropfieldItem = await _farmmapsApiService.GetItemAsync(_settings.CropfieldItemCode);
}
DateTime plantingDate = new DateTime(2020, 3, 20);
DateTime emergeDate = new DateTime(2020, 5, 20);
var blightItem = await _blightService.CreateAdvice(cropfieldItem, plantingDate, emergeDate);
if (blightItem == null)
{
return;
}
// advice as json
var data = blightItem.Data;
}
private void LoadSettings()
{
if (File.Exists(SettingsFile))
{
var jsonText = File.ReadAllText(SettingsFile);
_settings = JsonConvert.DeserializeObject<Settings>(jsonText);
}
else
{
_settings = new Settings();
}
}
private void SaveSettings()
{
if (_settings == null)
return;
var json = JsonConvert.SerializeObject(_settings);
File.WriteAllText(SettingsFile, json);
}
}
}

View File

@ -0,0 +1,67 @@
using FarmmapsApi.Models;
using FarmmapsApi.Services;
using Microsoft.Extensions.Logging;
using System;
using System.Threading.Tasks;
using static FarmmapsApi.Extensions;
using static FarmmapsApiSamples.Constants;
namespace FarmMapsBlight
{
public class BlightService
{
private readonly ILogger<BlightService> _logger;
private readonly FarmmapsApiService _farmmapsApiService;
private readonly GeneralService _generalService;
public BlightService(ILogger<BlightService> logger, FarmmapsApiService farmmapsApiService,
GeneralService generalService)
{
_logger = logger;
_farmmapsApiService = farmmapsApiService;
_generalService = generalService;
}
public async Task<Item> CreateAdvice(Item cropfieldItem, DateTime plantingDate, DateTime emergeDate)
{
var taskRequest = new TaskRequest()
{
TaskType = "vnd.farmmaps.task.blight"
};
taskRequest.attributes["plantingDate"] = plantingDate.ToUniversalTime().ToString("o");
taskRequest.attributes["emergeDate"] = emergeDate.ToUniversalTime().ToString("o");
var taskCode = await _farmmapsApiService.QueueTaskAsync(cropfieldItem.Code, taskRequest);
await PollTask(TimeSpan.FromSeconds(3), async (tokenSource) =>
{
_logger.LogInformation("Checking blight task status");
var itemTaskStatus = await _farmmapsApiService.GetTaskStatusAsync(cropfieldItem.Code, taskCode);
if (itemTaskStatus.IsFinished)
tokenSource.Cancel();
});
var itemTask = await _farmmapsApiService.GetTaskStatusAsync(cropfieldItem.Code, taskCode);
if (itemTask.State == ItemTaskState.Error)
{
_logger.LogError($"Something went wrong with task execution: {itemTask.Message}");
return null;
}
var itemName = $"Blight";
var blightAdviceItem = await _generalService.FindChildItemAsync(cropfieldItem.Code,
BLIGHT_ITEMTYPE, itemName);
// incorrect filter task is finished after updating
// i => i.Updated >= itemTask.Finished && i.Name.ToLower().Contains(itemName.ToLower())
if (blightAdviceItem == null)
{
_logger.LogError("Could not find the blight item under cropfield");
return null;
}
return blightAdviceItem;
}
}
}

View File

@ -0,0 +1,18 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFramework>netcoreapp3.1</TargetFramework>
</PropertyGroup>
<ItemGroup>
<ProjectReference Include="..\FarmmapsApi\FarmmapsApi.csproj" />
</ItemGroup>
<ItemGroup>
<None Update="appsettings.json">
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
</None>
</ItemGroup>
</Project>

View File

@ -0,0 +1,7 @@
namespace FarmMapsBlight.Models
{
public class Settings
{
public string CropfieldItemCode { get; set; }
}
}

23
FarmMapsBlight/Program.cs Normal file
View File

@ -0,0 +1,23 @@
using FarmmapsApi;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using System.Threading.Tasks;
namespace FarmMapsBlight
{
public class Program : FarmmapsProgram<BlightApplication>
{
private static async Task Main(string[] args)
{
await new Program().Start(args);
}
protected override void Configure(IServiceCollection serviceCollection)
{
serviceCollection.AddLogging(opts => opts
.AddConsole()
.AddFilter("System.Net.Http", LogLevel.Warning))
.AddTransient<BlightService>();
}
}
}

View File

@ -0,0 +1,12 @@
{
"Authority": "https://accounts.farmmaps.awtest.nl/",
//"Endpoint": "http://farmmaps.awtest.nl",
//"Endpoint": "http://localhost:8095",
"Endpoint": "http://localhost:8083",
"BasePath": "api/v1",
"DiscoveryEndpointUrl": "https://accounts.farmmaps.awtest.nl/.well-known/openid-configuration",
"RedirectUri": "http://example.nl/api",
"ClientId": "",
"ClientSecret": "",
"Scopes": [ "api" ]
}

View File

@ -10,10 +10,17 @@ namespace FarmmapsApiSamples
public const string SHAPE_PROCESSED_ITEMTYPE = "vnd.farmmaps.itemtype.shape.processed"; public const string SHAPE_PROCESSED_ITEMTYPE = "vnd.farmmaps.itemtype.shape.processed";
public const string SHAPE_ITEMTYPE = "vnd.farmmaps.itemtype.shape"; public const string SHAPE_ITEMTYPE = "vnd.farmmaps.itemtype.shape";
public const string GEOJSON_ITEMTYPE = "vnd.farmmaps.itemtype.geojson"; public const string GEOJSON_ITEMTYPE = "vnd.farmmaps.itemtype.geojson";
public const string BLIGHT_ITEMTYPE = "vnd.farmmaps.itemtype.blight";
public const string VRANBS_TASK = "vnd.farmmaps.task.vranbs"; public const string VRANBS_TASK = "vnd.farmmaps.task.vranbs";
public const string VRAHERBICIDE_TASK = "vnd.farmmaps.task.vraherbicide"; public const string VRAHERBICIDE_TASK = "vnd.farmmaps.task.vraherbicide";
public const string VRAHAULMKILLING_TASK = "vnd.farmmaps.task.vrahaulmkilling"; public const string VRAHAULMKILLING_TASK = "vnd.farmmaps.task.vrahaulmkilling";
public const string VRAPLANTING_TASK = "vnd.farmmaps.task.vrapoten";
public const string SATELLITE_TASK = "vnd.farmmaps.task.satellite"; public const string SATELLITE_TASK = "vnd.farmmaps.task.satellite";
public const string TASKMAP_TASK = "vnd.farmmaps.task.taskmap";
public const string WORKFLOW_TASK = "vnd.farmmaps.task.workflow";
public const string BOFEK_TASK = "vnd.farmmaps.task.bofek";
public const string SHADOW_TASK = "vnd.farmmaps.task.shadow";
public const string AHN_TASK = "vnd.farmmaps.task.ahn";
} }
} }

View File

@ -23,7 +23,8 @@ namespace FarmmapsApi.Services
_farmmapsApiService = farmmapsApiService; _farmmapsApiService = farmmapsApiService;
} }
public async Task<Item> CreateCropfieldItemAsync(string parentItemCode, string name, int year, string fieldGeomJson) public async Task<Item> CreateCropfieldItemAsync(string parentItemCode, string name, int year,
string fieldGeomJson)
{ {
var currentYear = new DateTime(year, 1, 1); var currentYear = new DateTime(year, 1, 1);
var cropfieldItemRequest = new ItemRequest() var cropfieldItemRequest = new ItemRequest()
@ -81,7 +82,7 @@ namespace FarmmapsApi.Services
if (items.Any()) if (items.Any())
{ {
shapeItem = items.First(i => i.Name.Contains(itemName)); shapeItem = items.First(i => i.Name.Contains(itemName));
if(shapeItem != null) if (shapeItem != null)
{ {
source.Cancel(); source.Cancel();
break; break;
@ -102,6 +103,42 @@ namespace FarmmapsApi.Services
return await _farmmapsApiService.GetItemAsync(shapeItem.ParentCode); return await _farmmapsApiService.GetItemAsync(shapeItem.ParentCode);
} }
public async Task<Item> GeotiffToShape(Item tiffItem)
{
var taskmapRequest = new TaskRequest {TaskType = TASKMAP_TASK};
string itemTaskCode = await _farmmapsApiService.QueueTaskAsync(tiffItem.Code, taskmapRequest);
await PollTask(TimeSpan.FromSeconds(5), async (tokenSource) =>
{
var itemTaskStatus = await _farmmapsApiService.GetTaskStatusAsync(tiffItem.Code, itemTaskCode);
_logger.LogInformation($"Waiting on converting geotiff to shape; status: {itemTaskStatus.State}");
if (itemTaskStatus.IsFinished)
tokenSource.Cancel();
});
var itemTask = await _farmmapsApiService.GetTaskStatusAsync(tiffItem.Code, itemTaskCode);
if (itemTask.State == ItemTaskState.Error)
{
_logger.LogError($"Something went wrong with task execution: {itemTask.Message}");
return null;
}
//the taskmap is a child of the input tiff
var itemName = "Taskmap";
var taskMapItem = await FindChildItemAsync(tiffItem.Code,
SHAPE_PROCESSED_ITEMTYPE, itemName);
if (taskMapItem == null)
{
_logger.LogError("Could not find the shape taskmap as a child item under the input");
return null;
}
return taskMapItem;
}
public async Task<ItemTaskStatus> RunAndWaitForTask(Item subjectItem, string taskIdentifier, public async Task<ItemTaskStatus> RunAndWaitForTask(Item subjectItem, string taskIdentifier,
Action<TaskRequest> configureCallback = null, int retrySeconds = 3) Action<TaskRequest> configureCallback = null, int retrySeconds = 3)
{ {
@ -158,5 +195,107 @@ namespace FarmmapsApi.Services
_logger.LogInformation($"Found {containsName} item"); _logger.LogInformation($"Found {containsName} item");
return dataItem; return dataItem;
} }
public async Task<Item> RunBofekTask(Item cropfieldItem)
{
var taskmapRequest = new TaskRequest {TaskType = BOFEK_TASK};
string itemTaskCode = await _farmmapsApiService.QueueTaskAsync(cropfieldItem.Code, taskmapRequest);
await PollTask(TimeSpan.FromSeconds(5), async (tokenSource) =>
{
var itemTaskStatus = await _farmmapsApiService.GetTaskStatusAsync(cropfieldItem.Code, itemTaskCode);
_logger.LogInformation($"Waiting on retreiving BOFEK data; status: {itemTaskStatus.State}");
if (itemTaskStatus.IsFinished)
tokenSource.Cancel();
});
var itemTask = await _farmmapsApiService.GetTaskStatusAsync(cropfieldItem.Code, itemTaskCode);
if (itemTask.State == ItemTaskState.Error)
{
_logger.LogError($"Something went wrong with task execution: {itemTask.Message}");
return null;
}
//the BOFEK data is a child of the cropfield
var itemName = "bofek";
var bofekItem = await FindChildItemAsync(cropfieldItem.Code,
SHAPE_PROCESSED_ITEMTYPE, itemName);
if (bofekItem == null)
{
_logger.LogError("Could not find the BOFEK data as a child item under the cropfield");
return null;
}
return bofekItem;
}
public async Task<Item> RunAhnTask(Item cropfieldItem)
{
var taskmapRequest = new TaskRequest {TaskType = AHN_TASK};
string itemTaskCode = await _farmmapsApiService.QueueTaskAsync(cropfieldItem.Code, taskmapRequest);
await PollTask(TimeSpan.FromSeconds(5), async (tokenSource) =>
{
var itemTaskStatus = await _farmmapsApiService.GetTaskStatusAsync(cropfieldItem.Code, itemTaskCode);
_logger.LogInformation($"Waiting on retreiving AHN data; status: {itemTaskStatus.State}");
if (itemTaskStatus.IsFinished)
tokenSource.Cancel();
});
var itemTask = await _farmmapsApiService.GetTaskStatusAsync(cropfieldItem.Code, itemTaskCode);
if (itemTask.State == ItemTaskState.Error)
{
_logger.LogError($"Something went wrong with task execution: {itemTask.Message}");
return null;
}
//the AHN data is a child of the cropfield
var itemName = "ahn";
var ahnItem = await FindChildItemAsync(cropfieldItem.Code,
GEOTIFF_PROCESSED_ITEMTYPE, itemName);
if (ahnItem == null)
{
_logger.LogError("Could not find the AHN data as a child item under the cropfield");
return null;
}
return ahnItem;
}
public async Task<Item> RunShadowTask(Item cropfieldItem)
{
var taskmapRequest = new TaskRequest {TaskType = SHADOW_TASK};
string itemTaskCode = await _farmmapsApiService.QueueTaskAsync(cropfieldItem.Code, taskmapRequest);
await PollTask(TimeSpan.FromSeconds(5), async (tokenSource) =>
{
var itemTaskStatus = await _farmmapsApiService.GetTaskStatusAsync(cropfieldItem.Code, itemTaskCode);
_logger.LogInformation($"Waiting on calculation shadow data; status: {itemTaskStatus.State}");
if (itemTaskStatus.IsFinished)
tokenSource.Cancel();
});
var itemTask = await _farmmapsApiService.GetTaskStatusAsync(cropfieldItem.Code, itemTaskCode);
if (itemTask.State == ItemTaskState.Error)
{
_logger.LogError($"Something went wrong with task execution: {itemTask.Message}");
return null;
}
//the shadow data is a child of the cropfield
var itemName = "shadow";
var shadowItem = await FindChildItemAsync(cropfieldItem.Code,
GEOTIFF_PROCESSED_ITEMTYPE, itemName);
if (shadowItem == null)
{
_logger.LogError("Could not find the shadow data as a child item under the cropfield");
return null;
}
return shadowItem;
}
} }
} }

View File

@ -1,19 +1,25 @@
 
Microsoft Visual Studio Solution File, Format Version 12.00 Microsoft Visual Studio Solution File, Format Version 12.00
# # Visual Studio Version 16
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "FarmmapsNbs", "FarmmapsNbs\FarmmapsNbs.csproj", "{E08EF7E9-F09E-42D8-825C-164E458C78F4}" VisualStudioVersion = 16.0.30320.27
MinimumVisualStudioVersion = 10.0.40219.1
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "FarmmapsNbs", "FarmmapsNbs\FarmmapsNbs.csproj", "{E08EF7E9-F09E-42D8-825C-164E458C78F4}"
EndProject EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "FarmmapsApi", "FarmmapsApi\FarmmapsApi.csproj", "{1FA9E50B-F45E-4534-953A-37C783D03C74}" Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "FarmmapsApi", "FarmmapsApi\FarmmapsApi.csproj", "{1FA9E50B-F45E-4534-953A-37C783D03C74}"
EndProject EndProject
Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "General", "General", "{6FA66E07-A59E-480E-B5D1-DBEFC4E4583D}" Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "General", "General", "{6FA66E07-A59E-480E-B5D1-DBEFC4E4583D}"
ProjectSection(SolutionItems) = preProject ProjectSection(SolutionItems) = preProject
README.MD = README.MD
.gitignore = .gitignore .gitignore = .gitignore
README.MD = README.MD
EndProjectSection EndProjectSection
EndProject EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "FarmmapsHerbicide", "FarmmapsHerbicide\FarmmapsHerbicide.csproj", "{731A88CD-9DC4-4969-86F2-2315830A6998}" Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "FarmmapsHerbicide", "FarmmapsHerbicide\FarmmapsHerbicide.csproj", "{731A88CD-9DC4-4969-86F2-2315830A6998}"
EndProject EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "FarmmapsHaulmkilling", "FarmmapsHaulmkilling\FarmmapsHaulmkilling.csproj", "{DFA89D0B-5400-4374-B824-8367B76B4B6E}" Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "FarmmapsHaulmkilling", "FarmmapsHaulmkilling\FarmmapsHaulmkilling.csproj", "{DFA89D0B-5400-4374-B824-8367B76B4B6E}"
EndProject
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "FarmmapsPoten", "FarmmapsPoten\FarmmapsPoten.csproj", "{AAFAB03A-6F5C-4D91-991F-867B7898F981}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "FarmMapsBlight", "FarmMapsBlight\FarmMapsBlight.csproj", "{892E0932-5D11-4A37-979E-CEDB39C2E181}"
EndProject EndProject
Global Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution GlobalSection(SolutionConfigurationPlatforms) = preSolution
@ -37,5 +43,19 @@ Global
{DFA89D0B-5400-4374-B824-8367B76B4B6E}.Debug|Any CPU.Build.0 = Debug|Any CPU {DFA89D0B-5400-4374-B824-8367B76B4B6E}.Debug|Any CPU.Build.0 = Debug|Any CPU
{DFA89D0B-5400-4374-B824-8367B76B4B6E}.Release|Any CPU.ActiveCfg = Release|Any CPU {DFA89D0B-5400-4374-B824-8367B76B4B6E}.Release|Any CPU.ActiveCfg = Release|Any CPU
{DFA89D0B-5400-4374-B824-8367B76B4B6E}.Release|Any CPU.Build.0 = Release|Any CPU {DFA89D0B-5400-4374-B824-8367B76B4B6E}.Release|Any CPU.Build.0 = Release|Any CPU
{AAFAB03A-6F5C-4D91-991F-867B7898F981}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{AAFAB03A-6F5C-4D91-991F-867B7898F981}.Debug|Any CPU.Build.0 = Debug|Any CPU
{AAFAB03A-6F5C-4D91-991F-867B7898F981}.Release|Any CPU.ActiveCfg = Release|Any CPU
{AAFAB03A-6F5C-4D91-991F-867B7898F981}.Release|Any CPU.Build.0 = Release|Any CPU
{892E0932-5D11-4A37-979E-CEDB39C2E181}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{892E0932-5D11-4A37-979E-CEDB39C2E181}.Debug|Any CPU.Build.0 = Debug|Any CPU
{892E0932-5D11-4A37-979E-CEDB39C2E181}.Release|Any CPU.ActiveCfg = Release|Any CPU
{892E0932-5D11-4A37-979E-CEDB39C2E181}.Release|Any CPU.Build.0 = Release|Any CPU
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE
EndGlobalSection
GlobalSection(ExtensibilityGlobals) = postSolution
SolutionGuid = {88AA58C4-40E6-4FC6-B501-6557C7E9DA81}
EndGlobalSection EndGlobalSection
EndGlobal EndGlobal

View File

@ -0,0 +1,10 @@
<?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="Current" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<PropertyGroup>
<ShowAllFiles>false</ShowAllFiles>
<ActiveDebugProfile>FarmmapsNbs</ActiveDebugProfile>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|AnyCPU'">
<DebuggerFlavor>ProjectDebugger</DebuggerFlavor>
</PropertyGroup>
</Project>

View File

@ -34,6 +34,7 @@ namespace FarmmapsNbs
public async Task RunAsync() public async Task RunAsync()
{ {
var nitrogenInputJson = File.ReadAllText("NitrogenInput.json"); var nitrogenInputJson = File.ReadAllText("NitrogenInput.json");
//var nitrogenInputJson = File.ReadAllText("fivefieldsinput.json");
List<NitrogenInput> nitrogenInputs = JsonConvert.DeserializeObject<List<NitrogenInput>>(nitrogenInputJson); List<NitrogenInput> nitrogenInputs = JsonConvert.DeserializeObject<List<NitrogenInput>>(nitrogenInputJson);
if (!Directory.Exists(DownloadFolder)) if (!Directory.Exists(DownloadFolder))
@ -75,6 +76,7 @@ namespace FarmmapsNbs
return; return;
} }
var cropfieldItem = await _generalService.CreateCropfieldItemAsync(myDriveRoot.Code, var cropfieldItem = await _generalService.CreateCropfieldItemAsync(myDriveRoot.Code,
$"VRA NBS cropfield {input.OutputFileName}", plantingDate.Year, input.GeometryJson.ToString(Formatting.None)); $"VRA NBS cropfield {input.OutputFileName}", plantingDate.Year, input.GeometryJson.ToString(Formatting.None));
@ -98,6 +100,11 @@ namespace FarmmapsNbs
return; return;
} }
_logger.LogInformation("Downloading geotiff file");
await _farmmapsApiService.DownloadItemAsync(geotiffItem.Code,
Path.Combine(DownloadFolder, $"{input.OutputFileName}.input_geotiff.zip"));
_logger.LogInformation($"Calculating targetN with targetYield: {input.TargetYield}"); _logger.LogInformation($"Calculating targetN with targetYield: {input.TargetYield}");
var targetNItem = await _nitrogenService.CreateTargetNItem(cropfieldItem); var targetNItem = await _nitrogenService.CreateTargetNItem(cropfieldItem);
var targetNData = await _nitrogenService.CalculateTargetN(cropfieldItem, targetNItem, plantingDate, var targetNData = await _nitrogenService.CalculateTargetN(cropfieldItem, targetNItem, plantingDate,
@ -127,6 +134,7 @@ namespace FarmmapsNbs
_logger.LogInformation("Downloading uptake map"); _logger.LogInformation("Downloading uptake map");
await _farmmapsApiService.DownloadItemAsync(uptakeMapItem.Code, await _farmmapsApiService.DownloadItemAsync(uptakeMapItem.Code,
Path.Combine(DownloadFolder, $"{input.OutputFileName}.uptake.zip")); Path.Combine(DownloadFolder, $"{input.OutputFileName}.uptake.zip"));
_logger.LogInformation("UptakeMap downloaded to {0}", Path.Combine(DownloadFolder, $"{input.OutputFileName}.uptake.zip"));
_logger.LogInformation("Calculating application map"); _logger.LogInformation("Calculating application map");
var applicationMapItem = var applicationMapItem =
@ -142,6 +150,29 @@ namespace FarmmapsNbs
_logger.LogInformation("Downloading application map"); _logger.LogInformation("Downloading application map");
await _farmmapsApiService.DownloadItemAsync(applicationMapItem.Code, await _farmmapsApiService.DownloadItemAsync(applicationMapItem.Code,
Path.Combine(DownloadFolder, $"{input.OutputFileName}.application.zip")); Path.Combine(DownloadFolder, $"{input.OutputFileName}.application.zip"));
_logger.LogInformation("Application map can be found in {0}", Path.Combine(DownloadFolder, $"{input.OutputFileName}.application.zip"));
//transforming tiff to shape
var tiffItem = applicationMapItem;
if (tiffItem == null)
{
_logger.LogError("Could not find item for uploaded data");
return;
}
_logger.LogInformation($"Converting geotiff to shape");
var taskmap = await _generalService.GeotiffToShape(tiffItem);
if (taskmap == null)
{
_logger.LogError("Something went wrong with geotiff to shape transformation");
return;
}
_logger.LogInformation("Downloading taskmap");
await _farmmapsApiService.DownloadItemAsync(taskmap.Code,
Path.Combine(DownloadFolder, $"{input.OutputFileName}.taskmap.zip"));
} }
} }
} }

View File

@ -51,8 +51,8 @@ namespace FarmmapsNbs
var nbsTargetNRequest = new TaskRequest {TaskType = VRANBS_TASK}; var nbsTargetNRequest = new TaskRequest {TaskType = VRANBS_TASK};
nbsTargetNRequest.attributes["operation"] = "targetn"; nbsTargetNRequest.attributes["operation"] = "targetn";
nbsTargetNRequest.attributes["inputCode"] = targetNItem.Code; nbsTargetNRequest.attributes["inputCode"] = targetNItem.Code;
nbsTargetNRequest.attributes["plantingDate"] = plantingDate.ToString(); nbsTargetNRequest.attributes["plantingDate"] = plantingDate.ToString("o");
nbsTargetNRequest.attributes["measurementDate"] = measurementDate.ToString(); nbsTargetNRequest.attributes["measurementDate"] = measurementDate.ToString("o");
nbsTargetNRequest.attributes["purposeType"] = purposeType.ToLower(); nbsTargetNRequest.attributes["purposeType"] = purposeType.ToLower();
nbsTargetNRequest.attributes["targetYield"] = targetYield.ToString(); nbsTargetNRequest.attributes["targetYield"] = targetYield.ToString();
string itemTaskCode = await _farmmapsApiService.QueueTaskAsync(cropfieldItem.Code, nbsTargetNRequest); string itemTaskCode = await _farmmapsApiService.QueueTaskAsync(cropfieldItem.Code, nbsTargetNRequest);
@ -89,9 +89,14 @@ namespace FarmmapsNbs
var nbsUptakeMapRequest = new TaskRequest {TaskType = VRANBS_TASK}; var nbsUptakeMapRequest = new TaskRequest {TaskType = VRANBS_TASK};
nbsUptakeMapRequest.attributes["operation"] = "uptake"; nbsUptakeMapRequest.attributes["operation"] = "uptake";
nbsUptakeMapRequest.attributes["inputCode"] = inputItem.Code; nbsUptakeMapRequest.attributes["inputCode"] = inputItem.Code;
nbsUptakeMapRequest.attributes["plantingDate"] = plantingDate.ToString(); nbsUptakeMapRequest.attributes["plantingDate"] = plantingDate.ToString("o");
nbsUptakeMapRequest.attributes["measurementDate"] = measurementDate.ToString(); nbsUptakeMapRequest.attributes["measurementDate"] = measurementDate.ToString("o");
nbsUptakeMapRequest.attributes["inputType"] = inputType.ToLower(); nbsUptakeMapRequest.attributes["inputType"] = inputType.ToLower();
nbsUptakeMapRequest.attributes["inputLayerName"] = "IRMI"; //toevoeging FS. Kolom IRMI hernoemd als IMI. Deze wordt niet automatisch herkend. En moet dus gespecificeerd worden.
var layers = inputItem.Data["layers"]; //toevoeging FS, check welke data lagen worden omgezet
_logger.LogInformation($"DataLayers: {layers}"); //toevoeging FS check welke data lagen worden omgezet
string itemTaskCode = await _farmmapsApiService.QueueTaskAsync(cropfieldItem.Code, nbsUptakeMapRequest); string itemTaskCode = await _farmmapsApiService.QueueTaskAsync(cropfieldItem.Code, nbsUptakeMapRequest);
@ -140,8 +145,8 @@ namespace FarmmapsNbs
var nbsApplicationMapRequest = new TaskRequest {TaskType = VRANBS_TASK}; var nbsApplicationMapRequest = new TaskRequest {TaskType = VRANBS_TASK};
nbsApplicationMapRequest.attributes["operation"] = "application"; nbsApplicationMapRequest.attributes["operation"] = "application";
nbsApplicationMapRequest.attributes["inputCode"] = inputItem.Code; nbsApplicationMapRequest.attributes["inputCode"] = inputItem.Code;
nbsApplicationMapRequest.attributes["plantingDate"] = plantingDate.ToString(); nbsApplicationMapRequest.attributes["plantingDate"] = plantingDate.ToString("o");
nbsApplicationMapRequest.attributes["measurementDate"] = measurementDate.ToString(); nbsApplicationMapRequest.attributes["measurementDate"] = measurementDate.ToString("o");
nbsApplicationMapRequest.attributes["inputCode"] = inputItem.Code; nbsApplicationMapRequest.attributes["inputCode"] = inputItem.Code;
nbsApplicationMapRequest.attributes["inputType"] = inputType.ToLower(); nbsApplicationMapRequest.attributes["inputType"] = inputType.ToLower();
nbsApplicationMapRequest.attributes["targetN"] = targetN.ToString(CultureInfo.InvariantCulture); nbsApplicationMapRequest.attributes["targetN"] = targetN.ToString(CultureInfo.InvariantCulture);
@ -151,10 +156,13 @@ namespace FarmmapsNbs
await PollTask(TimeSpan.FromSeconds(5), async (tokenSource) => await PollTask(TimeSpan.FromSeconds(5), async (tokenSource) =>
{ {
var itemTaskStatus = await _farmmapsApiService.GetTaskStatusAsync(cropfieldItem.Code, itemTaskCode); var itemTaskStatus = await _farmmapsApiService.GetTaskStatusAsync(cropfieldItem.Code, itemTaskCode);
if (itemTaskStatus.IsFinished) if (itemTaskStatus.IsFinished)
tokenSource.Cancel(); tokenSource.Cancel();
}); });
var itemTask = await _farmmapsApiService.GetTaskStatusAsync(cropfieldItem.Code, itemTaskCode); var itemTask = await _farmmapsApiService.GetTaskStatusAsync(cropfieldItem.Code, itemTaskCode);
if(itemTask.State == ItemTaskState.Error) if(itemTask.State == ItemTaskState.Error)
{ {

Binary file not shown.

View File

@ -0,0 +1,21 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFramework>netcoreapp3.1</TargetFramework>
</PropertyGroup>
<ItemGroup>
<None Update="appsettings.json">
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
</None>
<None Update="Data\**\*">
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
</None>
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\FarmmapsApi\FarmmapsApi.csproj" />
</ItemGroup>
</Project>

View File

@ -0,0 +1,18 @@
using System;
using Newtonsoft.Json.Linq;
namespace FarmmapsPoten.Models
{
public class PotenInput
{
public bool UseShadow { get; set; }
public string File { get; set; }
public string OutputFileName { get; set; }
public string FieldName { get; set; }
public int PlantingYear { get; set; }
public string MeanDensity { get; set; }
public string Variation { get; set; }
public JObject GeometryJson { get; set; }
}
}

View File

@ -0,0 +1,196 @@
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 FarmmapsPoten.Models;
using Microsoft.Extensions.Logging;
using Newtonsoft.Json;
using static FarmmapsApiSamples.Constants;
namespace FarmmapsVRApoten
{
public class PotenApplication : IApplication
{
private const string DownloadFolder = "Downloads";
private readonly ILogger<PotenApplication> _logger;
private readonly FarmmapsApiService _farmmapsApiService;
private readonly PotenService _potenService;
private readonly GeneralService _generalService;
public PotenApplication(ILogger<PotenApplication> logger, FarmmapsApiService farmmapsApiService,
GeneralService generalService, PotenService potenService)
{
_logger = logger;
_farmmapsApiService = farmmapsApiService;
_generalService = generalService;
_potenService = potenService;
}
public async Task RunAsync()
{
// read field data from separate json file
var VRAPotenInputJson = File.ReadAllText("PotenInput.json");
List<PotenInput> potenInputs = JsonConvert.DeserializeObject<List<PotenInput>>(VRAPotenInputJson);
if (!Directory.Exists(DownloadFolder))
Directory.CreateDirectory(DownloadFolder);
// !! 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();
foreach (var input in potenInputs)
{
try
{
await Process(roots, input);
}
catch (Exception ex)
{
_logger.LogError(ex.Message);
}
}
}
private async Task Process(List<UserRoot> roots, PotenInput input)
{
var meanDensity = input.MeanDensity;
var variation = input.Variation;
var fieldName = input.FieldName;
bool useShadow = input.UseShadow;
var myDrive = roots.SingleOrDefault(r => r.Name == "My drive");
if (myDrive == null)
{
_logger.LogError("Could not find a needed root item");
return;
}
var uploadedRoot = roots.SingleOrDefault(r => r.Name == "Uploaded");
if (uploadedRoot == null)
{
_logger.LogError("Could not find a needed root item");
return;
}
_logger.LogInformation("Creating cropfield");
var cropfieldItem = await _generalService.CreateCropfieldItemAsync(myDrive.Code,
$"VRA Poten cropfield {input.OutputFileName}", input.PlantingYear,
input.GeometryJson.ToString(Formatting.None));
//Calculating shadow map
if (useShadow)
{
_logger.LogInformation("Calculate shadow map for field");
var shadowItem = await _generalService.RunShadowTask(cropfieldItem);
if (shadowItem == null)
{
_logger.LogError("Something went wrong while obtaining the shadow map");
return;
}
_logger.LogInformation("Downloading shadow map");
await _farmmapsApiService.DownloadItemAsync(shadowItem.Code,
Path.Combine(DownloadFolder, $"{input.OutputFileName}.shadow.zip"));
}
_logger.LogInformation("Looking for local data to use");
var localDataAvailable = input.File;
var geotiffItem = (Item) null;
if (String.IsNullOrEmpty(localDataAvailable))
{
_logger.LogInformation("Could not find item for uploaded data, using BOFEK");
//Retreiving BOFEK
_logger.LogInformation("Get BOFEK for field");
var bofekItem = await _generalService.RunBofekTask(cropfieldItem);
if (bofekItem == null)
{
_logger.LogError("Something went wrong while obtaining the BOFEK data");
return;
}
_logger.LogInformation("Downloading Bofek map");
await _farmmapsApiService.DownloadItemAsync(bofekItem.Code,
Path.Combine(DownloadFolder, $"{input.OutputFileName}.BOFEK.zip"));
}
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))
: await _generalService.UploadZipWithShapeAsync(uploadedRoot, dataPath,
Path.GetFileNameWithoutExtension(input.File));
if (shapeItem == null)
{
_logger.LogError("Something went wrong while searching for the shape file");
return;
}
// transform shape to geotiff as VRA poten only supports tiff input item
_logger.LogInformation($"Converting shape to geotiff");
geotiffItem = await _generalService.ShapeToGeotiff(shapeItem);
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, $"VRApoten_inputGeotiff_{input.OutputFileName}.zip"));
}
// create appliance map
_logger.LogInformation("Calculating application map");
// INPUT IS NEEDED as GEOTIFF
var applianceMapItem =
await _potenService.CalculateApplicationMapAsync(cropfieldItem, geotiffItem, meanDensity, variation);
if (applianceMapItem == null)
{
return;
}
_logger.LogInformation("Downloading application map");
await _farmmapsApiService.DownloadItemAsync(applianceMapItem.Code,
Path.Combine(DownloadFolder, $"VRApoten_appliancemap_{input.OutputFileName}.zip"));
string finalOutput = Path.Combine(DownloadFolder, $"VRApoten_appliancemap_{input.OutputFileName}.zip");
_logger.LogInformation(File.Exists(finalOutput)
? "Download application map completed."
: "Something went wrong while downloading.");
_logger.LogInformation($"Converting geotiff to shape");
var taskmap = await _generalService.GeotiffToShape(applianceMapItem);
if (taskmap == null)
{
_logger.LogError("Something went wrong with geotiff to shape transformation");
return;
}
_logger.LogInformation("Downloading taskmap");
await _farmmapsApiService.DownloadItemAsync(taskmap.Code,
Path.Combine(DownloadFolder, $"VRApoten_taskmap_{input.OutputFileName}.zip"));
}
}
}

View File

@ -0,0 +1,24 @@
[
{
"File": "PlantingSampleDataLutum.zip",
//"File": "Lutum_SampleDataPlanting.zip",
"OutputFileName": "vraPoten_SampleData",
"FieldName": "lutum",
"PlantingYear": 2020,
"MeanDensity": "30",
"Variation": "20",
"UseShadow": false,
"geometryJson": {
"type": "Polygon",
"coordinates": [
[
[ 5.66886041703652044, 52.52929999060298627 ],
[ 5.6716230923214912, 52.52946316399909676 ],
[ 5.67185376229668581, 52.5280565894154563 ],
[ 5.66903207841337231, 52.52790646510525363 ],
[ 5.66886041703652044, 52.52929999060298627 ]
]
]
}
}
]

View File

@ -0,0 +1,91 @@
using System;
using System.Globalization;
using System.Threading.Tasks;
using FarmmapsApi.Models;
using FarmmapsApi.Services;
using Microsoft.Extensions.Logging;
using Newtonsoft.Json;
using static FarmmapsApi.Extensions;
using static FarmmapsApiSamples.Constants;
namespace FarmmapsVRApoten
{
public class PotenService
{
private readonly ILogger<PotenService> _logger;
private readonly FarmmapsApiService _farmmapsApiService;
private readonly GeneralService _generalService;
public PotenService(ILogger<PotenService> logger, FarmmapsApiService farmmapsApiService,
GeneralService generalService)
{
_logger = logger;
_farmmapsApiService = farmmapsApiService;
_generalService = generalService;
}
public async Task<Item> CalculateApplicationMapAsync(Item cropfieldItem, Item inputItem,string meanDensity, string variation)
{
var potenApplicationMapRequest = new TaskRequest() { TaskType = VRAPLANTING_TASK };
if (inputItem != null) {potenApplicationMapRequest.attributes["inputCode"] = inputItem.Code; }
potenApplicationMapRequest.attributes["meanDensity"] = meanDensity;
potenApplicationMapRequest.attributes["variation"] = variation;
//var taskCode = await _farmmapsApiService.QueueTaskAsync(cropfieldItem.Code, potenApplicationMapRequest);
//await PollTask(TimeSpan.FromSeconds(3), async (tokenSource) =>
//{
// _logger.LogInformation("Checking VRAPoten task status");
// var itemTaskStatus = await _farmmapsApiService.GetTaskStatusAsync(cropfieldItem.Code, taskCode);
// // Code
// if (itemTaskStatus.IsFinished)
// tokenSource.Cancel();
//});
var taskCode = await _farmmapsApiService.QueueTaskAsync(cropfieldItem.Code, potenApplicationMapRequest);
_logger.LogInformation($"itemTaskCode: {taskCode}");
_logger.LogInformation($"potenTaskmapRequest: {potenApplicationMapRequest}");
_logger.LogInformation($"potenTaskmapRequest type: {potenApplicationMapRequest.TaskType}");
_logger.LogInformation($"cropfieldItemCode: {cropfieldItem.Code}");
await PollTask(TimeSpan.FromSeconds(5), async (tokenSource) => {
var itemTaskStatus = await _farmmapsApiService.GetTaskStatusAsync(cropfieldItem.Code, taskCode);
_logger.LogInformation($"Waiting on calculation of application map; Status: {itemTaskStatus.State}");
if (itemTaskStatus.IsFinished)
tokenSource.Cancel();
});
var itemTask = await _farmmapsApiService.GetTaskStatusAsync(cropfieldItem.Code, taskCode);
if (itemTask.State == ItemTaskState.Error)
{
_logger.LogError($"Something went wrong with task execution: {itemTask.Message}");
return null;
}
var itemName = $"VRAPoten";
var applianceMapItem = await _generalService.FindChildItemAsync(cropfieldItem.Code,
GEOTIFF_PROCESSED_ITEMTYPE, itemName,
i => i.Updated >= itemTask.Finished.GetValueOrDefault(DateTime.UtcNow) &&
i.Name.ToLower().Contains(itemName.ToLower()));
if (applianceMapItem == null)
{
_logger.LogError("Could not find the VRAPoten geotiff child item under cropfield");
return null;
}
return applianceMapItem;
}
}
}

23
FarmmapsPoten/Program.cs Normal file
View File

@ -0,0 +1,23 @@
using System.Threading.Tasks;
using FarmmapsApi;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
namespace FarmmapsVRApoten
{
class Program : FarmmapsProgram<PotenApplication>
{
private static async Task Main(string[] args)
{
await new Program().Start(args);
}
protected override void Configure(IServiceCollection serviceCollection)
{
serviceCollection.AddLogging(opts => opts
.AddConsole()
.AddFilter("System.Net.Http", LogLevel.Warning))
.AddTransient<PotenService>();
}
}
}

View File

@ -0,0 +1,10 @@
{
"Authority": "https://accounts.farmmaps.awtest.nl/",
"Endpoint": "http://localhost:8095/",
"BasePath": "api/v1",
"DiscoveryEndpointUrl": "https://accounts.farmmaps.awtest.nl/.well-known/openid-configuration",
"RedirectUri": "http://example.nl/api",
"ClientId": "",
"ClientSecret": "",
"Scopes": ["api"]
}