Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Update ApiLibs #50

Merged
merged 11 commits into from
Jul 7, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
101 changes: 101 additions & 0 deletions Dirigera/DeviceController.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,101 @@
using ApiLibs.General;
using Tomidix.NetStandard.Dirigera.Devices;
using Newtonsoft.Json;
using ApiLibs;

namespace Tomidix.NetStandard.Dirigera;

public class DeviceController : SubService
{
private Service service;
public DeviceController(DirigeraController controller) : base(controller)
{
service = controller;
}

public Task<List<Device>> GetDevices() => MakeRequest<List<Device>>("devices/").ContinueWith((item) => item.Result.Select(i =>
{
i.service = service;
return i;
}).ToList());
public Task<string> GetDevicesJson() => MakeRequest<string>("devices/");

public Task<string> ChangeAttributes<T>(string deviceId, PostingAttributes<T> attributes) where T : PostingAttributesProperties => MakeRequest<string>("devices/" + deviceId, Call.PATCH, content: new object[] { attributes }, statusCode: System.Net.HttpStatusCode.Accepted);

public Task<string> Toggle(Light l) => Toggle(l.Id, !l.Attributes.IsOn).ContinueWith((a) =>
{
l.Attributes.IsOn = !l.Attributes.IsOn;
return a.Result;
});

public Task<string> Toggle(string id, bool isOn) => ChangeAttributes(id, new PostingAttributes<ToggleProperty>(new ToggleProperty
{
IsOn = isOn
}));

public Task<string> SetLightLevel(Light l, int level) => SetLightLevel(l.Id, level).ContinueWith((a) =>
{
l.Attributes.LightLevel = level;
return a.Result;
});

public Task<string> SetLightLevel(string id, int level) => ChangeAttributes(id, new PostingAttributes<LightLevelProperty>(new LightLevelProperty
{
LightLevel = level
}));


public Task<string> SetLightTemperature(Light l, int temperature) => Toggle(l.Id, !l.Attributes.IsOn).ContinueWith((a) =>
{
l.Attributes.ColorTemperature = temperature;
return a.Result;
});

public Task<string> SetLightTemperature(string id, int temperature) => ChangeAttributes(id, new PostingAttributes<LightTemperatureProperty>(new LightTemperatureProperty
{
ColorTemperature = temperature
}));

}

public class PostingAttributes<T> where T : PostingAttributesProperties
{
public PostingAttributes(T properties, int? transitionTime = null)
{
// TransitionTime = transitionTime;
Attributes = properties;
}

[JsonProperty("attributes")]
public T Attributes { get; set; }


[JsonProperty("transitionTime")]
public int? TransitionTime { get; set; }
}

public interface PostingAttributesProperties
{

}

public class ToggleProperty : PostingAttributesProperties
{
[JsonProperty("isOn")]
public required bool IsOn { get; set; }
}


public class LightLevelProperty : PostingAttributesProperties
{
[JsonProperty("lightLevel")]
public required int LightLevel { get; set; }
}

public class LightTemperatureProperty : PostingAttributesProperties
{
[JsonProperty("colorTemperature")]
public required int ColorTemperature { get; set; }
}


154 changes: 154 additions & 0 deletions Dirigera/Devices/Device.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,154 @@
using System.Reflection;
using ApiLibs.General;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;

namespace Tomidix.NetStandard.Dirigera.Devices;

public class DeviceConverter : JsonConverter<Device>

{
public override Device ReadJson(JsonReader reader, Type objectType, Device existingValue, bool hasExistingValue, JsonSerializer serializer)
{
JToken jObject = JToken.ReadFrom(reader);

string type = null;

try
{
if (jObject.Type is not JTokenType.None and not JTokenType.Null)
{
type = jObject["deviceType"].ToObject<string>();
}
}
catch { }

Device result = type switch
{
"environmentSensor" => new EnvironmentSensor(),
"gateway" => new Gateway(),
"light" => new Light(),
_ => throw new ArgumentOutOfRangeException("Cannot convert type " + type + jObject.ToString())
};


serializer.Populate(jObject.CreateReader(), result);
return result;
}

public override bool CanWrite => true;

public void Serialize(PropertyInfo info, Device value, JsonWriter writer)
{
var val = info.GetValue(value);

if (val != null)
{
var customAttributes = (JsonPropertyAttribute[])info.GetCustomAttributes(typeof(JsonPropertyAttribute), true);
if (customAttributes.Length > 0)
{
var myAttribute = customAttributes[0];
string propName = myAttribute.PropertyName;

if (!string.IsNullOrEmpty(propName))
{
writer.WritePropertyName(propName);
}
else
{
writer.WritePropertyName(info.Name);
}
// TODO: Do something with the value
}
else
{
writer.WritePropertyName(info.Name);
}

writer.WriteRawValue(JsonConvert.SerializeObject(val, Formatting.None, new JsonSerializerSettings
{
NullValueHandling = NullValueHandling.Ignore
}));
}
}

public override void WriteJson(JsonWriter writer, Device value, JsonSerializer serializer)
{
throw new System.NotImplementedException();
}
}

#pragma warning disable CS8618 // Non-nullable field must contain a non-null value when exiting constructor. Consider adding the 'required' modifier or declaring as nullable.

[JsonConverter(typeof(DeviceConverter))]
public class Device : ObjectSearcher
{
[JsonProperty("id")]
public string Id { get; set; }

[JsonProperty("type")]
public string Type { get; set; }

[JsonProperty("deviceType")]
public string DeviceType { get; set; }

[JsonProperty("createdAt")]
public string CreatedAt { get; set; }

[JsonProperty("isReachable")]
public bool IsReachable { get; set; }

[JsonProperty("lastSeen")]
public string LastSeen { get; set; }
}

public partial class Attributes
{
[JsonProperty("customName")]
public string CustomName { get; set; }

[JsonProperty("model")]
public string Model { get; set; }

[JsonProperty("manufacturer")]
public string Manufacturer { get; set; }

[JsonProperty("firmwareVersion")]
public string FirmwareVersion { get; set; }

[JsonProperty("hardwareVersion")]
public string HardwareVersion { get; set; }

[JsonProperty("serialNumber")]
public string SerialNumber { get; set; }

[JsonProperty("productCode")]
public string ProductCode { get; set; }

[JsonProperty("identifyPeriod")]
public long IdentifyPeriod { get; set; }

[JsonProperty("identifyStarted")]
public DateTimeOffset IdentifyStarted { get; set; }

[JsonProperty("permittingJoin")]
public bool PermittingJoin { get; set; }

[JsonProperty("otaPolicy")]
public string OtaPolicy { get; set; }

[JsonProperty("otaProgress")]
public long OtaProgress { get; set; }

[JsonProperty("otaScheduleEnd")]
public string OtaScheduleEnd { get; set; }

[JsonProperty("otaScheduleStart")]
public string OtaScheduleStart { get; set; }

[JsonProperty("otaState")]
public string OtaState { get; set; }

[JsonProperty("otaStatus")]
public string OtaStatus { get; set; }
}
58 changes: 58 additions & 0 deletions Dirigera/Devices/EnvironmentSensor.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,58 @@
using System.Reflection;
using ApiLibs.General;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;

namespace Tomidix.NetStandard.Dirigera.Devices;

#pragma warning disable CS8618 // Non-nullable field must contain a non-null value when exiting constructor. Consider adding the 'required' modifier or declaring as nullable.

public class EnvironmentSensor : Device
{
[JsonProperty("attributes")]
public EnvironmentSensorAttributes Attributes { get; set; }

[JsonProperty("room")]
public Room Room { get; set; }

public override string ToString()
{
return Attributes.CustomName;
}
}

public partial class Room
{
[JsonProperty("id")]
public string Id { get; set; }

[JsonProperty("name")]
public string Name { get; set; }

[JsonProperty("color")]
public string Color { get; set; }

[JsonProperty("icon")]
public string Icon { get; set; }
}

public class EnvironmentSensorAttributes : Attributes
{
[JsonProperty("currentTemperature")]
public int CurrentTemperature { get; set; }

[JsonProperty("currentRH")]
public int CurrentRH { get; set; }

[JsonProperty("currentPM25")]
public int CurrentPM25 { get; set; }

[JsonProperty("maxMeasuredPM25")]
public int MaxMeasuredPM25 { get; set; }

[JsonProperty("minMeasuredPM25")]
public int MinMeasuredPM25 { get; set; }

[JsonProperty("vocIndex")]
public int VocIndex { get; set; }
}
80 changes: 80 additions & 0 deletions Dirigera/Devices/Gateway.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,80 @@
using Newtonsoft.Json;

namespace Tomidix.NetStandard.Dirigera.Devices;
#pragma warning disable CS8618 // Non-nullable field must contain a non-null value when exiting constructor. Consider adding the 'required' modifier or declaring as nullable.

public class Gateway : Device
{
[JsonProperty("relationId")]
public string RelationId { get; set; }

[JsonProperty("deviceSet")]
public object[] DeviceSet { get; set; }

[JsonProperty("remoteLinks")]
public object[] RemoteLinks { get; set; }

[JsonProperty("attributes")]
public GatewayAttributes Attributes { get; set; }

public override string ToString()
{
return Attributes.CustomName;
}
}

public partial class GatewayAttributes : Attributes
{
[JsonProperty("backendConnected")]
public bool BackendConnected { get; set; }

[JsonProperty("backendConnectionPersistent")]
public bool BackendConnectionPersistent { get; set; }

[JsonProperty("backendOnboardingComplete")]
public bool BackendOnboardingComplete { get; set; }

[JsonProperty("backendRegion")]
public string BackendRegion { get; set; }

[JsonProperty("backendCountryCode")]
public string BackendCountryCode { get; set; }

[JsonProperty("userConsents")]
public UserConsent[] UserConsents { get; set; }

[JsonProperty("logLevel")]
public long LogLevel { get; set; }

[JsonProperty("coredump")]
public bool Coredump { get; set; }

[JsonProperty("timezone")]
public string Timezone { get; set; }

[JsonProperty("nextSunSet")]
public object NextSunSet { get; set; }

[JsonProperty("nextSunRise")]
public object NextSunRise { get; set; }

[JsonProperty("homestate")]
public string Homestate { get; set; }

[JsonProperty("countryCode")]
public string CountryCode { get; set; }

[JsonProperty("isOn")]
public bool IsOn { get; set; }
}

public partial class UserConsent
{
[JsonProperty("name")]
public string Name { get; set; }

[JsonProperty("value")]
public string Value { get; set; }
}

#pragma warning restore CS8618 // Non-nullable field must contain a non-null value when exiting constructor. Consider adding the 'required' modifier or declaring as nullable.
Loading