//
// Copyright (c) 2020 smdn <smdn@smdn.jp>
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
using System;
using System.Buffers;
using System.Collections.Generic;
using System.Net;
using System.Net.Sockets;
using System.Linq;
using System.Text.Json;
using System.Threading;
using System.Threading.Tasks;
namespace Smdn.TPLinkKasaClient {
/// <summary>
/// C# implementation of TP-Link Kasa API client, ported from https://github.com/plasticrake/tplink-smarthome-api
/// </summary>
public class SimpleClient {
public const int DefaultPort = 9999;
public string Host { get; }
public int Port { get; }
public SimpleClient(
string host,
int port = DefaultPort
)
{
this.Host = string.IsNullOrEmpty(host)
? throw new ArgumentException($"'{nameof(host)}' must be non-empty string", nameof(host))
: host;
this.Port = port < IPEndPoint.MinPort || IPEndPoint.MaxPort < port
? throw new ArgumentOutOfRangeException(nameof(port), port, $"must be in range of {IPEndPoint.MinPort}~{IPEndPoint.MaxPort}")
: port;
}
public Task<JsonDocument> SendAsync(
string module,
string method
)
=> SendAsync(
module,
method,
methodParameters: (IEnumerable<(string, object)>)null
);
public Task<JsonDocument> SendAsync(
string module,
string method,
IEnumerable<(string name, object value)> methodParameters
)
=> SendCommandAsync(
module,
method,
methodParameters?.Select(ConvertToJsonFormat)
);
public Task<JsonDocument> SendAsync(
string module,
string method,
IEnumerable<KeyValuePair<string, object>> methodParameters
)
=> SendCommandAsync(
module,
method,
methodParameters?.Select(pair => ConvertToJsonFormat((pair.Key, pair.Value)))
);
private static (string, string) ConvertToJsonFormat(
(string name, object value) prop
)
=> (
prop.name,
prop.value switch {
bool b => b ? "true" : "false",
string s => string.Concat("\"", s.Replace("\"", "\\\""), "\""),
//int i => i.ToString(),
//double d => d.ToString(),
null => "null",
_ => Convert.ToString(prop.value),
}
);
private async Task<JsonDocument> SendCommandAsync(
string module,
string method,
IEnumerable<(string name, string value)> nullableMethodParameters)
{
string ConstructJsonDocument()
=> @$"{{
""{module}"":{{
""{method}"":{{
{string.Join(",\n", nullableMethodParameters?.Select(p => $"\"{p.name}\":{p.value}") ?? Enumerable.Empty<string>())}
}}
}}
}}";
using (var socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp)) {
/*
* connect
*/
await socket.ConnectAsync(Host, Port).ConfigureAwait(false);
/*
* send
*/
await socket.SendAsync(
CryptoUtils.Encrypt(ConstructJsonDocument()),
default(SocketFlags),
default(CancellationToken)
).ConfigureAwait(false);
/*
* receive
*/
SequenceSegment receivedSequenceHead = null;
SequenceSegment receivedSequenceTail = null;
for (;;) {
const int bufferSize = 0x100;
var buffer = (Memory<byte>)new byte[bufferSize];
var len = await socket.ReceiveAsync(
buffer,
default(SocketFlags),
default(CancellationToken)
).ConfigureAwait(false);
if (len <= 0)
break;
if (receivedSequenceHead == null)
receivedSequenceTail = receivedSequenceHead = new SequenceSegment(null, buffer);
else
receivedSequenceTail = new SequenceSegment(receivedSequenceTail, buffer);
if (len < buffer.Length)
break;
}
/*
* parse
*/
var receivedSequence = new ReadOnlySequence<byte>(
receivedSequenceHead,
0,
receivedSequenceTail,
receivedSequenceTail.Memory.Length
);
var response = CryptoUtils.Decrypt(receivedSequence);
return JsonDocument.Parse(
response,
default(JsonDocumentOptions)
);
}
}
private class SequenceSegment : ReadOnlySequenceSegment<byte> {
public SequenceSegment(SequenceSegment prev, ReadOnlyMemory<byte> memory)
{
Memory = memory;
if (prev == null) {
RunningIndex = 0;
}
else {
RunningIndex = prev.RunningIndex + prev.Memory.Length;
prev.Next = this;
}
}
}
}
}