I'm new to this and have little programming knowledge. I want to create a very simple Windows application in Delphi with just one button to turn a Switch on and off.
So far, I haven't been able to connect the Switch to the controller.
In the example below there are 3 buttons. One to Connect, one to Turn On and one to Turn Off.
Code: Select all
unit Unit1;
interface
uses
Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants,
System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs,
Vcl.StdCtrls, System.Net.HttpClient, System.JSON, System.NetEncoding, System.DateUtils;
type
TForm1 = class(TForm)
BtnConectar: TButton;
BtnLigar: TButton;
BtnDesligar: TButton;
MemoLog: TMemo;
procedure BtnConectarClick(Sender: TObject);
procedure BtnLigarClick(Sender: TObject);
procedure BtnDesligarClick(Sender: TObject);
private
FToken: string;
function GetAccessToken: string;
procedure SendCommand(const Code: string; const Value: Variant);
procedure Log(const Msg: string);
public
end;
var
Form1: TForm1;
const
ACCESS_ID = 'My_ACCESS_ID';
ACCESS_SECRET = 'My_ACCESS_SECRET';
DEVICE_ID = 'My_DEVICE_ID';
API_URL = 'https://openapi.tuyaus.com';
implementation
{$R *.dfm}
procedure TForm1.Log(const Msg: string);
begin
MemoLog.Lines.Add(FormatDateTime('hh:nn:ss', Now) + ' - ' + Msg);
end;
function TForm1.GetAccessToken: string;
var
Client: THTTPClient;
Response: IHTTPResponse;
JSONResp: TJSONObject;
URL: string;
begin
Result := '';
Client := THTTPClient.Create;
try
URL := API_URL + '/v1.0/token?grant_type=1';
// Atenção: Pode ser necessário implementar assinatura HMAC
Client.CustomHeaders['client_id'] := ACCESS_ID;
Client.CustomHeaders['sign_method'] := 'HMAC-SHA256';
Client.CustomHeaders['t'] := IntToStr(DateTimeToUnix(Now) * 1000);
Response := Client.Get(URL);
if Response.StatusCode = 200 then
begin
JSONResp := TJSONObject.ParseJSONValue(Response.ContentAsString) as TJSONObject;
try
Result := JSONResp.GetValue<TJSONObject>('result').GetValue<string>('access_token');
Log('Token obtido com sucesso.');
finally
JSONResp.Free;
end;
end
else
Log('Erro ao obter token: ' + Response.StatusCode.ToString);
finally
Client.Free;
end;
end;
procedure TForm1.SendCommand(const Code: string; const Value: Variant);
var
Client: THTTPClient;
Response: IHTTPResponse;
Command, Commands: TJSONObject;
URL: string;
begin
if FToken = '' then
begin
Log('Erro: Token não encontrado. Conecte-se primeiro.');
Exit;
end;
Client := THTTPClient.Create;
try
URL := Format('%s/v1.0/devices/%s/commands', [API_URL, DEVICE_ID]);
Command := TJSONObject.Create;
Command.AddPair('code', Code);
if VarIsBool(Value) then
Command.AddPair('value', TJSONBool.Create(Value))
else
Command.AddPair('value', TJSONString.Create(VarToStr(Value)));
Commands := TJSONObject.Create;
Commands.AddPair('commands', TJSONArray.Create(Command));
Client.CustomHeaders['Authorization'] := 'Bearer ' + FToken;
Response := Client.Post(URL, TStringStream.Create(Commands.ToJSON, TEncoding.UTF8), nil);
if Response.StatusCode = 200 then
Log('Comando "' + Code + '" enviado com sucesso.')
else
Log('Erro ao enviar comando: ' + Response.StatusCode.ToString);
finally
Client.Free;
Commands.Free;
end;
end;
procedure TForm1.BtnConectarClick(Sender: TObject);
begin
FToken := GetAccessToken;
end;
procedure TForm1.BtnLigarClick(Sender: TObject);
begin
SendCommand('switch_1', True);
end;
procedure TForm1.BtnDesligarClick(Sender: TObject);
begin
SendCommand('switch_1', False);
end;
end.