-
Notifications
You must be signed in to change notification settings - Fork 7
/
Copy pathDeviceCache.cs
110 lines (94 loc) · 3.33 KB
/
DeviceCache.cs
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
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
namespace EWeLink.Api
{
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using EWeLink.Api.Models.Devices;
using EWeLink.Api.Models.EventParameters;
public class DeviceCache : IDeviceCache
{
private static readonly Dictionary<int, Type> UiidToEventParameterTypes;
private readonly Dictionary<string, IDevice> deviceIdToDevices = new ();
private readonly Dictionary<string, int> deviceIdTUiid = new ();
static DeviceCache()
{
UiidToEventParameterTypes = typeof(DeviceCache).Assembly.ExportedTypes
.Select(x => new { Attribute = x.GetCustomAttribute(typeof(EventDeviceIdentifierAttribute)) as EventDeviceIdentifierAttribute, Type = x })
.Where(x => x.Attribute != null).SelectMany(x => x.Attribute!.Uiids.Select(i => new { Uiid = i, Type = x.Type }))
.ToDictionary(x => x.Uiid, v => v.Type);
}
public int? GetDevicesUiid(string deviceId)
{
if (this.deviceIdTUiid.TryGetValue(deviceId, out var uiid))
{
return uiid;
}
return null;
}
public bool TryGetDevice(string deviceId, out IDevice? device)
{
device = null;
if (this.deviceIdToDevices.TryGetValue(deviceId, out var val))
{
device = val;
return true;
}
return false;
}
public Type? GetEventParameterTypeForUiid(int uiid)
{
if (UiidToEventParameterTypes.TryGetValue(uiid, out var type))
{
return type;
}
return null;
}
public bool TryGetEventParameterTypeForUiid(int uiid, out Type? type)
{
type = null;
if (UiidToEventParameterTypes.TryGetValue(uiid, out var val))
{
type = val;
return true;
}
return false;
}
public IDevice? GetDevice(string deviceId)
{
if (this.deviceIdToDevices.TryGetValue(deviceId, out var device))
{
return device;
}
return null;
}
public IEnumerable<IDevice> UpdateCache(IEnumerable<IDevice> devices)
{
foreach (var device in devices)
{
UpdateCache(device);
}
return devices;
}
public IDevice UpdateCache(IDevice device)
{
lock (this.deviceIdToDevices)
{
if (device is { DeviceId: not null })
{
if (!this.deviceIdToDevices.ContainsKey(device.DeviceId))
{
this.deviceIdToDevices.Add(device.DeviceId, device);
this.deviceIdTUiid.Add(device.DeviceId, device.Uiid);
}
else
{
this.deviceIdToDevices[device.DeviceId] = device;
this.deviceIdTUiid[device.DeviceId] = device.Uiid;
}
}
return device;
}
}
}
}