SsdpDevice.cs 30 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Collections.ObjectModel;
  4. using System.Linq;
  5. using System.Text;
  6. using System.Threading.Tasks;
  7. using System.Xml;
  8. using Rssdp.Infrastructure;
  9. namespace Rssdp
  10. {
  11. /// <summary>
  12. /// Base class representing the common details of a (root or embedded) device, either to be published or that has been located.
  13. /// </summary>
  14. /// <remarks>
  15. /// <para>Do not derive new types directly from this class. New device classes should derive from either <see cref="SsdpRootDevice"/> or <see cref="SsdpEmbeddedDevice"/>.</para>
  16. /// </remarks>
  17. /// <seealso cref="SsdpRootDevice"/>
  18. /// <seealso cref="SsdpEmbeddedDevice"/>
  19. public abstract class SsdpDevice
  20. {
  21. #region Fields
  22. private string _Udn;
  23. private string _DeviceType;
  24. private string _DeviceTypeNamespace;
  25. private int _DeviceVersion;
  26. private SsdpDevicePropertiesCollection _CustomProperties;
  27. private CustomHttpHeadersCollection _CustomResponseHeaders;
  28. private IList<SsdpDevice> _Devices;
  29. #endregion
  30. #region Events
  31. /// <summary>
  32. /// Raised when a new child device is added.
  33. /// </summary>
  34. /// <seealso cref="AddDevice"/>
  35. /// <seealso cref="DeviceAdded"/>
  36. public event EventHandler<DeviceEventArgs> DeviceAdded;
  37. /// <summary>
  38. /// Raised when a child device is removed.
  39. /// </summary>
  40. /// <seealso cref="RemoveDevice"/>
  41. /// <seealso cref="DeviceRemoved"/>
  42. public event EventHandler<DeviceEventArgs> DeviceRemoved;
  43. #endregion
  44. #region Constructors
  45. /// <summary>
  46. /// Derived type constructor, allows constructing a device with no parent. Should only be used from derived types that are or inherit from <see cref="SsdpRootDevice"/>.
  47. /// </summary>
  48. protected SsdpDevice()
  49. {
  50. _DeviceTypeNamespace = SsdpConstants.UpnpDeviceTypeNamespace;
  51. _DeviceType = SsdpConstants.UpnpDeviceTypeBasicDevice;
  52. _DeviceVersion = 1;
  53. this.Icons = new List<SsdpDeviceIcon>();
  54. _Devices = new List<SsdpDevice>();
  55. this.Devices = new ReadOnlyCollection<SsdpDevice>(_Devices);
  56. _CustomResponseHeaders = new CustomHttpHeadersCollection();
  57. _CustomProperties = new SsdpDevicePropertiesCollection();
  58. }
  59. /// <summary>
  60. /// Deserialisation constructor.
  61. /// </summary>
  62. /// <remarks><para>Uses the provided XML string and parent device properties to set the properties of the object. The XML provided must be a valid UPnP device description document.</para></remarks>
  63. /// <param name="deviceDescriptionXml">A UPnP device description XML document.</param>
  64. /// <exception cref="System.ArgumentNullException">Thrown if the <paramref name="deviceDescriptionXml"/> argument is null.</exception>
  65. /// <exception cref="System.ArgumentException">Thrown if the <paramref name="deviceDescriptionXml"/> argument is empty.</exception>
  66. protected SsdpDevice(string deviceDescriptionXml)
  67. : this()
  68. {
  69. if (deviceDescriptionXml == null) throw new ArgumentNullException("deviceDescriptionXml");
  70. if (deviceDescriptionXml.Length == 0) throw new ArgumentException("deviceDescriptionXml cannot be an empty string.", "deviceDescriptionXml");
  71. using (var ms = new System.IO.MemoryStream(System.Text.UTF8Encoding.UTF8.GetBytes(deviceDescriptionXml)))
  72. {
  73. var reader = XmlReader.Create(ms);
  74. LoadDeviceProperties(reader, this);
  75. }
  76. }
  77. #endregion
  78. #region Public Properties
  79. #region UPnP Device Description Properties
  80. /// <summary>
  81. /// Sets or returns the core device type (not including namespace, version etc.). Required.
  82. /// </summary>
  83. /// <remarks><para>Defaults to the UPnP basic device type.</para></remarks>
  84. /// <seealso cref="DeviceTypeNamespace"/>
  85. /// <seealso cref="DeviceVersion"/>
  86. /// <seealso cref="FullDeviceType"/>
  87. public string DeviceType
  88. {
  89. get
  90. {
  91. return _DeviceType;
  92. }
  93. set
  94. {
  95. _DeviceType = value;
  96. }
  97. }
  98. public string DeviceClass { get; set; }
  99. /// <summary>
  100. /// Sets or returns the namespace for the <see cref="DeviceType"/> of this device. Optional, but defaults to UPnP schema so should be changed if <see cref="DeviceType"/> is not a UPnP device type.
  101. /// </summary>
  102. /// <remarks><para>Defaults to the UPnP standard namespace.</para></remarks>
  103. /// <seealso cref="DeviceType"/>
  104. /// <seealso cref="DeviceVersion"/>
  105. /// <seealso cref="FullDeviceType"/>
  106. public string DeviceTypeNamespace
  107. {
  108. get
  109. {
  110. return _DeviceTypeNamespace;
  111. }
  112. set
  113. {
  114. _DeviceTypeNamespace = value;
  115. }
  116. }
  117. /// <summary>
  118. /// Sets or returns the version of the device type. Optional, defaults to 1.
  119. /// </summary>
  120. /// <remarks><para>Defaults to a value of 1.</para></remarks>
  121. /// <seealso cref="DeviceType"/>
  122. /// <seealso cref="DeviceTypeNamespace"/>
  123. /// <seealso cref="FullDeviceType"/>
  124. public int DeviceVersion
  125. {
  126. get
  127. {
  128. return _DeviceVersion;
  129. }
  130. set
  131. {
  132. _DeviceVersion = value;
  133. }
  134. }
  135. /// <summary>
  136. /// Returns the full device type string.
  137. /// </summary>
  138. /// <remarks>
  139. /// <para>The format used is urn:<see cref="DeviceTypeNamespace"/>:device:<see cref="DeviceType"/>:<see cref="DeviceVersion"/></para>
  140. /// </remarks>
  141. public string FullDeviceType
  142. {
  143. get
  144. {
  145. return String.Format("urn:{0}:{3}:{1}:{2}",
  146. this.DeviceTypeNamespace ?? String.Empty,
  147. this.DeviceType ?? String.Empty,
  148. this.DeviceVersion,
  149. this.DeviceClass ?? "device");
  150. }
  151. }
  152. /// <summary>
  153. /// Sets or returns the universally unique identifier for this device (without the uuid: prefix). Required.
  154. /// </summary>
  155. /// <remarks>
  156. /// <para>Must be the same over time for a specific device instance (i.e. must survive reboots).</para>
  157. /// <para>For UPnP 1.0 this can be any unique string. For UPnP 1.1 this should be a 128 bit number formatted in a specific way, preferably generated using the time and MAC based algorithm. See section 1.1.4 of http://upnp.org/specs/arch/UPnP-arch-DeviceArchitecture-v1.1.pdf for details.</para>
  158. /// <para>Technically this library implements UPnP 1.0, so any value is allowed, but we advise using UPnP 1.1 compatible values for good behaviour and forward compatibility with future versions.</para>
  159. /// </remarks>
  160. public string Uuid { get; set; }
  161. /// <summary>
  162. /// Returns (or sets*) a unique device name for this device. Optional, not recommended to be explicitly set.
  163. /// </summary>
  164. /// <remarks>
  165. /// <para>* In general you should not explicitly set this property. If it is not set (or set to null/empty string) the property will return a UDN value that is correct as per the UPnP specification, based on the other device properties.</para>
  166. /// <para>The setter is provided to allow for devices that do not correctly follow the specification (when we discover them), rather than to intentionally deviate from the specification.</para>
  167. /// <para>If a value is explicitly set, it is used verbatim, and so any prefix (such as uuid:) must be provided in the value.</para>
  168. /// </remarks>
  169. public string Udn
  170. {
  171. get
  172. {
  173. if (String.IsNullOrEmpty(_Udn) && !String.IsNullOrEmpty(this.Uuid))
  174. return "uuid:" + this.Uuid;
  175. else
  176. return _Udn;
  177. }
  178. set
  179. {
  180. _Udn = value;
  181. }
  182. }
  183. /// <summary>
  184. /// Sets or returns a friendly/display name for this device on the network. Something the user can identify the device/instance by, i.e Lounge Main Light. Required.
  185. /// </summary>
  186. /// <remarks><para>A short description for the end user. </para></remarks>
  187. public string FriendlyName { get; set; }
  188. /// <summary>
  189. /// Sets or returns the name of the manufacturer of this device. Required.
  190. /// </summary>
  191. public string Manufacturer { get; set; }
  192. /// <summary>
  193. /// Sets or returns a URL to the manufacturers web site. Optional.
  194. /// </summary>
  195. public Uri ManufacturerUrl { get; set; }
  196. /// <summary>
  197. /// Sets or returns a description of this device model. Recommended.
  198. /// </summary>
  199. /// <remarks><para>A long description for the end user.</para></remarks>
  200. public string ModelDescription { get; set; }
  201. /// <summary>
  202. /// Sets or returns the name of this model. Required.
  203. /// </summary>
  204. public string ModelName { get; set; }
  205. /// <summary>
  206. /// Sets or returns the number of this model. Recommended.
  207. /// </summary>
  208. public string ModelNumber { get; set; }
  209. /// <summary>
  210. /// Sets or returns a URL to a web page with details of this device model. Optional.
  211. /// </summary>
  212. /// <remarks>
  213. /// <para>Optional. May be relative to base URL.</para>
  214. /// </remarks>
  215. public Uri ModelUrl { get; set; }
  216. /// <summary>
  217. /// Sets or returns the serial number for this device. Recommended.
  218. /// </summary>
  219. public string SerialNumber { get; set; }
  220. /// <summary>
  221. /// Sets or returns the universal product code of the device, if any. Optional.
  222. /// </summary>
  223. /// <remarks>
  224. /// <para>If not blank, must be exactly 12 numeric digits.</para>
  225. /// </remarks>
  226. public string Upc { get; set; }
  227. /// <summary>
  228. /// Sets or returns the URL to a web page that can be used to configure/manager/use the device. Recommended.
  229. /// </summary>
  230. /// <remarks>
  231. /// <para>May be relative to base URL. </para>
  232. /// </remarks>
  233. public Uri PresentationUrl { get; set; }
  234. #endregion
  235. /// <summary>
  236. /// Returns a list of icons (images) that can be used to display this device. Optional, but recommended you provide at least one at 48x48 pixels.
  237. /// </summary>
  238. public IList<SsdpDeviceIcon> Icons
  239. {
  240. get;
  241. private set;
  242. }
  243. /// <summary>
  244. /// Returns a read-only enumerable set of <see cref="SsdpDevice"/> objects representing children of this device. Child devices are optional.
  245. /// </summary>
  246. /// <seealso cref="AddDevice"/>
  247. /// <seealso cref="RemoveDevice"/>
  248. public IEnumerable<SsdpDevice> Devices
  249. {
  250. get;
  251. private set;
  252. }
  253. /// <summary>
  254. /// Returns a dictionary of <see cref="SsdpDeviceProperty"/> objects keyed by <see cref="SsdpDeviceProperty.FullName"/>. Each value represents a custom property in the device description document.
  255. /// </summary>
  256. public SsdpDevicePropertiesCollection CustomProperties
  257. {
  258. get
  259. {
  260. return _CustomProperties;
  261. }
  262. }
  263. /// <summary>
  264. /// Provides a list of additional information to provide about this device in search response and notification messages.
  265. /// </summary>
  266. /// <remarks>
  267. /// <para>The headers included here are included in the (HTTP headers) for search response and alive notifications sent in relation to this device.</para>
  268. /// <para>Only values specified directly on this <see cref="SsdpDevice"/> instance will be included, headers from ancestors are not automatically included.</para>
  269. /// </remarks>
  270. public CustomHttpHeadersCollection CustomResponseHeaders
  271. {
  272. get
  273. {
  274. return _CustomResponseHeaders;
  275. }
  276. }
  277. #endregion
  278. #region Public Methods
  279. /// <summary>
  280. /// Adds a child device to the <see cref="Devices"/> collection.
  281. /// </summary>
  282. /// <param name="device">The <see cref="SsdpEmbeddedDevice"/> instance to add.</param>
  283. /// <remarks>
  284. /// <para>If the device is already a member of the <see cref="Devices"/> collection, this method does nothing.</para>
  285. /// <para>Also sets the <see cref="SsdpEmbeddedDevice.RootDevice"/> property of the added device and all descendant devices to the relevant <see cref="SsdpRootDevice"/> instance.</para>
  286. /// </remarks>
  287. /// <exception cref="System.ArgumentNullException">Thrown if the <paramref name="device"/> argument is null.</exception>
  288. /// <exception cref="System.InvalidOperationException">Thrown if the <paramref name="device"/> is already associated with a different <see cref="SsdpRootDevice"/> instance than used in this tree. Can occur if you try to add the same device instance to more than one tree. Also thrown if you try to add a device to itself.</exception>
  289. /// <seealso cref="DeviceAdded"/>
  290. public void AddDevice(SsdpEmbeddedDevice device)
  291. {
  292. if (device == null) throw new ArgumentNullException("device");
  293. if (device.RootDevice != null && device.RootDevice != this.ToRootDevice()) throw new InvalidOperationException("This device is already associated with a different root device (has been added as a child in another branch).");
  294. if (device == this) throw new InvalidOperationException("Can't add device to itself.");
  295. bool wasAdded = false;
  296. lock (_Devices)
  297. {
  298. device.RootDevice = this.ToRootDevice();
  299. _Devices.Add(device);
  300. wasAdded = true;
  301. }
  302. if (wasAdded)
  303. OnDeviceAdded(device);
  304. }
  305. /// <summary>
  306. /// Removes a child device from the <see cref="Devices"/> collection.
  307. /// </summary>
  308. /// <param name="device">The <see cref="SsdpEmbeddedDevice"/> instance to remove.</param>
  309. /// <remarks>
  310. /// <para>If the device is not a member of the <see cref="Devices"/> collection, this method does nothing.</para>
  311. /// <para>Also sets the <see cref="SsdpEmbeddedDevice.RootDevice"/> property to null for the removed device and all descendant devices.</para>
  312. /// </remarks>
  313. /// <exception cref="System.ArgumentNullException">Thrown if the <paramref name="device"/> argument is null.</exception>
  314. /// <seealso cref="DeviceRemoved"/>
  315. public void RemoveDevice(SsdpEmbeddedDevice device)
  316. {
  317. if (device == null) throw new ArgumentNullException("device");
  318. bool wasRemoved = false;
  319. lock (_Devices)
  320. {
  321. wasRemoved = _Devices.Remove(device);
  322. if (wasRemoved)
  323. {
  324. device.RootDevice = null;
  325. }
  326. }
  327. if (wasRemoved)
  328. OnDeviceRemoved(device);
  329. }
  330. /// <summary>
  331. /// Raises the <see cref="DeviceAdded"/> event.
  332. /// </summary>
  333. /// <param name="device">The <see cref="SsdpEmbeddedDevice"/> instance added to the <see cref="Devices"/> collection.</param>
  334. /// <seealso cref="AddDevice"/>
  335. /// <seealso cref="DeviceAdded"/>
  336. protected virtual void OnDeviceAdded(SsdpEmbeddedDevice device)
  337. {
  338. var handlers = this.DeviceAdded;
  339. if (handlers != null)
  340. handlers(this, new DeviceEventArgs(device));
  341. }
  342. /// <summary>
  343. /// Raises the <see cref="DeviceRemoved"/> event.
  344. /// </summary>
  345. /// <param name="device">The <see cref="SsdpEmbeddedDevice"/> instance removed from the <see cref="Devices"/> collection.</param>
  346. /// <seealso cref="RemoveDevice"/>
  347. /// <see cref="DeviceRemoved"/>
  348. protected virtual void OnDeviceRemoved(SsdpEmbeddedDevice device)
  349. {
  350. var handlers = this.DeviceRemoved;
  351. if (handlers != null)
  352. handlers(this, new DeviceEventArgs(device));
  353. }
  354. /// <summary>
  355. /// Writes this device to the specified <see cref="System.Xml.XmlWriter"/> as a device node and it's content.
  356. /// </summary>
  357. /// <param name="writer">The <see cref="System.Xml.XmlWriter"/> to output to.</param>
  358. /// <param name="device">The <see cref="SsdpDevice"/> to write out.</param>
  359. /// <exception cref="System.ArgumentNullException">Thrown if the <paramref name="writer"/> or <paramref name="device"/> argument is null.</exception>
  360. protected virtual void WriteDeviceDescriptionXml(XmlWriter writer, SsdpDevice device)
  361. {
  362. if (writer == null) throw new ArgumentNullException("writer");
  363. if (device == null) throw new ArgumentNullException("device");
  364. writer.WriteStartElement("device");
  365. if (!String.IsNullOrEmpty(device.FullDeviceType))
  366. WriteNodeIfNotEmpty(writer, "deviceType", device.FullDeviceType);
  367. WriteNodeIfNotEmpty(writer, "friendlyName", device.FriendlyName);
  368. WriteNodeIfNotEmpty(writer, "manufacturer", device.Manufacturer);
  369. WriteNodeIfNotEmpty(writer, "manufacturerURL", device.ManufacturerUrl);
  370. WriteNodeIfNotEmpty(writer, "modelDescription", device.ModelDescription);
  371. WriteNodeIfNotEmpty(writer, "modelName", device.ModelName);
  372. WriteNodeIfNotEmpty(writer, "modelNumber", device.ModelNumber);
  373. WriteNodeIfNotEmpty(writer, "modelURL", device.ModelUrl);
  374. WriteNodeIfNotEmpty(writer, "presentationURL", device.PresentationUrl);
  375. WriteNodeIfNotEmpty(writer, "serialNumber", device.SerialNumber);
  376. WriteNodeIfNotEmpty(writer, "UDN", device.Udn);
  377. WriteNodeIfNotEmpty(writer, "UPC", device.Upc);
  378. WriteCustomProperties(writer, device);
  379. WriteIcons(writer, device);
  380. WriteChildDevices(writer, device);
  381. writer.WriteEndElement();
  382. }
  383. /// <summary>
  384. /// Converts a string to a <see cref="Uri"/>, or returns null if the string provided is null.
  385. /// </summary>
  386. /// <param name="value">The string value to convert.</param>
  387. /// <returns>A <see cref="Uri"/>.</returns>
  388. protected static Uri StringToUri(string value)
  389. {
  390. if (!String.IsNullOrEmpty(value))
  391. return new Uri(value, UriKind.RelativeOrAbsolute);
  392. return null;
  393. }
  394. #endregion
  395. #region Private Methods
  396. #region Serialisation Methods
  397. private static void WriteCustomProperties(XmlWriter writer, SsdpDevice device)
  398. {
  399. foreach (var prop in device.CustomProperties)
  400. {
  401. writer.WriteElementString(prop.Namespace, prop.Name, SsdpConstants.SsdpDeviceDescriptionXmlNamespace, prop.Value);
  402. }
  403. }
  404. private static void WriteIcons(XmlWriter writer, SsdpDevice device)
  405. {
  406. if (device.Icons.Any())
  407. {
  408. writer.WriteStartElement("iconList");
  409. foreach (var icon in device.Icons)
  410. {
  411. writer.WriteStartElement("icon");
  412. writer.WriteElementString("mimetype", icon.MimeType);
  413. writer.WriteElementString("width", icon.Width.ToString());
  414. writer.WriteElementString("height", icon.Height.ToString());
  415. writer.WriteElementString("depth", icon.ColorDepth.ToString());
  416. writer.WriteElementString("url", icon.Url.ToString());
  417. writer.WriteEndElement();
  418. }
  419. writer.WriteEndElement();
  420. }
  421. }
  422. private void WriteChildDevices(XmlWriter writer, SsdpDevice parentDevice)
  423. {
  424. if (parentDevice.Devices.Any())
  425. {
  426. writer.WriteStartElement("deviceList");
  427. foreach (var device in parentDevice.Devices)
  428. {
  429. WriteDeviceDescriptionXml(writer, device);
  430. }
  431. writer.WriteEndElement();
  432. }
  433. }
  434. private static void WriteNodeIfNotEmpty(XmlWriter writer, string nodeName, string value)
  435. {
  436. if (!String.IsNullOrEmpty(value))
  437. writer.WriteElementString(nodeName, value);
  438. }
  439. private static void WriteNodeIfNotEmpty(XmlWriter writer, string nodeName, Uri value)
  440. {
  441. if (value != null)
  442. writer.WriteElementString(nodeName, value.ToString());
  443. }
  444. #endregion
  445. #region Deserialisation Methods
  446. private void LoadDeviceProperties(XmlReader reader, SsdpDevice device)
  447. {
  448. ReadUntilDeviceNode(reader);
  449. while (!reader.EOF)
  450. {
  451. if (reader.NodeType == XmlNodeType.EndElement && reader.Name == "device")
  452. {
  453. reader.Read();
  454. break;
  455. }
  456. if (!SetPropertyFromReader(reader, device))
  457. reader.Read();
  458. }
  459. }
  460. private static void ReadUntilDeviceNode(XmlReader reader)
  461. {
  462. while (!reader.EOF && (reader.LocalName != "device" || reader.NodeType != XmlNodeType.Element))
  463. {
  464. reader.Read();
  465. }
  466. }
  467. [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Maintainability", "CA1502:AvoidExcessiveComplexity", Justification = "Yes, there is a large switch statement, not it's not really complex and doesn't really need to be rewritten at this point.")]
  468. private bool SetPropertyFromReader(XmlReader reader, SsdpDevice device)
  469. {
  470. switch (reader.LocalName)
  471. {
  472. case "friendlyName":
  473. device.FriendlyName = reader.ReadElementContentAsString();
  474. break;
  475. case "manufacturer":
  476. device.Manufacturer = reader.ReadElementContentAsString();
  477. break;
  478. case "manufacturerURL":
  479. device.ManufacturerUrl = StringToUri(reader.ReadElementContentAsString());
  480. break;
  481. case "modelDescription":
  482. device.ModelDescription = reader.ReadElementContentAsString();
  483. break;
  484. case "modelName":
  485. device.ModelName = reader.ReadElementContentAsString();
  486. break;
  487. case "modelNumber":
  488. device.ModelNumber = reader.ReadElementContentAsString();
  489. break;
  490. case "modelURL":
  491. device.ModelUrl = StringToUri(reader.ReadElementContentAsString());
  492. break;
  493. case "presentationURL":
  494. device.PresentationUrl = StringToUri(reader.ReadElementContentAsString());
  495. break;
  496. case "serialNumber":
  497. device.SerialNumber = reader.ReadElementContentAsString();
  498. break;
  499. case "UDN":
  500. device.Udn = reader.ReadElementContentAsString();
  501. SetUuidFromUdn(device);
  502. break;
  503. case "UPC":
  504. device.Upc = reader.ReadElementContentAsString();
  505. break;
  506. case "deviceType":
  507. SetDeviceTypePropertiesFromFullDeviceType(device, reader.ReadElementContentAsString());
  508. break;
  509. case "iconList":
  510. reader.Read();
  511. LoadIcons(reader, device);
  512. break;
  513. case "deviceList":
  514. reader.Read();
  515. LoadChildDevices(reader, device);
  516. break;
  517. case "serviceList":
  518. reader.Skip();
  519. break;
  520. default:
  521. if (reader.NodeType == XmlNodeType.Element && reader.Name != "device" && reader.Name != "icon")
  522. {
  523. AddCustomProperty(reader, device);
  524. break;
  525. }
  526. else
  527. return false;
  528. }
  529. return true;
  530. }
  531. private static void SetDeviceTypePropertiesFromFullDeviceType(SsdpDevice device, string value)
  532. {
  533. if (String.IsNullOrEmpty(value) || !value.Contains(":"))
  534. device.DeviceType = value;
  535. else
  536. {
  537. var parts = value.Split(':');
  538. if (parts.Length == 5)
  539. {
  540. int deviceVersion = 1;
  541. if (Int32.TryParse(parts[4], out deviceVersion))
  542. {
  543. device.DeviceTypeNamespace = parts[1];
  544. device.DeviceType = parts[3];
  545. device.DeviceVersion = deviceVersion;
  546. }
  547. else
  548. device.DeviceType = value;
  549. }
  550. else
  551. device.DeviceType = value;
  552. }
  553. }
  554. private static void SetUuidFromUdn(SsdpDevice device)
  555. {
  556. if (device.Udn != null && device.Udn.StartsWith("uuid:", StringComparison.OrdinalIgnoreCase))
  557. device.Uuid = device.Udn.Substring(5).Trim();
  558. else
  559. device.Uuid = device.Udn;
  560. }
  561. private static void LoadIcons(XmlReader reader, SsdpDevice device)
  562. {
  563. while (!reader.EOF)
  564. {
  565. while (!reader.EOF && reader.NodeType != XmlNodeType.Element)
  566. {
  567. reader.Read();
  568. }
  569. if (reader.LocalName != "icon") break;
  570. while (reader.Name == "icon")
  571. {
  572. var icon = new SsdpDeviceIcon();
  573. LoadIconProperties(reader, icon);
  574. device.Icons.Add(icon);
  575. reader.Read();
  576. }
  577. }
  578. }
  579. private static void LoadIconProperties(XmlReader reader, SsdpDeviceIcon icon)
  580. {
  581. while (!reader.EOF)
  582. {
  583. if (reader.NodeType != XmlNodeType.Element)
  584. {
  585. if (reader.NodeType == XmlNodeType.EndElement && reader.Name == "icon") break;
  586. reader.Read();
  587. continue;
  588. }
  589. switch (reader.LocalName)
  590. {
  591. case "depth":
  592. icon.ColorDepth = reader.ReadElementContentAsInt();
  593. break;
  594. case "height":
  595. icon.Height = reader.ReadElementContentAsInt();
  596. break;
  597. case "width":
  598. icon.Width = reader.ReadElementContentAsInt();
  599. break;
  600. case "mimetype":
  601. icon.MimeType = reader.ReadElementContentAsString();
  602. break;
  603. case "url":
  604. icon.Url = StringToUri(reader.ReadElementContentAsString());
  605. break;
  606. }
  607. reader.Read();
  608. }
  609. }
  610. private void LoadChildDevices(XmlReader reader, SsdpDevice device)
  611. {
  612. while (!reader.EOF && reader.NodeType != XmlNodeType.Element)
  613. {
  614. reader.Read();
  615. }
  616. while (!reader.EOF)
  617. {
  618. while (!reader.EOF && reader.NodeType != XmlNodeType.Element)
  619. {
  620. reader.Read();
  621. }
  622. if (reader.LocalName == "device")
  623. {
  624. var childDevice = new SsdpEmbeddedDevice();
  625. LoadDeviceProperties(reader, childDevice);
  626. device.AddDevice(childDevice);
  627. }
  628. else
  629. break;
  630. }
  631. }
  632. private static void AddCustomProperty(XmlReader reader, SsdpDevice device)
  633. {
  634. var newProp = new SsdpDeviceProperty() { Namespace = reader.Prefix, Name = reader.LocalName };
  635. int depth = reader.Depth;
  636. reader.Read();
  637. while (reader.NodeType == XmlNodeType.Whitespace || reader.NodeType == XmlNodeType.Comment)
  638. {
  639. reader.Read();
  640. }
  641. if (reader.NodeType != XmlNodeType.CDATA && reader.NodeType != XmlNodeType.Text)
  642. {
  643. while (!reader.EOF && (reader.NodeType != XmlNodeType.EndElement || reader.Name != newProp.Name || reader.Prefix != newProp.Namespace || reader.Depth != depth))
  644. {
  645. reader.Read();
  646. }
  647. if (!reader.EOF)
  648. reader.Read();
  649. return;
  650. }
  651. newProp.Value = reader.Value;
  652. // We don't support complex nested types or repeat/multi-value properties
  653. if (!device.CustomProperties.Contains(newProp.FullName))
  654. device.CustomProperties.Add(newProp);
  655. }
  656. #endregion
  657. //private bool ChildDeviceExists(SsdpDevice device)
  658. //{
  659. // return (from d in _Devices where device.Uuid == d.Uuid select d).Any();
  660. //}
  661. #endregion
  662. }
  663. }