public void MutiTierTest() { CoapClient client = new CoapClient(new Uri($"coap://localhost:{_port}/ps")); Response resp = client.Get(); Assert.AreEqual(StatusCode.Content, resp.StatusCode); Assert.AreEqual(MediaType.ApplicationLinkFormat, resp.ContentType); List <WebLink> links = LinkFormat.Parse(resp.PayloadString).ToList(); Assert.AreEqual(0, links.Count); resp = client.Post($"<middle>;ct={MediaType.ApplicationLinkFormat}", MediaType.ApplicationLinkFormat); Assert.AreEqual(StatusCode.Created, resp.StatusCode); Assert.AreEqual("ps/middle", resp.LocationPath); client.UriPath = "/ps/middle"; resp = client.Post($"<topic1>;ct={MediaType.TextPlain}", MediaType.ApplicationLinkFormat); Assert.AreEqual(StatusCode.Created, resp.StatusCode); Assert.AreEqual("ps/middle/topic1", resp.LocationPath); resp = client.Post($"<topic2>;ct={MediaType.ApplicationCbor}", MediaType.ApplicationLinkFormat); Assert.AreEqual(StatusCode.Created, resp.StatusCode); Assert.AreEqual("ps/middle/topic2", resp.LocationPath); client.UriPath = ""; resp = client.Get(); Assert.AreEqual(StatusCode.Content, resp.StatusCode); Assert.AreEqual(MediaType.ApplicationLinkFormat, resp.ContentType); links = LinkFormat.Parse(resp.PayloadString).ToList(); Assert.AreEqual(3, links.Count); string[] linkStrings = resp.PayloadString.Split(','); Assert.Contains("</ps/middle/topic2>;ct=60;obs", linkStrings); Assert.Contains("</ps/middle/topic1>;ct=0;obs", linkStrings);; }
public void PivExhaustion() { SecurityContext context = SecurityContext.DeriveGroupContext(secret, groupId1, clientId, AlgorithmValues.EdDSA, _clientSign1, null, null); SecurityContext context2 = SecurityContext.DeriveGroupContext(secret2, groupId2, clientId, AlgorithmValues.EdDSA, _clientSign1, null, null); for (int i = 0; i < 10; i++) { context.Sender.IncrementSequenceNumber(); } context.Sender.MaxSequenceNumber = 10; context.OscoreEvents += ClientEventHandler; CoapClient client = new CoapClient($"coap://localhost:{_serverPort}/abc") { OscoreContext = context, Timeout = 20 }; Response r = client.Get(); Assert.IsTrue(trigger.WaitOne(1000)); Assert.AreEqual(OscoreEvent.EventCode.PivExhaustion, _clientCallbackCode); _clientEventChoice = 1; client.Timeout = 1000 * 60; r = client.Get(); Assert.AreEqual(OscoreEvent.EventCode.UnknownGroupIdentifier, _callbackCode); }
/// <summary> /// Queries all existing devices known by the LAN controller /// </summary> /// <returns></returns> public static List <TradfriDevice> GetDevices() { _coapClient.UriPath = $"{CommandConstants.UniqueDevices}/"; Response response = _coapClient.Get(); var deviceIds = Newtonsoft.Json.JsonConvert.DeserializeObject <List <int> >(response.PayloadString); return(deviceIds.Select(GetDevice).ToList()); }
public void GetUnicastV6() { Uri uri; CoapClient client; Response response; IPAddress[] addresses = Dns.GetHostAddresses("localhost"); IPAddress addr = null; foreach (IPAddress a in addresses) { if (a.AddressFamily == AddressFamily.InterNetworkV6) { addr = a; break; } } uri = new Uri($"coap://[{addr}]:{_serverPort}/{UnicastTarget}"); client = new CoapClient(uri); response = client.Get(); Assert.IsNotNull(response); Assert.AreEqual(UnicastResponse, response.ResponseText); }
static void RunTest15(string[] cmds) { // Do it as a third party. CoapClient cl = new CoapClient(Program.Host) { UriPath = ResourceLookup, Timeout = 20 * 1000 }; Response r1 = cl.Get(MediaType.ApplicationLinkFormat); if (r1 == null) { Console.WriteLine("No response message retrieved"); return; } if (r1.StatusCode != StatusCode.Content) { Console.WriteLine("Incorrect return code"); } if (r1.StatusCode < StatusCode.BadRequest) { if (r1.ContentFormat != MediaType.ApplicationLinkFormat) { Console.WriteLine("Incorrect Media Type"); } } Console.WriteLine(Utils.ToString(r1)); }
private static async Task TestGet_ApiCoap() { var client = new CoapClient(); client.Uri = new Uri("coap://localhost:5683/helloworld"); var res = client.Get(); Console.WriteLine(res.ResponseText); }
// Use Security Context A static void RunTest3() { CoapClient request = new CoapClient(Program.Host + "/oscore/hello/2?first=1") { Timeout = 2000, OscoreContext = _oscoreContext }; Response response = request.Get(); if (response == null) { Console.WriteLine("Failed to receive response"); return; } if (response.StatusCode != StatusCode.Content) { Console.WriteLine("Content type should be 2.05 not ${response.StatusCode}"); } if (response.HasOption(OptionType.ContentType)) { if (response.ContentType != MediaType.TextPlain) { Console.WriteLine($"Content type is set to {response.ContentType} and not 0"); } } else { Console.WriteLine("Content Type is missing"); } if (response.HasOption(OptionType.ETag)) { if (response.ETags.Count() != 1) { Console.WriteLine("Number of ETags is incorrect"); } if (!response.ContainsETag(new byte[] { 0x2b })) { Console.WriteLine("Missing ETag = 0x2b"); } } else { Console.WriteLine("ETag is missing"); } if (!response.PayloadString.Equals("Hello World!")) { Console.WriteLine("Content value is wrong"); } Console.WriteLine($"Response Message:\n{Utils.ToString(response)}"); }
public void Ocoap_Get() { CoapClient client = new CoapClient($"coap://localhost:{_serverPort}/abc") { OscoreContext = SecurityContext.DeriveContext(_Secret, null, _ClientId, _ServerId) }; Response r = client.Get(); Assert.AreEqual("/abc", r.PayloadString); }
public void TestUnicastOfMulticastResource() { Uri uri; CoapClient client; Response response; uri = new Uri($"coap://localhost:{_serverPort}/{MulticastTarget}"); client = new CoapClient(uri); response = client.Get(); Assert.IsNotNull(response); Assert.AreEqual(StatusCode.MethodNotAllowed, response.StatusCode); }
static void RunTest4() { CoapClient request = new CoapClient(Program.Host + "/oscore/hello/3") { Timeout = 2000, OscoreContext = _oscoreContext }; Response response = request.Get(MediaType.TextPlain); if (response == null) { Console.WriteLine("Failed to receive response"); return; } if (response.StatusCode != StatusCode.Content) { Console.WriteLine($"Content type should be 2.05 not {response.StatusCode}"); } if (response.HasOption(OptionType.ContentType)) { if (response.ContentType != MediaType.TextPlain) { Console.WriteLine($"Content type is set to {response.ContentType} and not 0"); } } else { Console.WriteLine("Content Type is missing"); } if (response.HasOption(OptionType.MaxAge)) { if (response.MaxAge != 5) { Console.WriteLine($"Max age is {response.MaxAge} not 5"); } } else { Console.WriteLine("MaxAge is missing"); } if (!response.PayloadString.Equals("Hello World!")) { Console.WriteLine("Content value is wrong"); } Console.WriteLine($"Response Message:\n{Utils.ToString(response)}"); }
public void TestMethod1() { Uri uri = new Uri("coap+tls://localhost:" + _serverPort.ToString() + "/hello"); CoapClient client = new CoapClient(uri); TcpEndPoint ep = new TcpEndPoint(); ep.Start(); client.EndPoint = ep; Response resp = client.Get(); Assert.AreEqual(resp.StatusCode, StatusCode.Content); }
static void Main(string[] args) { Thread.Sleep(1000); CoapClient client = new CoapClient() { Uri = new Uri("coap://localhost"), UriPath = "/ps" }; Response resp = client.Get(); Console.WriteLine($"Discover ==> {resp.ToString()}"); resp = client.Post("<topic1>;ct=40", MediaType.ApplicationLinkFormat); Console.WriteLine($"Create topic1 ==> {resp.ToString()}"); client.UriPath = "/ps/topic1"; resp = client.Post("<subtopic1>;ct=0;rt=temperature;obs", MediaType.ApplicationLinkFormat); Console.WriteLine($"Create subtopic1 ==> {resp.ToString()}"); client.UriPath = "/ps"; resp = client.Get(); Console.WriteLine($"Discover ==> {resp.PayloadString}"); client.UriPath = "/ps/topic1/subtopic1"; resp = client.Post("Payload #1", MediaType.TextPlain); Console.WriteLine($"Post #1 ==> {resp.ToString()}"); resp = client.Post("Payload #2", MediaType.TextPlain); Console.WriteLine($"Post #2 ==> {resp.ToString()}"); resp = client.Post("Payload #3", MediaType.TextXml); Console.WriteLine($"Post #2 ==> {resp.ToString()}"); }
static void TestCall() { // Create a new client var client = new CoapClient(); // Set the Uri to visit client.Uri = new Uri("coap://192.168.0.101:5683/test"); // Get JSON object from example product var response = client.Get(); // Get the response Console.WriteLine("Response from GET: {0}", response.PayloadString); Console.ReadLine(); }
public void TestSharedSecret() { Request req; Uri uriHello = new Uri("coap://localhost:" + _serverPort + "/hello"); Uri uri = new Uri("coap://localhost:" + _serverPort + "/" + "edhoc"); CoapClient clientHello = new CoapClient(uriHello); CoapClient client = new CoapClient(uri); // Try and get hello -- should fail because no security setup. CoAP.Response resp = clientHello.Get(); Assert.AreEqual(CoAP.StatusCode.Unauthorized, resp.StatusCode); // Create and send message #1 for PSK EDHOC.EdhocInitiator init = new EdhocInitiator(psk); byte[] msg = init.CreateMessage1(); req = new Request(Method.POST); req.Payload = msg; resp = client.Send(req); Assert.AreEqual(CoAP.StatusCode.Changed, resp.StatusCode); // Process response message KeySet ks = new KeySet(); ks.AddKey(serverSignKey); init.ParseMessage2(resp.Payload, ks); // Post new message msg = init.CreateMessage3(); req = new Request(Method.POST); req.Payload = msg; resp = client.Send(req); Assert.AreEqual(StatusCode.Changed, resp.StatusCode); // Setup my security context. OSCOAP.SecurityContext ctx = init.CreateSecurityContext(); req = new Request(Method.GET); req.URI = uriHello; req.OscoapContext = ctx; resp = clientHello.Send(req); Assert.AreEqual(StatusCode.Content, resp.StatusCode); }
public void NoGroupId() { SecurityContext context = SecurityContext.DeriveGroupContext(secret, groupId1, clientId, AlgorithmValues.EdDSA, _clientSign1, null, null); CoapClient client = new CoapClient($"coap://localhost:{_serverPort}/abc") { OscoreContext = context, // Timeout = 60 }; Console.WriteLine($"--Server port = {_serverPort}"); Response r = client.Get(); Assert.AreEqual(OscoreEvent.EventCode.UnknownGroupIdentifier, _callbackCode); }
public void SetGroupId() { SecurityContext context = SecurityContext.DeriveGroupContext(secret, groupId1, clientId, AlgorithmValues.EdDSA, _clientSign1, new byte[][] { serverId }, new OneKey[] { _serverSign1 }); CoapClient client = new CoapClient($"coap://localhost:{_serverPort}/abc") { OscoreContext = context, Timeout = 60 * 1000 }; Console.WriteLine($"--Server port = {_serverPort}"); _serverEventChoice = 1; Response r = client.Get(); Assert.IsNotNull(r); Assert.AreEqual("/abc", r.PayloadString); }
public void MissingKeyId() { SecurityContext context = SecurityContext.DeriveGroupContext(secret, groupId1, clientId, AlgorithmValues.EdDSA, _clientSign1, new byte[][] { serverId }, new OneKey[] { _serverSign1 }); SecurityContext serverContext = SecurityContext.DeriveGroupContext(secret, groupId1, serverId, AlgorithmValues.EdDSA, _serverSign1, new byte[][] { clientId2 }, new OneKey[] { _clientSign2 }); _server.SecurityContexts.Add(serverContext); serverContext.OscoreEvents += ServerEventHandler; CoapClient client = new CoapClient($"coap://localhost:{_serverPort}/abc") { OscoreContext = context, Timeout = 60 * 1000 }; _serverEventChoice = 0; Response r = client.Get(); Assert.AreEqual(OscoreEvent.EventCode.UnknownKeyIdentifier, _callbackCode); }
static void RunTest5_2_2() { CoapClient request = new CoapClient(Program.Host + "/oscore/hello/1") { Timeout = 2000, OscoreContext = _oscoreContext }; _oscoreContext.Sender.BaseIV[_oscoreContext.Sender.BaseIV.Length - 1] -= 1; Response response = request.Get(); if (response == null) { Console.WriteLine("Failed to receive response"); return; } if (response.StatusCode != StatusCode.Changed) { Console.WriteLine($"Content type should be 2.04 not {response.StatusCode}"); } if (response.PayloadSize != 1 || response.Payload[0] != 0x4a) { Console.WriteLine("Payload for the package is wrong - should be 0x4a"); } Console.WriteLine($"Response Message:\n{Utils.ToString(response)}"); request = new CoapClient(Program.Host + "/oscore/hello/1") { Timeout = 2000, OscoreContext = _oscoreContext }; response = request.Get(); }
public void SupplyMissingKeyId() { SecurityContext context = SecurityContext.DeriveGroupContext(secret, groupId1, clientId, AlgorithmValues.EdDSA, _clientSign1, new byte[][] { serverId }, new OneKey[] { _serverSign1 }); SecurityContext serverContext = SecurityContext.DeriveGroupContext(secret, groupId1, serverId, AlgorithmValues.EdDSA, _serverSign1, new byte[][] { clientId2 }, new OneKey[] { _clientSign2 }); _server.SecurityContexts.Add(serverContext); serverContext.OscoreEvents += ServerEventHandler; CoapClient client = new CoapClient($"coap://localhost:{_serverPort}/abc") { OscoreContext = context, Timeout = 60 * 1000 }; _serverEventChoice = 2; Response r = client.Get(); Assert.IsNotNull(r); Assert.AreEqual("/abc", r.PayloadString); }
private static void RunTest1(string[] cmds) { // Multicast Request // NON GET /.well-known/core?rt=core.rd // Accept=40 Console.WriteLine("We don't do multicast for clients or servers at this time"); CoapClient cl = new CoapClient(Program.Host) { UriPath = "/.well-known/core", UriQuery = "rt=core.rd", Timeout = 20 * 1000 }; cl.UseNONs(); Response r1 = cl.Get(MediaType.ApplicationLinkFormat); if (r1 == null) { Console.WriteLine("No response message retrieved"); return; } if (r1.StatusCode != StatusCode.Content) { Console.WriteLine("Incorrect return code"); } if (r1.StatusCode < StatusCode.BadRequest) { if (r1.ContentFormat != MediaType.ApplicationLinkFormat) { Console.WriteLine("Incorrect Media Type"); } } Console.WriteLine(Utils.ToString(r1)); }
public void ServerIvExhaustion() { SecurityContext context = SecurityContext.DeriveGroupContext(secret, groupId1, clientId, AlgorithmValues.EdDSA, _clientSign1, new byte[][] { serverId }, new OneKey[] { _serverSign1 }); SecurityContext serverContext = SecurityContext.DeriveGroupContext(secret, groupId1, serverId, AlgorithmValues.EdDSA, _serverSign1, new byte[][] { clientId2, clientId }, new OneKey[] { _clientSign2, _clientSign1 }); _server.SecurityContexts.Add(serverContext); serverContext.OscoreEvents += ServerEventHandler; for (int i = 0; i < 10; i++) { serverContext.Sender.IncrementSequenceNumber(); } serverContext.Sender.MaxSequenceNumber = 10; CoapClient client = new CoapClient($"coap://localhost:{_serverPort}/abc") { OscoreContext = context, Timeout = 60 * 1000 }; _serverEventChoice = 0; Response r = client.Get(); Assert.IsNotNull(r); Assert.AreEqual("/abc", r.PayloadString); client = new CoapClient($"coap://localhost:{_serverPort}/abc") { OscoreContext = context, Timeout = 30 * 1000, }; client.Observe(); Assert.AreEqual(OscoreEvent.EventCode.PivExhaustion, _callbackCode); }
/// <summary> /// Initializes the connection with the LAN controller /// </summary> /// <param name="endPoint">IP endpoint of the IKEA Tradfri LAN Controller</param> /// <param name="securityKey">Private security key found on the bottom of the LAN Controller</param> public static void InitializeConnection(IPEndPoint endPoint, string securityKey) { if (endPoint == null) { throw new ArgumentNullException(nameof(endPoint)); } if (string.IsNullOrWhiteSpace(securityKey)) { throw new ArgumentNullException(nameof(securityKey)); } try { _controllerAddress = endPoint; _connectionSecurityKey = securityKey; OneKey userKey = new OneKey(); userKey.Add(CoseKeyKeys.KeyType, GeneralValues.KeyType_Octet); userKey.Add(CoseKeyParameterKeys.Octet_k, CBORObject.FromObject(Encoding.UTF8.GetBytes(_connectionSecurityKey))); CoAPEndPoint coapEndPoint = new DTLSClientEndPoint(userKey); _coapClient = new CoapClient(new Uri($"coaps://{_controllerAddress.Address}:{_controllerAddress.Port}/")) { EndPoint = coapEndPoint }; coapEndPoint.Start(); // there has to be a GET operation to successfully open the connection _coapClient.UriPath = CommandConstants.UniqueDevices + "/"; _coapClient.Get(); } catch (Exception ex) { Console.WriteLine(ex.Message); } }
static void Main(string[] args) { Com.AugustCellars.CoAP.Log.LogManager.Level = LogLevel.None; ; String Server = "192.168.53.55:5684"; OneKey userKey = new OneKey(); userKey.Add(CoseKeyKeys.KeyType, GeneralValues.KeyType_Octet); //userKey.Add(CoseKeyParameterKeys.Octet_k, CBORObject.FromObject(Encoding.UTF8.GetBytes("sesame"))); // userKey.Add(CoseKeyKeys.KeyIdentifier, CBORObject.FromObject(Encoding.UTF8.GetBytes("password"))); CoapClient client = new CoapClient(new Uri($"coaps://{Server}/.well-known/core")); CoAPEndPoint ep = new DTLSClientEndPoint(userKey); client.EndPoint = ep; ep.Start(); // Response r1 = client.Get(); Console.WriteLine("Links = " + r1.PayloadString); // // string str = "<//15001/65536>;ct=0;obs,<//15001/65537>;ct=0;obs,<//15004/136834>;ct=0;obs,<//15005/136834/217609>;ct=0;obs,<//15005/136834/218326>;ct=0;obs,<//15005/136834/224384>;ct=0;obs,<//15005/136834>;ct=0;obs,<//15001>;ct=0;obs,<//15001/reset>;ct=0,<//status>;ct=0;obs,<//15005>;ct=0;obs,<//15004>;ct=0;obs,<//15004/add>;ct=0,<//15004/remove>;ct=0,<//15006>;ct=0;obs,<//15011/15012>;ct=0;obs,<//15011/9034>;ct=0,<//15011/9030>;ct=0,<//15011/9031>;ct=0,<//15011/9063>;ct=0,<//15011/9033>;ct=0,<//15010>;ct=0;obs"; // IEnumerable<WebLink> links = LinkFormat.Parse(str); // foreach(var item in links) Console.WriteLine(item); // LogManager.Level = LogLevel.None; IEnumerable <WebLink> items = client.Discover(); foreach (var node in items) { Console.WriteLine($"Resource = {node}"); client.UriPath = node.Uri; if (false && node.Attributes.Observable) { CoapClient c2 = new CoapClient() { EndPoint = client.EndPoint, Uri = client.Uri, UriPath = node.Uri }; Console.WriteLine("Observe it"); CoapObserveRelation relation1 = c2.Observe(r => { EventIn(node.Uri, r); }); } else { Response response = client.Get(); Console.WriteLine(" Payload: " + response.PayloadString); Console.WriteLine(); } } client.Uri = new Uri($"coaps://{Server}"); client.UriPath = "/15004/166412"; client.Get(); Response rep = client.Put("{ \"5850\":1}"); Thread.Sleep(3000); //rep = client.Get(); Console.WriteLine(rep.PayloadString); client.UriPath = "/15001/65537"; ; for (int i = 0; i < 10; i++) { Thread.Sleep(3000); client.Put("{ \"5851\":127}"); Thread.Sleep(3000); client.Put("{ \"3311\":[{ \"5851\":0}]}"); Thread.Sleep(3000); client.Put("{ \"3311\":[{ \"5851\":255}]}"); } ep.Stop(); }
public static Response GetValues(this CoapClient _client, TradFriRequest request) { _client.UriPath = request.UriPath; return(_client.Get()); }
private static void RunTest3(string[] cmds) { // Simple registration - RdServer server = new RdServer(); server.Start(); server.PostTo(); Thread.Sleep(20 * 1000); server.Stop(); CoapClient cl = new CoapClient(Program.Host) { UriPath = EndpointLookup, UriQuery = "ep=node1", Timeout = 20 * 1000 }; Response r1 = cl.Get(MediaType.ApplicationLinkFormat); if (r1 != null && r1.StatusCode == StatusCode.Content) { string ss = r1.PayloadString.Substring(1); int i = ss.IndexOf('>'); Test3Location = ss.Substring(0, i); } Console.WriteLine("Test 3 done"); #if false if (cmds.Length == 2) { // Do it as a third party. CoapClient cl = new CoapClient(Program.Host) { UriPath = "/rd", Timeout = 20 * 1000, UriQuery = "lt=6000&ep=node1" }; Response r1 = cl.Post( "</sensors/temp>;ct=41;rt=\"temperature-c\";if=sensor;anchor=\"coap://spurious.example.com:5683\"," + "</sensors/light>;ct=41;rt=\"light-lux\";if=sensor", MediaType.ApplicationLinkFormat); if (r1 == null) { Console.WriteLine("No response message retrieved"); return; } Test3Location = r1.LocationPath; return; } if (cmds.Length != 4) { Console.WriteLine("Should be 'rd_test 1 <server to do Simple Registration> <endpoint name>'"); return; } CoapClient client = new CoapClient(cmds[2]) { UriPath = "/rd/post2", Timeout = 20 * 1000 }; Response r = client.Post(Program.Host.ToString() + " " + cmds[3]); if (r == null) { Console.WriteLine("No response message retrieved"); return; } else if (r.Code != (int)StatusCode.Changed) { Console.WriteLine("Unexpected status code {0}.{1} returned", r.Code / 32, r.Code % 32); return; } #endif }