99 lines
2.7 KiB
C#
99 lines
2.7 KiB
C#
using System;
|
|
using System.Net.Http;
|
|
using System.Text;
|
|
using System.Threading.Tasks;
|
|
using TBF.Rig.GenericDevices;
|
|
using TBF.Rig.Network.RestAPI.facade;
|
|
|
|
namespace TBF.Rig.Network.RestAPI
|
|
{
|
|
public class ApiMessageOp : IOperation
|
|
{
|
|
private static readonly HttpClient httpClient = new HttpClient();
|
|
private HttpRequestMessage httpRequest;
|
|
private bool isFinished = false;
|
|
private int timeoutCounter = 0;
|
|
private Event holdEvent = Event.Starting;
|
|
|
|
private IRestAPIAdapter restApiAdapter;
|
|
private ApiDataLoad apiDataLoad;
|
|
|
|
public ApiMessageOp(IRestAPIAdapter restApiAdapter, ApiDataLoad apiDataLoad)
|
|
{
|
|
this.restApiAdapter = restApiAdapter;
|
|
this.apiDataLoad = apiDataLoad;
|
|
}
|
|
|
|
|
|
public void Start()
|
|
{
|
|
httpRequest = new HttpRequestMessage(HttpMethod.Post, restApiAdapter.Path); // An exemplar URL is used here
|
|
holdEvent = Event.Starting;
|
|
}
|
|
|
|
public Event Run()
|
|
{
|
|
if (isFinished)
|
|
{
|
|
return Event.Done;
|
|
}
|
|
|
|
if (timeoutCounter >= 3000)
|
|
{
|
|
return Event.Abort;
|
|
}
|
|
|
|
/**
|
|
* send asynchro request only one time and wait to result or timeout
|
|
*/
|
|
if (holdEvent != Event.Starting)
|
|
{
|
|
return holdEvent;
|
|
}
|
|
|
|
//I must have what to send and where to send
|
|
if (!(restApiAdapter == null || apiDataLoad == null))
|
|
{
|
|
httpRequest.Content = new StringContent(apiDataLoad.getJsonRequestBody(), Encoding.UTF8, "application/json");
|
|
|
|
_ = SendRequestAsync();
|
|
|
|
holdEvent = Event.Busy;
|
|
return holdEvent;
|
|
}
|
|
|
|
holdEvent = Event.Error;
|
|
return holdEvent;
|
|
}
|
|
|
|
private async Task SendRequestAsync()
|
|
{
|
|
try
|
|
{
|
|
var response = await httpClient.SendAsync(httpRequest);
|
|
if (response.IsSuccessStatusCode)
|
|
{
|
|
isFinished = true;
|
|
holdEvent = Event.Done;
|
|
}
|
|
else
|
|
{
|
|
timeoutCounter += 1000;
|
|
await Task.Delay(1000); // Counting timeout
|
|
}
|
|
}
|
|
catch (Exception)
|
|
{
|
|
timeoutCounter += 1000;
|
|
await Task.Delay(1000); // Counting timeout
|
|
holdEvent = Event.Error;
|
|
}
|
|
}
|
|
|
|
public void Stop()
|
|
{
|
|
httpClient.Dispose();
|
|
holdEvent = Event.Done;
|
|
}
|
|
}
|
|
} |