IotService.cs
2.82 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
using DataAcquisition.ViewModels.IOT;
using System.Text;
using System.Text.Json;
namespace DataAcquisition.Services
{
public class IotService
{
private readonly IHttpClientFactory _httpClientFactory;
private readonly string identity = "iot";
public IotService(IHttpClientFactory httpClientFactory)
{
_httpClientFactory = httpClientFactory;
}
/// <summary>
/// 设备数据
/// </summary>
/// <param name="equipment"></param>
/// <returns></returns>
public IotResult<string> SendEquipment(IEnumerable<IotEquipment> equipment)
{
return Post("", equipment);
}
/// <summary>
/// 设备报警
/// </summary>
/// <param name="equipmentAlarm"></param>
/// <returns></returns>
public IotResult<string> SendEquipmentAlarm(IotEquipmentAlarm equipmentAlarm)
{
return Post("", equipmentAlarm);
}
/// <summary>
/// 设备运行参数
/// </summary>
/// <param name="equipmmentRunParameter"></param>
/// <returns></returns>
public IotResult<string> SendEquipmentRunParameter(IotEquipmmentRunParameter equipmmentRunParameter)
{
return Post("", equipmmentRunParameter);
}
/// <summary>
/// 设备状态
/// </summary>
/// <param name="equipmentStatus"></param>
/// <returns></returns>
public IotResult<string> SendEquipmentStatus(IotEquipmentStatus equipmentStatus)
{
return Post("", equipmentStatus);
}
private IotResult<string> Post<T>(string requestUri, T data)
{
try
{
var client = _httpClientFactory.CreateClient(identity);
var json = JsonSerializer.Serialize(data);
var responseMessage = client.PostAsync(requestUri, new StringContent(json, Encoding.UTF8)).GetAwaiter().GetResult();
if (!responseMessage.IsSuccessStatusCode)
{
return new IotResult<string>
{
Code = (int)responseMessage.StatusCode,
Status = false,
Message = responseMessage.ReasonPhrase ?? string.Empty,
};
}
var responseContent = responseMessage.Content.ReadAsStringAsync().GetAwaiter().GetResult();
return JsonSerializer.Deserialize<IotResult<string>>(responseContent)!;
}
catch (Exception ex)
{
return new IotResult<string>
{
Code = 500,
Message = ex.Message,
Status = false,
};
}
}
}
}