Files
Zway/Zway/Devices/Device.cs
T

92 lines
3.2 KiB
C#

using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Text.RegularExpressions;
using BlubbFish.IoT.Zway.Events;
using BlubbFish.IoT.Zway.lib;
using LitJson;
namespace BlubbFish.IoT.Zway.Devices {
public class Device {
private Boolean polling;
public delegate void UpdatedDevice(Object sender, DeviceUpdateEvent e);
public event UpdatedDevice Update;
public String Name { get; }
public Int32 Id { get; }
public ReadOnlyDictionary<Int32, Instance> Instances { get; private set; }
public DateTime LastUpdate { get; private set; }
private Device(JsonData json, Tuple<Int32> id, HttpConnection http, Boolean polling) {
this.Id = id.Item1;
this.polling = polling;
this.CreateInstances(json["instances"], http);
if (json["data"].Keys.Contains("givenName") && json["data"]["givenName"].Keys.Contains("value")) {
this.Name = json["data"]["givenName"]["value"].ToString();
} else {
this.Name = "Unknown";
}
foreach (KeyValuePair<Int32, Instance> item in this.Instances) {
item.Value.Update += this.InstanceUpdate;
}
}
protected Boolean CheckSetUpdateTime(JsonData json) {
if (json.Keys.Contains("updateTime") && (json["updateTime"].IsInt || json["updateTime"].IsLong)) {
DateTime newdate = DateTimeOffset.FromUnixTimeSeconds(Int64.Parse(json["updateTime"].ToString())).ToLocalTime().DateTime;
if (newdate > this.LastUpdate) {
this.LastUpdate = newdate;
return true;
} else {
return false;
}
} else {
return true;
}
}
private void InstanceUpdate(Object sender, DeviceUpdateEvent e) {
this.Update?.Invoke(this, e);
}
private void CreateInstances(JsonData json, HttpConnection http) {
Dictionary<Int32, Instance> instances = new Dictionary<Int32, Instance>();
foreach (String instanceid in json.Keys) {
Instance i = Instance.CreateInstance(json[instanceid], new Tuple<Int32, Int32>(this.Id, Int32.Parse(instanceid)), http, this.polling);
if (i != null) {
instances.Add(Int32.Parse(instanceid), i);
}
}
this.Instances = new ReadOnlyDictionary<Int32, Instance>(instances);
}
internal static Device CreateDevice(JsonData json, Tuple<Int32> id, HttpConnection http, Boolean polling) {
if(json.Keys.Contains("instances") &&
json["instances"].Count > 0 &&
json.Keys.Contains("data") && id.Item1 != 1) {
return new Device(json, id, http, polling);
}
return null;
}
public override String ToString() {
return this.Name+"_"+this.Id+" ["+this.Instances.Count+"]";
}
internal void SetUpdate(JsonData json, Match match) {
if (match.Groups[2].Value == "data.lastReceived") {
if (this.CheckSetUpdateTime(json)) {
//this.Update?.Invoke(this, new DeviceUpdateEvent(this.LastUpdate, this.LastUpdate));
}
}
}
internal void Poll() {
foreach (KeyValuePair<Int32, Instance> item in this.Instances) {
item.Value.Poll();
}
}
}
}