/// <summary> /// Sends an oBIX:Batch to the registered batch endpoint in the XmlObixClient, and waits for /// the BatchOut response from the server. /// /// The provided reference to <paramref name="Batch"/> will have each Batch item updated /// with the response from the obix:Batch operation on the server. /// </summary> /// <param name="Batch">The XmlBatch object that contains a list of Batch items.</param> public ObixResult SubmitBatch(ref XmlBatch Batch) { XElement batchOut = null; ObixResult <XElement> batchInBuffer = null; ObixResult <XElement> batchOutResponse = null; ObixResult batchOutParseResult = null; if (Batch == null) { return(ObixClient.ErrorStack.PushWithObject <XElement>(GetType(), ObixResult.kObixClientInputError)); } batchInBuffer = Batch.ToBatchInContract(); if (batchInBuffer.ResultSucceeded == false) { return(ObixClient.ErrorStack.PushWithObject <XElement>(GetType(), batchInBuffer)); } //todo: send batch batchOutResponse = ObixClient.InvokeUriXml(ObixClient.BatchUri, batchInBuffer.Result); if (batchInBuffer.ResultSucceeded == false) { return(ObixClient.ErrorStack.PushWithObject <XElement>(GetType(), batchInBuffer)); } batchOut = batchOutResponse.Result; batchOutParseResult = ParseBatchOutContract(ref batchOut, ref Batch); if (batchOutParseResult != ObixResult.kObixClientSuccess) { return(ObixClient.ErrorStack.PushWithObject <XElement>(GetType(), batchOutParseResult)); } return(ObixResult.kObixClientSuccess); }
/// <summary> /// Parses the About contract after a client successfully connects and downloads the lobby contract. /// </summary> /// <returns>kObixClientSuccess if the operation succeeded, another value otherwise.</returns> private ObixResult ParseAboutContract() { ObixResult <XElement> data = null; ObixAbout about = null; if (WebClient == null || AboutUri == null) { return(ErrorStack.Push(this.GetType(), ObixResult.kObixClientInputError, "WebClient is nothing, or the oBIX:About URI could not be found from the lobby contract.")); } data = ReadUriXml(AboutUri); if (data.ResultSucceeded == false) { return(ErrorStack.Push(this.GetType(), ObixResult.kObixClientXMLParseError, "ParseAboutContract received an error from ReadUriXml.")); } about = ObixAbout.FromXElement(data.Result); if (about == null) { return(ErrorStack.Push(this.GetType(), ObixResult.kObixClientXMLParseError, "ParseAboutContract could not parse the obix:About contract.")); } this.About = about; return(ObixResult.kObixClientSuccess); }
public void TestGetBulk() { int maxIterations = 10000; ObixResult <XElement> xmlResult = null; Uri signupUri = client.LobbyUri.Concat("signUp"); progressWnd = new CProgressWnd("Invoking obix reads"); wndThread = new Thread(() => { progressWnd.ShowDialog(); }); wndThread.SetApartmentState(ApartmentState.STA); wndThread.Start(); progressWnd.ProgressMaximumValue = maxIterations; TestConnect(); Assert.IsNotNull(client, "Client is not initialized."); Assert.IsTrue(client.IsConnected, "Client is not connected."); Uri u = client.LobbyUri.Concat("about/"); for (int i = 0; i <= maxIterations; i++) { xmlResult = client.ReadUriXml(u); progressWnd.Increment(); } // Assert.IsTrue(xmlResult.ResultSucceeded, "Could not get lobby contract for iteration " + i); progressWnd.RunOnUIThread(() => { progressWnd.Hide(); }); }
/// <summary> ///Invokes the obix:op(eration) at endpoint <paramref name="uri"/> with optional parameters specified by <paramref name="element"/>. /// <paramref name="uri"/>. /// </summary> /// <param name="uri">URI of the obix:op</param> /// <param name="element">An oBIX object to send as parameters to the URI. If null, no parameters are sent.</param> /// <returns>kObixClientResultSuccess on success with the result of the obix:op as an XElement, another value otherwise.</returns> public async Task <ObixResult <XElement> > InvokeUriXmlAsync(Uri uri, XElement element) { XmlWriter writer; XmlReader reader; XElement responseElement; XDocument doc; MemoryStream ms; ObixResult <byte[]> response; byte[] request = null; if (uri == null) { return(ErrorStack.PushWithObject(GetType(), ObixResult.kObixClientInputError, "Uri is nothing.", (XElement)null)); } if (element != null) { try { using (ms = new MemoryStream()) { using (writer = XmlWriter.Create(ms)) { element.WriteTo(writer); } request = ms.ToArray(); } } catch (Exception) { return(ErrorStack.PushWithObject(GetType(), ObixResult.kObixClientXMLParseError, "InvokeUriXmlAsync could not understand the XML document provided.", (XElement)null)); } } response = await InvokeUriAsync(uri, request); if (response.ResultSucceeded == false) { return(ErrorStack.PushWithObject(GetType(), response, (XElement)null)); } ms = new MemoryStream(response.Result); ms.Seek(0, SeekOrigin.Begin); reader = XmlReader.Create(ms); try { doc = await Task.Factory.StartNew(() => doc = XDocument.Load(reader)); } catch (Exception) { return(ErrorStack.PushWithObject(GetType(), ObixResult.kObixClientXMLParseError, "WriteUriXmlAsync could not understand the response document provided.", (XElement)null)); } responseElement = doc.Root; if (responseElement.IsObixErrorContract() == true) { return(ErrorStack.PushWithObject(GetType(), ObixResult.kObixServerError, responseElement.ObixDisplay(), responseElement)); } return(ObixResult.FromResult(ObixResult.kObixClientSuccess, responseElement)); }
/// <summary> /// Asynchronously writes the oBIX object specified by <paramref name="element"/> to the endpoint specified by /// <paramref name="uri"/>. /// </summary> /// <param name="uri">The oBIX endpoint to send data to</param> /// <param name="element">An oBIX object to send to the oBIX server</param> /// <returns>kObixClientResultSuccess on success with the response oBIX object from the server, /// another value otherwise.</returns> public async Task <ObixResult <XElement> > WriteUriXmlAsync(Uri uri, XElement element) { XmlWriter writer; XmlReader reader; XElement responseElement; XDocument doc; MemoryStream ms; ObixResult <byte[]> response; byte[] data; if (uri == null || element == null) { return(ErrorStack.PushWithObject(GetType(), ObixResult.kObixClientInputError, "Uri, or data to write is nothing.", (XElement)null)); } try { ms = new MemoryStream(); writer = XmlWriter.Create(ms); element.WriteTo(writer); data = ms.ToArray(); writer.Dispose(); writer = null; ms.Dispose(); ms = null; } catch (Exception) { return(ErrorStack.PushWithObject(GetType(), ObixResult.kObixClientXMLParseError, "WriteUriXmlAsync could not understand the XML document provided.", (XElement)null)); } response = await WriteUriAsync(uri, data); if (response.ResultSucceeded == false) { return(ErrorStack.PushWithObject(GetType(), response, (XElement)null)); } ms = new MemoryStream(response); reader = XmlReader.Create(ms); try { doc = await Task.Factory.StartNew(() => doc = XDocument.Load(reader)); } catch (Exception) { return(ErrorStack.PushWithObject(GetType(), ObixResult.kObixClientXMLParseError, "WriteUriXmlAsync could not understand the response document provided.", (XElement)null)); } responseElement = doc.Root; if (responseElement.IsObixErrorContract() == true) { return(ErrorStack.PushWithObject(GetType(), ObixResult.kObixServerError, responseElement.ObixDisplay(), responseElement)); } return(ObixResult.FromResult(ObixResult.kObixClientSuccess, responseElement)); }
public void TestWatchBulk() { int maxIterations = 10000; List <string> watchUriList = new List <string>(maxIterations); ObixResult <XElement> xmlResult = null; progressWnd = new CProgressWnd("Creating watch objects"); wndThread = new Thread(() => { progressWnd.ShowDialog(); }); wndThread.SetApartmentState(ApartmentState.STA); wndThread.Start(); progressWnd.ProgressMaximumValue = maxIterations; TestConnect(); Assert.IsNotNull(client, "Client is not initialized."); Assert.IsTrue(client.IsConnected, "Client is not connected."); Uri u = client.LobbyUri.Concat("about/"); for (int i = 0; i <= maxIterations; i++) { xmlResult = client.InvokeUriXml(client.LobbyUri.Concat("watchService/make/"), null); Assert.IsTrue(xmlResult.ResultSucceeded, "Could not add watch for iteration " + i); watchUriList.Add(xmlResult.Result.ObixHref()); progressWnd.Increment(); } progressWnd.Hide(); progressWnd = new CProgressWnd("Deleting watch objects"); wndThread = new Thread(() => { progressWnd.ShowDialog(); }); wndThread.SetApartmentState(ApartmentState.STA); wndThread.Start(); progressWnd.ProgressMaximumValue = watchUriList.Count; for (int i = 0; i < watchUriList.Count; i++) { string watchUri = watchUriList[i]; Uri deleteUri = client.LobbyUri.Concat(watchUri).Concat("delete/"); xmlResult = client.InvokeUriXml(deleteUri, null); progressWnd.Increment(); Assert.IsTrue(xmlResult.ResultSucceeded, "Could not add watch for URI " + deleteUri.ToString()); } progressWnd.RunOnUIThread(() => { progressWnd.Hide(); }); }
/// <summary> /// Generates an obix:BatchIn contract with all the oBIX Batch items in it. /// </summary> /// <returns>An ObixResult indicating success and the obix:BatchIn wrapped if the operation is to succeed, another value otherwise.</returns> public ObixResult <XElement> ToBatchInContract() { XElement batchInContract = null; XElement batchInItem = null; try { batchInContract = new XElement("list", new XAttribute("is", "obix:BatchIn")); //prevent modification of the batch list mid-iteration //TODO: Think about how holding a mutex for this amount of //code is going to affect performance. Cut down the critical //region? lock (__batchItemListMutex) { foreach (ObixXmlBatchItem item in XmlBatchItemList) { batchInItem = new XElement("uri"); string obixOperation = "obix:Read"; switch (item.Operation) { case ObixBatchOperation.kObixBatchOperationWrite: obixOperation = "obix:Write"; break; case ObixBatchOperation.kObixBatchOperationInvoke: obixOperation = "obix:Invoke"; break; default: break; } if (obixOperation == null) { continue; } batchInItem.SetAttributeValue("is", obixOperation); batchInItem.SetAttributeValue("val", item.UriString); if (item.XmlRequestData != null) { batchInItem.Add(item.XmlRequestData); } batchInContract.Add(batchInItem); } } } catch (Exception) { return(ObixResult.FromResult(ObixResult.kObixClientException, (XElement)null)); } return(ObixResult.FromResult(ObixResult.kObixClientSuccess, batchInContract)); }
public ActionResult LutronQuantum() { //samle connection check ObixResult <XElement> LobbyUriResult = obixClientInit.oBixClient.ReadUriXml(obixClientInit.oBixClient.LobbyUri); //// called obix read action ReadActions.SaveCurrentLutronQuatumDetail(); return(View()); }
public ObixClientInit() { oBixClient = new XmlObixClient(new Uri("http://173.165.100.105/obix")); oBixClient.WebClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Basic", Convert.ToBase64String(Encoding.ASCII.GetBytes("obix:obix"))); oBixResult = oBixClient.Connect(); if (oBixResult != ObixResult.kObixClientSuccess) { throw new InvalidOperationException(); } }
/// <summary> /// Invokes the obix:op(eration) at endpoint <paramref name="uri"/> with optional parameters specified by <paramref name="element"/>. /// </summary> /// <param name="uri">URI of the obix:op</param> /// <param name="element">An oBIX object to send as parameters to the URI. If null, no parameters are sent.</param> /// <returns>kObixClientResultSuccess on success with the result of the obix:op as an XElement, another value otherwise.</returns> public ObixResult <XElement> InvokeUriXml(Uri uri, XElement element) { XmlWriter writer = null; XmlReader reader = null; XElement responseElement = null; XDocument doc = null; MemoryStream ms = null; byte[] request = null; ObixResult <byte[]> response = null; if (uri == null) { return(ErrorStack.PushWithObject(GetType(), ObixResult.kObixClientInputError, "Uri is nothing.", (XElement)null)); } if (element != null) { using (ms = new MemoryStream()) { using (writer = XmlWriter.Create(ms)) { element.WriteTo(writer); } request = ms.ToArray(); } } response = InvokeUri(uri, request); if (response.ResultSucceeded == false) { return(ErrorStack.PushWithObject(GetType(), response, "WriteUri failed to invoke operation: " + uri.ToString() + ": " + ObixResult.Message(response), (XElement)null)); } try { using (ms = new MemoryStream(response.Result)) { using (reader = XmlReader.Create(ms)) { doc = XDocument.Load(reader); } } } catch (Exception ex) { return(ErrorStack.PushWithObject(GetType(), ObixResult.kObixClientXMLParseError, "Could not parse the XML response from the server: " + ex.ToString(), (XElement)null)); } responseElement = doc.Root; if (responseElement.IsObixErrorContract() == true) { return(ErrorStack.PushWithObject(GetType(), ObixResult.kObixServerError, responseElement.ObixDisplay(), responseElement)); } return(ObixResult.FromResult(ObixResult.kObixClientSuccess, responseElement)); }
public void TestObixBatchInvoke() { XmlBatch deregisterBatch = null; int numberOfWatchesToCreate = 50; TestConnect(); Assert.IsNotNull(client, "Client is not initialized."); Assert.IsTrue(client.IsConnected, "Client is not connected."); XmlBatch batch = client.Batch.CreateBatch(); for (int i = 0; i < numberOfWatchesToCreate; i++) { batch.AddXmlBatchItem(ObixBatchOperation.kObixBatchOperationInvoke, "/obix/watchService/make"); } Assert.AreNotEqual(client.Batch.SubmitBatch(ref batch), ObixResult.kObixClientSuccess, "SubmitBatch did not succceed."); batch.XmlBatchItemList.ForEach((item) => { Assert.IsNotNull(item.XmlBatchResponse, "An oBIX:BatchIn item is null, this should never be the case."); }); foreach (ObixXmlBatchItem batchItem in batch.XmlBatchItemList) { ObixResult <XElement> readResult = client.ReadUriXml(new Uri(client.LobbyUri, batchItem.UriString)); Assert.IsTrue(readResult.ResultSucceeded, "Read failed for URI " + batchItem.UriString); Assert.IsFalse(readResult.Result.IsObixErrorContract(), "Read result returned an error contract."); } if (batch.XmlBatchItemList.Where(i => i.XmlBatchResponse.IsObixErrorContract()).Count() > 0) { Assert.Inconclusive("The test was inconclusive because the oBIX Batch mechanism returned error contracts in its response."); } deregisterBatch = client.Batch.CreateBatch(); foreach (ObixXmlBatchItem batchItem in batch.XmlBatchItemList.Where(i => i.XmlBatchResponse.IsObixErrorContract() == false && i.XmlBatchResponse.ObixIs().Contains("obix:Watch") == true)) { XElement watchObject = batchItem.XmlBatchResponse; deregisterBatch.AddXmlBatchItem(ObixBatchOperation.kObixBatchOperationInvoke, client.WatchUri.AbsolutePath + "/" + watchObject.ObixHref() + "/delete"); } Assert.AreNotEqual(client.Batch.SubmitBatch(ref deregisterBatch), ObixResult.kObixClientSuccess, "SubmitBatch did not succceed on the deregister"); foreach (ObixXmlBatchItem batchItem in deregisterBatch.XmlBatchItemList) { Assert.IsFalse(batchItem.XmlBatchResponse.IsObixErrorContract(), "Watch delete of uri " + batchItem.UriString + " returned an error contract: " + batchItem.XmlBatchResponse.ToString()); Assert.IsTrue(batchItem.XmlBatchResponse.IsObixNullContract(), "Watch delete of uri " + batchItem.UriString + " did not return obix:nil contract as is required for obix:Watch delete operations."); } }
/// <summary> /// Read and save updated light scene value in database. /// </summary> /// <param name="basicXml">Passes xml object.</param> /// <param name="basicPointsUrl">Xml url for nodes list.</param> private static void SaveLightOccupancyStateObix(ObixResult <XElement> basicPointsResult, string basicPointsUrl) { var lightOccupancyState = basicPointsResult.Result.Document.Descendants(). Where(d => d.FirstAttribute.Value == DeviceNameType.OccupancyState).FirstOrDefault(); if (lightOccupancyState != null) { XElement basicNodeElement = lightOccupancyState as XElement; var lightOccupancyStateUrl = basicPointsUrl + basicNodeElement.Attribute("href").Value; var lightOccupancyStateXmlData = obixClientInit.oBixClient.ReadUriXml(new Uri(lightOccupancyStateUrl)); if (lightOccupancyStateXmlData.ResultSucceeded == true) { SaveCurrentOccupancyState(lightOccupancyStateXmlData, DeviceNameType.Conference4628A1761035); } } }
/// <summary> /// Read and save updated day light sensor in database. /// </summary> /// <param name="basicXml">Passes xml object.</param> /// <param name="basicPointsUrl">Xml url for nodes list.</param> private static void SaveDayLightSensorObix(ObixResult <XElement> basicPointsResult, string basicPointsUrl) { var daylightSensor = basicPointsResult.Result.Document.Descendants(). Where(d => d.FirstAttribute.Value == DeviceNameType.LtgPowerUsed).FirstOrDefault(); if (daylightSensor != null) { XElement basicNodeElement = daylightSensor as XElement; var daylightSensorUsedUrl = basicPointsUrl + basicNodeElement.Attribute("href").Value; var daylightSensorUsedXmlData = obixClientInit.oBixClient.ReadUriXml(new Uri(daylightSensorUsedUrl)); if (daylightSensorUsedXmlData.ResultSucceeded == true) { SaveCurrentDaylightSensor(daylightSensorUsedXmlData, DeviceNameType.Conference4628A1761035); } } }
/// <summary> /// Writes the oBIX object specified by <paramref name="element"/> to the endpoint specified by /// <paramref name="uri"/>. /// </summary> /// <param name="uri">The oBIX endpoint to send data to</param> /// <param name="element">An oBIX object to send to the oBIX server</param> /// <returns>kObixClientResultSuccess on success with the response oBIX object from the server, /// another value otherwise.</returns> public ObixResult <XElement> WriteUriXml(Uri uri, XElement element) { XmlWriter writer; XmlReader reader; XElement responseElement; XDocument doc; MemoryStream ms; ObixResult <byte[]> response; if (uri == null || element == null) { return(ErrorStack.PushWithObject(GetType(), ObixResult.kObixClientInputError, "Uri, or data to write is nothing.", (XElement)null)); } using (ms = new MemoryStream()) { using (writer = XmlWriter.Create(ms)) { element.WriteTo(writer); } response = WriteUri(uri, ms.ToArray()); } if (response.ResultSucceeded == false) { return(ErrorStack.PushWithObject(GetType(), response, "WriteUri failed to write data to the obix server: " + response.ToString(), (XElement)null)); } try { using (ms = new MemoryStream(response.Result)) { using (reader = XmlReader.Create(ms)) { doc = XDocument.Load(reader); } } } catch (Exception) { return(ErrorStack.PushWithObject(GetType(), ObixResult.kObixClientXMLParseError, "Could not parse the XML response from the server.", (XElement)null)); } responseElement = doc.Root; if (responseElement.IsObixErrorContract() == true) { return(ErrorStack.PushWithObject(GetType(), ObixResult.kObixServerError, responseElement.ObixDisplay(), responseElement)); } return(ObixResult.FromResult(ObixResult.kObixClientSuccess, responseElement)); }
/// <summary> /// Saves current light level. /// </summary> /// <param name="lightLevelXmlData">Passes read xml light level object.</param> /// <param name="DeviceType">Passes device type.</param> private static void SaveCurrentLightLevel(ObixResult <XElement> lightLevelXmlData, string DeviceType) { IEnumerable <XNode> lighLevelLst = lightLevelXmlData.Result.Document.DescendantNodes(); XElement lightLevelelement = lighLevelLst.LastOrDefault() as XElement; if (lightLevelelement != null) { var deviceDetail = _dbcontext.ObixDevices.Where(y => y.object_instance == (int)DeviceEnum.LightLevel).FirstOrDefault(); if (deviceDetail == null) { var lightLevelObj = new ObixDevice { DeviceName = lightLevelelement.Attribute("displayName").Value, Unit = lightLevelelement.Attribute("unit").Value, DeviceUrl = lightLevelelement.Attribute("href").Value, Status = lightLevelelement.Attribute("status") != null?lightLevelelement.Attribute("status").Value : null, Value = lightLevelelement.Attribute("val").Value, DeviceType = DeviceType, isActive = true, DateOfEntry = DateTime.UtcNow, ValueType = lightLevelelement.Name.LocalName, object_instance = (int)DeviceEnum.LightLevel }; _dbcontext.ObixDevices.Add(lightLevelObj); _dbcontext.SaveChanges(); } else { deviceDetail.DeviceName = lightLevelelement.Attribute("displayName").Value; deviceDetail.Unit = lightLevelelement.Attribute("unit").Value; deviceDetail.DeviceUrl = lightLevelelement.Attribute("href").Value; deviceDetail.Status = lightLevelelement.Attribute("status") != null?lightLevelelement.Attribute("status").Value : null; deviceDetail.Value = lightLevelelement.Attribute("val").Value; deviceDetail.DeviceType = DeviceType; deviceDetail.isActive = true; deviceDetail.DateOfEntry = DateTime.UtcNow; deviceDetail.ValueType = lightLevelelement.Name.LocalName; deviceDetail.object_instance = (int)DeviceEnum.LightLevel; _dbcontext.Entry(deviceDetail).State = System.Data.Entity.EntityState.Modified; _dbcontext.SaveChanges(); } } }
public void TestDeviceIO() { ObixResult <XElement> xmlResult = null; XElement sampleDevice = null; XElement remoteSampleDevice = null; Uri deviceUri = null; Uri signupUri = client.LobbyUri.Concat("signUp"); TestConnect(); Assert.IsNotNull(client, "Client is not initialized."); Assert.IsTrue(client.IsConnected, "Client is not connected."); sampleDevice = CreateTestDevice(); Assert.IsNotNull(sampleDevice, "TestDeviceWrite failed to create a sample device oBIX object."); xmlResult = client.InvokeUriXml(signupUri, sampleDevice); Assert.IsTrue(xmlResult.ResultSucceeded, string.Format("Device signup to href {0} failed with result {1}.", signupUri, xmlResult)); deviceUri = obixLobby.Concat(sampleDevice.ObixHref()); Assert.IsNotNull(deviceUri, "deviceUri is null"); Console.WriteLine("Device registered at URI {0}", deviceUri.ToString()); xmlResult = client.ReadUriXml(deviceUri); Assert.IsTrue(xmlResult.ResultSucceeded && xmlResult.Result.IsObixErrorContract() == false, string.Format("Failed to retrieve created device at href {0} after successfully submitting it.", deviceUri)); remoteSampleDevice = xmlResult.Result; Assert.IsNotNull(remoteSampleDevice); xmlResult = client.ReadUriXml(deviceUri.Concat("testBool")); Assert.IsTrue(xmlResult.ResultSucceeded && xmlResult.Result.IsObixErrorContract() == false, "oBIX Read testBool failed."); Assert.IsNotNull(xmlResult.Result.ObixBoolValue(), "oBIX Read testBool failed: element returned is not an obix:bool."); Assert.IsTrue(xmlResult.Result.ObixBoolValue().Value, "testBool on sampleDevice is not true."); xmlResult = client.WriteUriXml(deviceUri.Concat("testBool"), false.ObixXmlValue()); Assert.IsTrue(xmlResult.ResultSucceeded && xmlResult.Result.IsObixErrorContract() == false, "oBIX write failed."); xmlResult = client.ReadUriXml(deviceUri.Concat("testBool")); Assert.IsTrue(xmlResult.ResultSucceeded && xmlResult.Result.IsObixErrorContract() == false, "oBIX Read testBool failed."); Assert.IsNotNull(xmlResult.Result.ObixBoolValue(), "oBIX Read testBool failed: element returned is not an obix:bool."); Assert.IsFalse(xmlResult.Result.ObixBoolValue().Value, "Changing testBool on sampleDevice failed: testBool on the server side is the same value."); }
/// <summary> /// Asynchronously gets data from the oBIX server specified by <paramref name="uri"/>. /// </summary> /// <param name="uri">The URI of the oBIX data point to read</param> /// <returns>kObixClientResultSuccess with an XElement representing the /// oBIX XML object on success, another value otherwise.</returns> public async Task <ObixResult <XElement> > ReadUriXmlAsync(Uri uri) { ObixResult <byte[]> data = null; XDocument doc = null; MemoryStream ms = null; if (WebClient == null) { return(ErrorStack.PushWithObject(this.GetType(), ObixResult.kObixClientNotConnectedError, (XElement)null)); } data = await ReadUriAsync(uri); if (data.ResultSucceeded == false) { return(ErrorStack.PushWithObject(this.GetType(), ObixResult.kObixClientXMLParseError, "ReadUriXml could not understand the downloaded document at URI " + uri.ToString(), (XElement)null)); } ms = new MemoryStream(data.Result); try { doc = await Task.Factory.StartNew <XDocument>(() => XDocument.Load(ms)); } catch (Exception ex) { return(ErrorStack.PushWithObject(this.GetType(), ex, (XElement)null)); } ms.Dispose(); ms = null; if (doc == null || doc.Root == null) { return(ErrorStack.PushWithObject(this.GetType(), ObixResult.kObixClientXMLParseError, "ReadUriXml could not understand the downloaded document at URI " + uri.ToString(), (XElement)null)); } if (doc.Root.IsObixErrorContract()) { return(ErrorStack.PushWithObject(GetType(), ObixResult.kObixServerError, doc.Root)); } return(ObixResult.FromResult(ObixResult.kObixClientSuccess, doc.Root)); }
/// <summary> /// Saves current occupancy state level detail. /// </summary> /// <param name="occupancyStateXmlData">Passes read xml ocupancy state detail.</param> /// <param name="DeviceType">Passes device type.</param> private static void SaveCurrentOccupancyState(ObixResult <XElement> occupancyStateXmlData, string DeviceType) { IEnumerable <XNode> occupancyStateLst = occupancyStateXmlData.Result.Document.DescendantNodes(); XElement occupancyStateElement = occupancyStateLst.LastOrDefault() as XElement; if (occupancyStateElement != null) { var deviceDetail = _dbcontext.ObixDevices.Where(y => y.object_instance == (int)DeviceEnum.OccupancyState).FirstOrDefault(); if (deviceDetail == null) { var occupancyStateObj = new ObixDevice { DeviceName = occupancyStateElement.Attribute("displayName").Value, DeviceUrl = occupancyStateElement.Attribute("href").Value, Value = occupancyStateElement.Attribute("val").Value, DeviceType = DeviceType, isActive = true, DateOfEntry = DateTime.UtcNow, ValueType = occupancyStateElement.Name.LocalName, object_instance = (int)DeviceEnum.OccupancyState }; _dbcontext.ObixDevices.Add(occupancyStateObj); _dbcontext.SaveChanges(); } else { deviceDetail.DeviceName = occupancyStateElement.Attribute("displayName").Value; deviceDetail.DeviceUrl = occupancyStateElement.Attribute("href").Value; deviceDetail.Value = occupancyStateElement.Attribute("val").Value; deviceDetail.DeviceType = DeviceType; deviceDetail.isActive = true; deviceDetail.DateOfEntry = DateTime.UtcNow; deviceDetail.ValueType = occupancyStateElement.Name.LocalName; deviceDetail.object_instance = (int)DeviceEnum.OccupancyState; _dbcontext.ObixDevices.Attach(deviceDetail); _dbcontext.SaveChanges(); } } }
/// <summary> /// Gets data from the oBIX server specified by <paramref name="uri"/>. /// </summary> /// <param name="uri">The URI of the oBIX data point to read</param> /// <returns>kObixClientResultSuccess with an XElement representing the /// oBIX XML object on success, another value otherwise.</returns> public ObixResult <XElement> ReadUriXml(Uri uri) { ObixResult <byte[]> data = null; XDocument doc = null; MemoryStream ms = null; if (WebClient == null) { return(ErrorStack.PushWithObject(this.GetType(), ObixResult.kObixClientNotConnectedError, (XElement)null)); } data = ReadUri(uri); if (data.ResultSucceeded == false) { return(ErrorStack.PushWithObject(this.GetType(), ObixResult.kObixClientXMLParseError, "ReadUriXml could not understand the downloaded document at URI " + uri.ToString(), (XElement)null)); } using (ms = new MemoryStream(data.Result)) { ms.Position = 0; try { doc = XDocument.Load(ms); } catch (Exception ex) { return(ErrorStack.PushWithObject(this.GetType(), ex, (XElement)null)); } } if (doc == null || doc.Root == null) { return(ErrorStack.PushWithObject(this.GetType(), ObixResult.kObixClientXMLParseError, "ReadUriXml could not understand the downloaded document at URI " + uri.ToString(), (XElement)null)); } if (doc.Root.IsObixErrorContract()) { return(ErrorStack.PushWithObject(GetType(), ObixResult.kObixServerError, doc.Root)); } return(ObixResult.FromResult(ObixResult.kObixClientSuccess, doc.Root)); }
public void TestDeviceBulk() { int maxDevices = 10000; ObixResult <XElement> xmlResult = null; XElement sampleDevice = null; Uri signupUri = client.LobbyUri.Concat("signUp"); progressWnd = new CProgressWnd("Posting oBIX devices"); wndThread = new Thread(() => { progressWnd.ShowDialog(); }); wndThread.SetApartmentState(ApartmentState.STA); wndThread.Start(); progressWnd.ProgressMaximumValue = maxDevices; TestConnect(); Assert.IsNotNull(client, "Client is not initialized."); Assert.IsTrue(client.IsConnected, "Client is not connected."); for (int i = 0; i <= maxDevices; i++) { sampleDevice = CreateTestDevice(); Assert.IsNotNull(sampleDevice, "TestDeviceWrite failed to create a sample device oBIX object."); xmlResult = client.InvokeUriXml(signupUri, sampleDevice); Assert.IsTrue(xmlResult.ResultSucceeded, string.Format("Device signup to href {0} failed with result {1}.", signupUri, xmlResult)); progressWnd.Increment(); } progressWnd.RunOnUIThread(() => { progressWnd.Hide(); }); wndThread.Join(); }
static void Main(string[] args) { string Server = "<server>"; string Username = "******"; string Password = "******"; using (var obixClient = new XmlObixClient(new Uri(Server))) { obixClient.WebClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue ( "Basic", Convert.ToBase64String( Encoding.ASCII.GetBytes( string.Format("{0}:{1}", Username, Password)))); var connectResult = obixClient.Connect(); if (connectResult != ObixResult.kObixClientSuccess) { throw new Exception("Connection to server failed: " + ObixResult.Message(connectResult)); } var readResult = obixClient.ReadUriXml(new Uri(Server + "histories/")); if (readResult.ResultSucceeded) { var element = readResult.Result; System.Console.WriteLine(element.ToString()); } else { throw new Exception("Error reading from server: " + ObixResult.Message(readResult)); } System.Console.ReadKey(); } }
public void TestConnect() { ObixResult result; result = client.Connect(); Console.Out.WriteLine("Connect result: {0}", result); Assert.AreEqual <int>(result, ObixResult.kObixClientSuccess, string.Format("Connect failed with error: {0}: {1}", result, ObixResult.Message((int)result))); }
public async Task TestConnectAsync() { ObixResult result; Assert.IsNotNull(client, "Initializing the oBIX client failed."); result = await client.ConnectAsync(); Console.Out.WriteLine("Connect result: {0}", result); Assert.AreEqual <int>(result, ObixResult.kObixClientSuccess, string.Format("Connect failed with error: {0}: {1}", result, ObixResult.Message((int)result))); }