Skip to content

Commit f3eb75f

Browse files
committed
FEAT: New MQTT commands started
1 parent 3313d12 commit f3eb75f

7 files changed

+167
-181
lines changed

CorefluxCSharpAPI/API/Client.cs

+104-56
Original file line numberDiff line numberDiff line change
@@ -1,92 +1,140 @@
1-
using Coreflux.API.DataModels;
2-
using CorefluxCSharpAPI.API.Services;
3-
using CorefluxCSharpAPI.API.Services.Interfaces;
1+
using System;
2+
using System.Net;
3+
using System.Collections.Generic;
4+
using System.Text;
5+
using System.IO;
46
using Newtonsoft.Json;
5-
using System;
7+
using MQTTnet;
8+
using MQTTnet.Client;
9+
using MQTTnet.Protocol;
10+
using MQTTnet.Client.Options;
611

712
namespace Coreflux.API
813
{
9-
public class Client
14+
15+
public class Central
1016
{
11-
private readonly string _ip;
12-
private readonly ICommunicationService _communicationService;
17+
18+
private IMqttClient client;
19+
private string serverAddress = "127.0.0.1"; // replace with your Coreflux server address
20+
private string username = "root";
21+
private string pass = "coreflux";
22+
private string cloudCommand = "$SYS/Coreflux/Cloud/Command";
23+
private string cloudCommandOutput = "$SYS/Coreflux/Cloud/Command/Output";
24+
public Central(string Host, string user, string password)
25+
{
26+
var factory = new MqttFactory();
27+
serverAddress = Host;
28+
username = user;
29+
pass = password;
30+
client = factory.CreateMqttClient();
31+
}
1332

1433
/// <summary>
15-
/// This constructor is recommend for unit testing.
16-
/// This constructor let's you pass a mock object of ICommunicationService.
34+
/// Connects to the Coreflux Central.
1735
/// </summary>
18-
/// <param name="ip"></param>
19-
/// <param name="communicationService"></param>
20-
public Client(string ip, ICommunicationService communicationService = null)
36+
public async void Connect()
2137
{
22-
_ip = ip;
23-
_communicationService = communicationService ?? new CommunicationService();
38+
var options = new MqttClientOptionsBuilder()
39+
.WithClientId(Guid.NewGuid().ToString())
40+
.WithTcpServer(serverAddress)
41+
.WithCredentials(username, pass)
42+
.Build();
43+
44+
await client.ConnectAsync(options);
45+
}
46+
47+
private async void SendCommand(string command)
48+
{
49+
var message = new MqttApplicationMessageBuilder()
50+
.WithTopic(cloudCommand)
51+
.WithPayload(command)
52+
.WithQualityOfServiceLevel(MqttQualityOfServiceLevel.AtLeastOnce)
53+
.WithRetainFlag()
54+
.Build();
55+
56+
await client.PublishAsync(message);
2457
}
2558

2659
/// <summary>
27-
/// This constructor is the recommend for production application's
60+
/// Subscribes to the given MQTT topic to receive messages from the Coreflux server.
2861
/// </summary>
29-
/// <param name="ip"></param>
30-
public Client(string ip)
62+
/// <param name="responseTopic">The MQTT topic to subscribe to.</param>
63+
public async void SubscribeToCommandOutput(string responseTopic)
3164
{
32-
_ip = ip;
33-
_communicationService = new CommunicationService();
65+
await client.SubscribeAsync(new TopicFilterBuilder()
66+
.WithTopic(responseTopic)
67+
.WithQualityOfServiceLevel(MqttQualityOfServiceLevel.AtLeastOnce)
68+
.Build());
69+
70+
client.UseApplicationMessageReceivedHandler(e =>
71+
{
72+
Console.WriteLine("### RECEIVED APPLICATION MESSAGE ###");
73+
Console.WriteLine($"+ Topic = {e.ApplicationMessage.Topic}");
74+
Console.WriteLine($"+ Payload = {Encoding.UTF8.GetString(e.ApplicationMessage.Payload)}");
75+
Console.WriteLine($"+ QoS = {e.ApplicationMessage.QualityOfServiceLevel}");
76+
Console.WriteLine($"+ Retain = {e.ApplicationMessage.Retain}");
77+
Console.WriteLine();
78+
});
3479
}
3580

81+
3682
/// <summary>
37-
/// If null is returned, something failed on obtaining the instances.
83+
/// Sends a login command to the Coreflux Cloud.
3884
/// </summary>
39-
/// <returns></returns>
40-
public AppInstance[] GetInstances()
85+
/// <param name="account">The account email.</param>
86+
/// <param name="pass">The password.</param>
87+
public void CloudLogin(string account, string pass)
4188
{
42-
string response = _communicationService.GetInformation(string.Format("https://{0}:9501/CorefluxCentral/instances", _ip));
43-
return string.IsNullOrEmpty(response) ? null : JsonConvert.DeserializeObject<AppInstance[]>(response);
89+
SendCommand($"-L {account} {pass}");
4490
}
4591

4692
/// <summary>
47-
/// This method start's the execution of a Instance
93+
/// Sends a command to install an asset on the Coreflux server.
4894
/// </summary>
49-
/// <param name="id"></param>
50-
/// <returns></returns>
51-
/// <exception cref="Exception"></exception>
52-
public bool StartInstance(string id)
95+
/// <param name="assetName">The name of the asset to install.</param>
96+
public void InstallAsset(string assetName)
5397
{
54-
if (FindAppInInstances(id))
55-
{
56-
// VERBS: start, stop, run, install, uninstall
57-
string response = _communicationService.PostInformation(string.Format("https://{0}:9501/CorefluxCentral/instances/{1}/start", _ip, id));
58-
return string.IsNullOrEmpty(response) ? true : throw new Exception(response);
59-
}
60-
return false;
61-
}
98+
SendCommand($"-I {assetName}");
6299

100+
}
63101
/// <summary>
64-
/// This method stop's the execution of a Instance
102+
/// Sends a command to list all assets on the Coreflux server.
65103
/// </summary>
66-
/// <param name="id"></param>
67-
/// <returns></returns>
68-
/// <exception cref="Exception"></exception>
69-
public bool StopInstance(string id)
104+
public void ListAssets()
70105
{
71-
if (FindAppInInstances(id))
72-
{
73-
var response = _communicationService.PostInformation(string.Format("https://{0}:9501/CorefluxCentral/instances/{1}/stop", _ip, id));
74-
return string.IsNullOrEmpty(response) ? true : throw new Exception(response);
75-
}
76-
return false;
106+
SendCommand("-l");
77107
}
78108

79-
private bool FindAppInInstances(string instance)
109+
/// <summary>
110+
/// Sends a command to uninstall an asset on the Coreflux server.
111+
/// </summary>
112+
/// <param name="assetGuid">The GUID of the asset to uninstall.</param>
113+
public void UninstallAsset(string assetInstanceGuid)
80114
{
81-
AppInstance[] apps = GetInstances();
82-
if (apps == null)
83-
return false;
115+
SendCommand($"-U {assetInstanceGuid}");
116+
}
84117

85-
foreach (AppInstance app in apps)
86-
if (app.code.Equals(instance))
87-
return true;
118+
/// <summary>
119+
/// Sends a command to stop an asset instance on the Coreflux server.
120+
/// </summary>
121+
/// <param name="assetInstanceGuid">The GUID of the asset instance to stop.</param>
122+
public void StopInstance(string assetInstanceGuid)
123+
{
124+
SendCommand($"-S {assetInstanceGuid}");
125+
}
88126

89-
return false;
127+
/// <summary>
128+
/// Sends a command to start an asset instance on the Coreflux server.
129+
/// </summary>
130+
/// <param name="assetInstanceGuid">The GUID of the asset instance to start.</param>
131+
public void StartAsset(string assetInstanceGuid)
132+
{
133+
SendCommand($"-R {assetInstanceGuid}");
90134
}
135+
91136
}
137+
138+
139+
92140
}

CorefluxCSharpAPI/API/Models/Enums/Version.cs

+1-1
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,6 @@
33
public enum CommunicationVersion
44
{
55
LegacyHTTPS,
6-
MQTTJWT
6+
MQTT
77
}
88
}

CorefluxCSharpAPI/CFDataModels.cs

+3-82
Original file line numberDiff line numberDiff line change
@@ -9,61 +9,7 @@
99
namespace Coreflux.API.DataModels
1010
{
1111

12-
#region JsonConverter for ParameterType
13-
14-
//public class ParameterTypeConverter : JsonConverter
15-
//{
16-
// public override bool CanConvert(Type objectType)
17-
// {
18-
// return typeof(ParameterType).IsAssignableFrom(objectType);
19-
// }
20-
21-
// public override object ReadJson(JsonReader reader,
22-
// Type objectType, object existingValue, JsonSerializer serializer)
23-
// {
24-
// JObject jo = JObject.Load(reader);
25-
// //var JTokenValue = jo.GetValue("Value");
26-
// var JTokenValue = jo.ToString();
27-
28-
// bool? isParameterType = (bool?)jo["type"];
29-
30-
// ParameterType item = new ParameterType();
31-
32-
// if (JTokenValue.Equals("{\r\n \"Value\": \"String\"\r\n}"))
33-
// {
34-
// item = new ParameterType("String");
35-
// }
36-
// else if (JTokenValue.Equals("{\r\n \"Value\": \"Bool\"\r\n}"))
37-
// {
38-
// item = new ParameterType("Bool");
39-
// }
40-
// else if (JTokenValue.Equals("{\r\n \"Value\": \"Int\"\r\n}"))
41-
// {
42-
// item = new ParameterType("Int");
43-
// }
44-
// else if (JTokenValue.Equals("{\r\n \"Value\": \"Float\"\r\n}"))
45-
// {
46-
// item = new ParameterType("Float");
47-
// }
48-
49-
// serializer.Populate(jo.CreateReader(), item);
50-
51-
// return item;
52-
// }
53-
54-
// public override bool CanWrite
55-
// {
56-
// get { return false; }
57-
// }
58-
59-
// public override void WriteJson(JsonWriter writer,
60-
// object value, JsonSerializer serializer)
61-
// {
62-
// throw new NotImplementedException();
63-
// }
64-
//}
65-
66-
#endregion
12+
6713

6814

6915
public class User
@@ -79,7 +25,7 @@ public class User
7925
public string name { get; set; } = "";
8026
}
8127

82-
[DataContract]
28+
8329
public class LoginData
8430
{
8531

@@ -225,32 +171,7 @@ public string getMedia(mediaType type)
225171
}
226172
}
227173

228-
//public class AppStore : App
229-
//{
230-
// [DataMember]
231-
// public bool dataAvaible { get; set; }
232-
// [DataMember]
233-
// public string storeID { get; set; } = "";
234-
// [DataMember]
235-
// public int accountMaxQty { get; set; }
236-
// [DataMember]
237-
// public float discount { get; set; }
238-
// [DataMember]
239-
// public float price { get; set; }
240-
241-
// [DataMember]
242-
// public string itemRef { get; set; } = null;
243-
244-
// [DataMember]
245-
// public float taxValue { get; set; }
246-
247-
// public StoreElemGUI myGameObject;
248-
249-
// public float GetPrice()
250-
// {
251-
// return this.price * (1 + this.taxValue);
252-
// }
253-
//}
174+
254175

255176

256177
public class Parameter

CorefluxCSharpAPI/obj/CorefluxCSharpAPI.csproj.nuget.dgspec.json

+11-13
Original file line numberDiff line numberDiff line change
@@ -1,31 +1,28 @@
11
{
22
"format": 1,
33
"restore": {
4-
"C:\\Users\\carlo\\Desktop\\CorefluxMQTTcSharpAPI\\CorefluxCSharpAPI\\CorefluxCSharpAPI.csproj": {}
4+
"D:\\Docs\\2-Products\\CorefluxMQTTcSharpAPI\\CorefluxCSharpAPI\\CorefluxCSharpAPI.csproj": {}
55
},
66
"projects": {
7-
"C:\\Users\\carlo\\Desktop\\CorefluxMQTTcSharpAPI\\CorefluxCSharpAPI\\CorefluxCSharpAPI.csproj": {
7+
"D:\\Docs\\2-Products\\CorefluxMQTTcSharpAPI\\CorefluxCSharpAPI\\CorefluxCSharpAPI.csproj": {
88
"version": "1.3.2",
99
"restore": {
10-
"projectUniqueName": "C:\\Users\\carlo\\Desktop\\CorefluxMQTTcSharpAPI\\CorefluxCSharpAPI\\CorefluxCSharpAPI.csproj",
10+
"projectUniqueName": "D:\\Docs\\2-Products\\CorefluxMQTTcSharpAPI\\CorefluxCSharpAPI\\CorefluxCSharpAPI.csproj",
1111
"projectName": "CorefluxMQTTcSharpAPI",
12-
"projectPath": "C:\\Users\\carlo\\Desktop\\CorefluxMQTTcSharpAPI\\CorefluxCSharpAPI\\CorefluxCSharpAPI.csproj",
13-
"packagesPath": "C:\\Users\\carlo\\.nuget\\packages\\",
14-
"outputPath": "C:\\Users\\carlo\\Desktop\\CorefluxMQTTcSharpAPI\\CorefluxCSharpAPI\\obj\\",
12+
"projectPath": "D:\\Docs\\2-Products\\CorefluxMQTTcSharpAPI\\CorefluxCSharpAPI\\CorefluxCSharpAPI.csproj",
13+
"packagesPath": "C:\\Users\\hugo.vaz\\.nuget\\packages\\",
14+
"outputPath": "D:\\Docs\\2-Products\\CorefluxMQTTcSharpAPI\\CorefluxCSharpAPI\\obj\\",
1515
"projectStyle": "PackageReference",
16-
"fallbackFolders": [
17-
"C:\\Program Files (x86)\\Microsoft Visual Studio\\Shared\\NuGetPackages"
18-
],
1916
"configFilePaths": [
20-
"C:\\Users\\carlo\\AppData\\Roaming\\NuGet\\NuGet.Config",
21-
"C:\\Program Files (x86)\\NuGet\\Config\\Microsoft.VisualStudio.FallbackLocation.config",
17+
"C:\\Users\\hugo.vaz\\AppData\\Roaming\\NuGet\\NuGet.Config",
2218
"C:\\Program Files (x86)\\NuGet\\Config\\Microsoft.VisualStudio.Offline.config"
2319
],
2420
"originalTargetFrameworks": [
2521
"netstandard2.0"
2622
],
2723
"sources": {
2824
"C:\\Program Files (x86)\\Microsoft SDKs\\NuGetPackages\\": {},
25+
"http://192.168.100.32:5555/v3/index.json": {},
2926
"https://api.nuget.org/v3/index.json": {}
3027
},
3128
"frameworks": {
@@ -65,11 +62,12 @@
6562
"net47",
6663
"net471",
6764
"net472",
68-
"net48"
65+
"net48",
66+
"net481"
6967
],
7068
"assetTargetFallback": true,
7169
"warn": true,
72-
"runtimeIdentifierGraphPath": "C:\\Program Files\\dotnet\\sdk\\6.0.201\\RuntimeIdentifierGraph.json"
70+
"runtimeIdentifierGraphPath": "C:\\Program Files\\dotnet\\sdk\\7.0.203\\RuntimeIdentifierGraph.json"
7371
}
7472
}
7573
}

CorefluxCSharpAPI/obj/CorefluxCSharpAPI.csproj.nuget.g.props

+3-4
Original file line numberDiff line numberDiff line change
@@ -5,12 +5,11 @@
55
<RestoreTool Condition=" '$(RestoreTool)' == '' ">NuGet</RestoreTool>
66
<ProjectAssetsFile Condition=" '$(ProjectAssetsFile)' == '' ">$(MSBuildThisFileDirectory)project.assets.json</ProjectAssetsFile>
77
<NuGetPackageRoot Condition=" '$(NuGetPackageRoot)' == '' ">$(UserProfile)\.nuget\packages\</NuGetPackageRoot>
8-
<NuGetPackageFolders Condition=" '$(NuGetPackageFolders)' == '' ">C:\Users\carlo\.nuget\packages\;C:\Program Files (x86)\Microsoft Visual Studio\Shared\NuGetPackages</NuGetPackageFolders>
8+
<NuGetPackageFolders Condition=" '$(NuGetPackageFolders)' == '' ">C:\Users\hugo.vaz\.nuget\packages\</NuGetPackageFolders>
99
<NuGetProjectStyle Condition=" '$(NuGetProjectStyle)' == '' ">PackageReference</NuGetProjectStyle>
10-
<NuGetToolVersion Condition=" '$(NuGetToolVersion)' == '' ">6.1.0</NuGetToolVersion>
10+
<NuGetToolVersion Condition=" '$(NuGetToolVersion)' == '' ">6.5.0</NuGetToolVersion>
1111
</PropertyGroup>
1212
<ItemGroup Condition=" '$(ExcludeRestorePackageImports)' != 'true' ">
13-
<SourceRoot Include="C:\Users\carlo\.nuget\packages\" />
14-
<SourceRoot Include="C:\Program Files (x86)\Microsoft Visual Studio\Shared\NuGetPackages\" />
13+
<SourceRoot Include="C:\Users\hugo.vaz\.nuget\packages\" />
1514
</ItemGroup>
1615
</Project>

0 commit comments

Comments
 (0)