2023-03-22 13:48:13 +00:00
using System ;
using System.Collections.Generic ;
using System.IO ;
using System.IO.Compression ;
using System.Linq ;
using System.Threading.Tasks ;
using FarmmapsApi ;
using FarmmapsApi.Models ;
using FarmmapsApi.Services ;
using FarmmapsKPI.Models ;
using Microsoft.Extensions.Logging ;
using Newtonsoft.Json ;
using Newtonsoft.Json.Linq ;
using static FarmmapsApiSamples . Constants ;
namespace FarmmapsKPI
{
public class KPIApplication : IApplication
{
//private const string DownloadFolder = "Downloads";
private const string SettingsFile = "settings.json" ;
private readonly ILogger < KPIApplication > _logger ;
private readonly FarmmapsApiService _farmmapsApiService ;
2023-10-04 15:21:05 +00:00
private readonly KPIService _kpiService ;
2023-03-22 13:48:13 +00:00
private readonly GeneralService _generalService ;
private Settings _settings ;
public KPIApplication ( ILogger < KPIApplication > logger , FarmmapsApiService farmmapsApiService ,
2023-10-04 15:21:05 +00:00
GeneralService generalService , KPIService kpiService )
2023-03-22 13:48:13 +00:00
{
_logger = logger ;
_farmmapsApiService = farmmapsApiService ;
_generalService = generalService ;
2023-10-04 15:21:05 +00:00
_kpiService = kpiService ;
2023-03-22 13:48:13 +00:00
}
public async Task RunAsync ( )
{
var fieldsInputJson = File . ReadAllText ( "KPIInput.json" ) ;
List < KPIInput > fieldsInputs = JsonConvert . DeserializeObject < List < KPIInput > > ( fieldsInputJson ) ;
// !! 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 fieldsInputs )
{
try
{
await Process ( roots , input ) ;
}
catch ( Exception ex )
{
_logger . LogError ( ex . Message ) ;
}
}
}
private async Task Process ( List < UserRoot > roots , KPIInput input )
{
string downloadFolder = input . DownloadFolder ;
if ( string . IsNullOrEmpty ( downloadFolder ) ) {
downloadFolder = "Downloads" ;
}
if ( ! Directory . Exists ( downloadFolder ) )
Directory . CreateDirectory ( downloadFolder ) ;
// !!specify if you are using an already created cropfield:
bool useCreatedCropfield = input . UseCreatedCropfield ;
2023-10-04 15:21:05 +00:00
bool useCreatedCropRecording = input . UseCreatedCropRecording ;
bool useCreatedOperations = input . UseCreatedOperation ;
bool useCreatedCropfieldCharacteristic = input . UseCreatedCropfieldCharacteristic ;
2023-03-22 13:48:13 +00:00
var cropYear = input . CropYear ;
var fieldName = input . fieldName ;
//bool storeSatelliteStatistics = input.StoreSatelliteStatisticsSingleImage;
//bool storeSatelliteStatisticsCropYear = input.StoreSatelliteStatisticsCropYear;
//List<string> SatelliteBands = new List<string>(1) { input.SatelliteBand };
//string headerLineStats = $"FieldName,satelliteDate,satelliteBand,max,min,mean,mode,median,stddev,minPlus,curtosis,maxMinus,skewness,variance,populationCount,variationCoefficient,confidenceIntervalLow, confidenceIntervalHigh,confidenceIntervalErrorMargin" + Environment.NewLine;
string settingsfile = $"Settings_{fieldName}.json" ;
LoadSettings ( settingsfile ) ;
var uploadedRoot = roots . SingleOrDefault ( r = > r . Name = = "USER_IN" ) ;
if ( uploadedRoot = = null )
{
_logger . LogError ( "Could not find a needed root item" ) ;
return ;
}
var myDriveRoot = roots . SingleOrDefault ( r = > r . Name = = "USER_FILES" ) ;
if ( myDriveRoot = = null )
{
_logger . LogError ( "Could not find a needed root item" ) ;
return ;
}
2023-04-25 14:14:43 +00:00
// Use already created cropfield or create new one, added a Data input, with field specific data for the KPI calculation
2023-03-22 13:48:13 +00:00
Item cropfieldItem ;
2023-10-04 15:21:05 +00:00
//1 useCreatedCropfield = false -> create new
2023-06-27 12:08:27 +00:00
//2 useCreatedCropfield = true && CropfieldItemCode = "" or absent -> read from settings json
2023-10-04 15:21:05 +00:00
//3 useCreatedCropfield = true && CropfieldItemCode like "deb48a74c5b54299bb852f17288010e9" in KPIinput -> use this one
2023-06-27 12:08:27 +00:00
if ( useCreatedCropfield = = false | | string . IsNullOrEmpty ( _settings . CropfieldItemCode ) )
2023-03-22 13:48:13 +00:00
{
2023-06-27 12:08:27 +00:00
_logger . LogInformation ( "Creating cropfield, writting to settings file" ) ;
2023-03-22 13:48:13 +00:00
cropfieldItem = await _generalService . CreateCropfieldItemAsync ( myDriveRoot . Code ,
2023-10-04 15:21:05 +00:00
$"{input.OutputFileName}" , cropYear , input . GeometryJson . ToString ( Formatting . None ) , input . DataCropfield . ToString ( Formatting . None ) ) ;
2023-03-22 13:48:13 +00:00
_settings . CropfieldItemCode = cropfieldItem . Code ;
SaveSettings ( settingsfile ) ;
}
2023-06-27 12:08:27 +00:00
else if ( string . IsNullOrEmpty ( input . CropfieldItemCode ) )
2023-03-22 13:48:13 +00:00
{
2023-10-04 15:21:05 +00:00
_logger . LogInformation ( "reading CropfieldItemCode from settings file" ) ;
2023-03-22 13:48:13 +00:00
cropfieldItem = await _farmmapsApiService . GetItemAsync ( _settings . CropfieldItemCode ) ;
}
2023-06-27 12:08:27 +00:00
else
{
2023-10-04 15:21:05 +00:00
_logger . LogInformation ( "reading CropfieldItemCode from KPIinput.json" ) ;
2023-06-27 12:08:27 +00:00
cropfieldItem = await _farmmapsApiService . GetItemAsync ( input . CropfieldItemCode ) ;
}
2023-03-22 13:48:13 +00:00
2023-10-04 15:21:05 +00:00
// Use already created croprecording or create new one, added a Data input, with field specific data for the KPI calculation
Item crprecItem ;
//1 useCreatedCropRecording = false -> create new
//2 useCreatedCropRecording = true && CropRecordingItemCode = "" or absent -> read from settings json
//3 useCreatedCropRecording = true && CropRecordingItemCode like "deb48a74c5b54299bb852f17288010e9" in KPIinput -> use this one
if ( useCreatedCropRecording = = false | | string . IsNullOrEmpty ( _settings . CropRecordingItemCode ) )
{
_logger . LogInformation ( "RunCropRecordingTask ..." ) ;
crprecItem = await _generalService . RunCropRecordingTask ( cropfieldItem ) ;
_settings . CropRecordingItemCode = crprecItem . Code ;
SaveSettings ( settingsfile ) ;
}
else if ( string . IsNullOrEmpty ( input . CropfieldItemCode ) )
{
_logger . LogInformation ( "reading CropRecordingItemCode from settings file" ) ;
crprecItem = await _farmmapsApiService . GetItemAsync ( _settings . CropRecordingItemCode ) ;
}
else
2023-03-22 13:48:13 +00:00
{
2023-10-04 15:21:05 +00:00
_logger . LogInformation ( "reading CropRecordingItemCode from KPIinput.json" ) ;
crprecItem = await _farmmapsApiService . GetItemAsync ( input . CropRecordingItemCode ) ;
}
2023-03-22 13:48:13 +00:00
2023-10-04 15:21:05 +00:00
// Use already created operation or create new one, added a Data input, with field specific data for the KPI calculation
Item crpOperationItem ;
//1 useCreatedOperation = false -> create new
//2 useCreatedOperation = true && OperationItemCode = "" or absent -> read from settings json
//3 useCreatedOperation = true && OperationItemCode like "deb48a74c5b54299bb852f17288010e9" in KPIinput -> use this one
if ( useCreatedOperations = = false | | string . IsNullOrEmpty ( _settings . OperationItemCode ) )
{
_logger . LogInformation ( "CreateOperationItemAsync ..." ) ;
crpOperationItem = await _generalService . CreateOperationItemAsync ( crprecItem . Code , input . DataOperation . ToString ( Formatting . None ) ) ;
_settings . OperationItemCode = crpOperationItem . Code ;
SaveSettings ( settingsfile ) ;
}
else if ( string . IsNullOrEmpty ( input . CropfieldItemCode ) )
{
_logger . LogInformation ( "reading OperationItemCode from settings file" ) ;
crpOperationItem = await _farmmapsApiService . GetItemAsync ( _settings . OperationItemCode ) ;
}
else
{
_logger . LogInformation ( "reading OperationItemCode from KPIinput.json" ) ;
crpOperationItem = await _farmmapsApiService . GetItemAsync ( input . OperationItemCode ) ;
}
2023-03-22 13:48:13 +00:00
2023-10-04 15:21:05 +00:00
// The cropfieldCharacteristicItem is used to enter crop yields
// So once we have added an operation for fertilizer application and a crop yield, then KPIapp can calculate
// Nutrient balance.
// Use already created cropfieldCharacteristicItem or create new one, added a Data input, with field specific data for the KPI calculation
Item cropfieldCharacteristicItem ;
//1 useCreatedCropfieldCharacteristic = false -> create new
//2 useCreatedCropfieldCharacteristic = true && CropfieldCharacteristicItemCode = "" or absent -> read from settings json
//3 useCreatedCropfieldCharacteristic = true && CropfieldCharacteristicItemCode like "deb48a74c5b54299bb852f17288010e9" in KPIinput -> use this one
if ( useCreatedCropfieldCharacteristic = = false )
{
_logger . LogInformation ( "CreateCropfieldCharacteristicItemAsync ..." ) ;
cropfieldCharacteristicItem = await _generalService . CreateCropfieldCharacteristicItemAsync ( cropfieldItem . Code , input . DataCropfieldCharacteristic . ToString ( Formatting . None ) ) ;
_settings . CropfieldCharacteristicItemCode = cropfieldCharacteristicItem . Code ;
SaveSettings ( settingsfile ) ;
}
else if ( string . IsNullOrEmpty ( input . CropfieldCharacteristicItemCode ) )
{
_logger . LogInformation ( "reading OperationItemCode from settings file" ) ;
cropfieldCharacteristicItem = await _farmmapsApiService . GetItemAsync ( _settings . CropfieldCharacteristicItemCode ) ;
2023-03-22 13:48:13 +00:00
}
else
{
2023-10-04 15:21:05 +00:00
_logger . LogInformation ( "reading CropfieldCharacteristicItemCode from KPIinput.json" ) ;
cropfieldCharacteristicItem = await _farmmapsApiService . GetItemAsync ( input . CropfieldCharacteristicItemCode ) ;
2023-03-22 13:48:13 +00:00
}
2023-10-04 15:21:05 +00:00
// Inspect the children. If all is well, cropfield will have one crprec and one edicrop.characteristic
// And the crprec will have 0-many operations as children
// And the Data of an operation will have specification of how much fertilizer was applied
// And crprec can have multiple operations
// Note existing cropfields and croprecordings keep existing properties you added in previous runs
// (unless you deleted them)
// So ech time you run with "UseCreatedCropfield": true & "UseCreatedCropRecording": false -> a new recording will be added to the existing cropfield
// So ech time you run with "UseCreatedCropfield": true & "useCreatedCropfieldCharacteristic": false -> a new CropfieldCharacteristic will be added to the existing cropfield
// So ech time you run with "UseCreatedCropRecording": true & "UseCreatedOperation": false -> a new operation will be added to the existing crop recording
var cropfieldChildren = await _farmmapsApiService . GetItemChildrenAsync ( cropfieldItem . Code ) ;
var crprecChildren = await _farmmapsApiService . GetItemChildrenAsync ( crprecItem . Code ) ;
//Now get the KPIs for this cropfield, mounted with operations & cropyield
2023-06-27 10:58:36 +00:00
// Get KPI data for saving it in a file, here the generalsedrvice is called to get the KPI data
2023-10-04 15:21:05 +00:00
_logger . LogInformation ( $"GetKpiItemsForCropField({cropfieldItem.Code})" ) ;
2023-04-25 10:00:08 +00:00
var KPIItem = await _generalService . GetKpiItemsForCropField ( cropfieldItem ) ;
2023-10-04 15:21:05 +00:00
//Download KPI's into a json output file for this specific cropfield (with unique cropfieldItem.Code)
2023-06-27 12:08:27 +00:00
var KPIItemPath = Path . Combine ( downloadFolder , $"KPIItems_{cropfieldItem.Code}.json" ) ;
2023-04-25 10:00:08 +00:00
_logger . LogInformation ( $"Found {KPIItem.Count} KPI items" ) ;
var count = 0 ;
await Task . Delay ( 50 ) ;
foreach ( var item in KPIItem )
2023-03-22 13:48:13 +00:00
{
2023-04-25 10:00:08 +00:00
Console . WriteLine ( $"KPI item #{count}: {item.Name}" ) ;
File . AppendAllText ( KPIItemPath , item . Data + Environment . NewLine ) ;
count + + ;
2023-03-22 13:48:13 +00:00
}
2023-04-25 10:00:08 +00:00
_logger . LogInformation ( $"Downloaded file {KPIItemPath}" ) ;
2023-03-22 13:48:13 +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 ) ;
}
else
{
_settings = new Settings ( ) ;
}
}
private void SaveSettings ( string file )
{
if ( _settings = = null )
return ;
var json = JsonConvert . SerializeObject ( _settings ) ;
File . WriteAllText ( file , json ) ;
}
private void SaveInfo ( string file )
{
if ( _settings = = null )
return ;
var json = JsonConvert . SerializeObject ( _settings ) ;
File . WriteAllText ( file , json ) ;
}
}
}