From eb82034190fbb1d92ae0be73e4a903be9a900271 Mon Sep 17 00:00:00 2001 From: glax Date: Fri, 19 Jan 2024 01:54:14 +0100 Subject: [PATCH] OpenShockHttp add GetShockers method, returns list of shockerids --- CShocker/CShocker.csproj | 2 +- CShocker/Shockers/APIS/OpenShockHttp.cs | 47 +++++++++++++++++++++++++ 2 files changed, 48 insertions(+), 1 deletion(-) diff --git a/CShocker/CShocker.csproj b/CShocker/CShocker.csproj index 1303e8a..f19cafa 100644 --- a/CShocker/CShocker.csproj +++ b/CShocker/CShocker.csproj @@ -7,7 +7,7 @@ Glax https://github.com/C9Glax/CShocker git - 1.2.0 + 1.2.1 diff --git a/CShocker/Shockers/APIS/OpenShockHttp.cs b/CShocker/Shockers/APIS/OpenShockHttp.cs index b200660..f798bfe 100644 --- a/CShocker/Shockers/APIS/OpenShockHttp.cs +++ b/CShocker/Shockers/APIS/OpenShockHttp.cs @@ -3,11 +3,58 @@ using System.Text; using CShocker.Ranges; using CShocker.Shockers.Abstract; using Microsoft.Extensions.Logging; +using Newtonsoft.Json.Linq; namespace CShocker.Shockers.APIS; public class OpenShockHttp : HttpShocker { + + public List GetShockers() + { + HttpRequestMessage requestDevices = new (HttpMethod.Post, $"{Endpoint}/2/devices") + { + Headers = + { + UserAgent = { new ProductInfoHeaderValue("CShocker", "1") }, + Accept = { new MediaTypeWithQualityHeaderValue("application/json") } + } + }; + requestDevices.Headers.Add("OpenShockToken", ApiKey); + HttpResponseMessage responseDevices = HttpClient.Send(requestDevices); + + StreamReader deviceStreamReader = new(responseDevices.Content.ReadAsStream()); + string deviceJson = deviceStreamReader.ReadToEnd(); + this.Logger?.Log(LogLevel.Debug, $"{requestDevices.RequestUri} response: {responseDevices.StatusCode}\n{deviceJson}"); + JObject deviceListJObj = JObject.Parse(deviceJson); + List deviceIds = new(); + foreach(JToken device in deviceListJObj.SelectTokens("data")) + deviceIds.Add(device.SelectToken("id")!.Value()!); + + List shockerIds = new(); + foreach (string deviceId in deviceIds) + { + HttpRequestMessage requestShockers = new (HttpMethod.Post, $"{Endpoint}/2/devices/{deviceId}/shockers") + { + Headers = + { + UserAgent = { new ProductInfoHeaderValue("CShocker", "1") }, + Accept = { new MediaTypeWithQualityHeaderValue("application/json") } + } + }; + requestShockers.Headers.Add("OpenShockToken", ApiKey); + HttpResponseMessage response = HttpClient.Send(requestShockers); + + StreamReader shockerStreamReader = new(response.Content.ReadAsStream()); + string shockerJson = shockerStreamReader.ReadToEnd(); + this.Logger?.Log(LogLevel.Debug, $"{requestShockers.RequestUri} response: {response.StatusCode}\n{shockerJson}"); + JObject shockerListJObj = JObject.Parse(shockerJson); + foreach(JToken shocker in shockerListJObj.SelectTokens("data")) + shockerIds.Add(shocker.SelectToken("id")!.Value()!); + + } + return shockerIds; + } protected override void ControlInternal(ControlAction action, string shockerId, int intensity, int duration) {