FarmMapsApiClient/FarmmapsApiSamples/NbsApp.cs

138 lines
5.7 KiB
C#

using System;
using System.Linq;
using System.Threading.Tasks;
using FarmmapsApi.Models;
using FarmmapsApi.Services;
using Microsoft.Extensions.Logging;
using Newtonsoft.Json.Linq;
using static FarmmapsApi.Extensions;
namespace FarmmapsApiSamples
{
public class NbsApp : IApp
{
private const string USERINPUT_ITEMTYPE = "vnd.farmmaps.itemtype.user.input";
private const string VRANBS_TASK = "vnd.farmmaps.task.vranbs";
private readonly ILogger<NbsApp> _logger;
private readonly FarmmapsApiService _farmmapsApiService;
public NbsApp(ILogger<NbsApp> logger, FarmmapsApiService farmmapsApiService)
{
_logger = logger;
_farmmapsApiService = farmmapsApiService;
farmmapsApiService.EventCallback += OnEvent;
}
private void OnEvent(EventMessage @event)
{
_logger.LogInformation(@event.EventType);
}
public async Task RunAsync()
{
try
{
_logger.LogInformation("NBS sample app started");
await _farmmapsApiService.AuthenticateAsync();
_logger.LogInformation("Authenticated client credentials");
var roots = await _farmmapsApiService.GetCurrentUserRootsAsync();
var myDriveRoot = roots.SingleOrDefault(r => r.Name == "My drive");
if (myDriveRoot != null)
{
var cropfieldItem = await GetOrCreateCropfieldItem(myDriveRoot.Code);
var targetN = await CalculateTargetN(cropfieldItem, 60);
_logger.LogInformation($"TargetN: {targetN}");
}
}
catch (Exception ex)
{
_logger.LogError(ex.Message);
}
}
private async Task<Item> GetOrCreateCropfieldItem(string parentItemCode)
{
var cropfieldItems = await
_farmmapsApiService.GetItemChildrenAsync(parentItemCode, "vnd.farmmaps.itemtype.cropfield");
if (cropfieldItems.Count > 0)
return cropfieldItems[0];
var currentYear = new DateTime(DateTime.UtcNow.Year, 1, 1);
var cropfieldItemRequest = new ItemRequest()
{
ParentCode = parentItemCode,
ItemType = "vnd.farmmaps.itemtype.cropfield",
Name = "cropfield for VRA",
DataDate = currentYear,
DataEndDate = currentYear.AddYears(1),
Data = JObject.FromObject(new
{startDate = currentYear, endDate = currentYear.AddYears(1)}),
Geometry = JObject.Parse(
@"{""type"":""Polygon"",""coordinates"":[[[6.09942873984307,53.070025028087],[6.09992507404607,53.0705617890585],[6.10036959220086,53.0710679529031],[6.10065149010421,53.0714062774307],[6.10087493644271,53.0716712354474],[6.10091082982487,53.0716936039203],[6.10165087441291,53.0712041549161],[6.10204994718318,53.0709349338005],[6.10263143118855,53.0705789370018],[6.10311578125011,53.0702657538294],[6.10331686552072,53.0701314102389],[6.103326530575,53.070119463569],[6.10309137950343,53.0699829669055],[6.10184241586523,53.0692902201371],[6.10168497998891,53.0691984306747],[6.10092987659869,53.0694894453514],[6.09942873984307,53.070025028087]]]}")
};
return await _farmmapsApiService.CreateItemAsync(cropfieldItemRequest);
}
private async Task<double> CalculateTargetN(Item cropfieldItem, int targetYield)
{
var targetNItems = await
_farmmapsApiService.GetItemChildrenAsync(cropfieldItem.ParentCode, USERINPUT_ITEMTYPE);
Item targetNItem;
if (targetNItems.Count == 0)
{
_logger.LogInformation("Creating targetN item");
var itemRequest = CreateTargetNItemRequest(cropfieldItem.ParentCode);
targetNItem = await _farmmapsApiService.CreateItemAsync(itemRequest);
}
else
{
targetNItem = targetNItems[0];
}
_logger.LogInformation($"Calculating targetN with targetYield: {targetYield}");
var nbsTargetNRequest = new TaskRequest {TaskType = VRANBS_TASK};
nbsTargetNRequest.attributes["operation"] = "targetn";
nbsTargetNRequest.attributes["inputCode"] = targetNItem.Code;
nbsTargetNRequest.attributes["inputType"] = "irmi";
nbsTargetNRequest.attributes["purposeType"] = "consumption";
nbsTargetNRequest.attributes["targetYield"] = targetYield.ToString();
string itemTaskCode = await _farmmapsApiService.QueueTaskAsync(cropfieldItem.Code, nbsTargetNRequest);
await PollTask(TimeSpan.FromSeconds(3), async (tokenSource) =>
{
var itemTask = await _farmmapsApiService.GetTaskStatusAsync(cropfieldItem.Code, itemTaskCode);
if (itemTask.State != ItemTaskState.Processing && itemTask.State != ItemTaskState.Scheduled)
tokenSource.Cancel();
});
var item = await _farmmapsApiService.GetItemAsync(targetNItem.Code);
if (item.Data.ContainsKey("TargetN"))
return item.Data["TargetN"].Value<double>();
return 0;
}
private ItemRequest CreateTargetNItemRequest(string parentItemCode)
{
return new ItemRequest()
{
ParentCode = parentItemCode,
ItemType = USERINPUT_ITEMTYPE,
Name = "TargetN",
DataDate = DateTime.UtcNow
};
}
}
}