UnderlyingSystem.cs 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561
  1. /******************************************************************************
  2. ** Copyright (c) 2006-2018 Unified Automation GmbH All rights reserved.
  3. **
  4. ** Software License Agreement ("SLA") Version 2.7
  5. **
  6. ** Unless explicitly acquired and licensed from Licensor under another
  7. ** license, the contents of this file are subject to the Software License
  8. ** Agreement ("SLA") Version 2.7, or subsequent versions
  9. ** as allowed by the SLA, and You may not copy or use this file in either
  10. ** source code or executable form, except in compliance with the terms and
  11. ** conditions of the SLA.
  12. **
  13. ** All software distributed under the SLA is provided strictly on an
  14. ** "AS IS" basis, WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESS OR IMPLIED,
  15. ** AND LICENSOR HEREBY DISCLAIMS ALL SUCH WARRANTIES, INCLUDING WITHOUT
  16. ** LIMITATION, ANY WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
  17. ** PURPOSE, QUIET ENJOYMENT, OR NON-INFRINGEMENT. See the SLA for specific
  18. ** language governing rights and limitations under the SLA.
  19. **
  20. ** Project: .NET based OPC UA Client Server SDK
  21. **
  22. ** Description: OPC Unified Architecture Software Development Kit.
  23. **
  24. ** The complete license agreement can be found here:
  25. ** http://unifiedautomation.com/License/SLA/2.7/
  26. ******************************************************************************/
  27. using System;
  28. using System.Collections.Generic;
  29. using System.Linq;
  30. using System.Text;
  31. using System.Threading;
  32. using System.IO;
  33. using System.Reflection;
  34. using System.Xml;
  35. using System.Xml.Serialization;
  36. using UnifiedAutomation.UaBase;
  37. using UnifiedAutomation.UaServer;
  38. namespace YourCompany.GettingStarted
  39. {
  40. /// <summary>
  41. /// A class that provides access to the underlying system.
  42. /// </summary>
  43. public class UnderlyingSystem : IDisposable
  44. {
  45. #region Constructors
  46. /// <summary>
  47. /// Initializes a new instance of the <see cref="UnderlyingSystem"/> class.
  48. /// </summary>
  49. public UnderlyingSystem()
  50. {
  51. m_registers = new byte[4096];
  52. m_blocks = new Dictionary<int, BlockConfiguration>();
  53. }
  54. #endregion
  55. #region IDisposable Members
  56. /// <summary>
  57. /// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources.
  58. /// </summary>
  59. public void Dispose()
  60. {
  61. Dispose(true);
  62. }
  63. /// <summary>
  64. /// Releases unmanaged and - optionally - managed resources
  65. /// </summary>
  66. /// <param name="disposing"><c>true</c> to release both managed and unmanaged resources; <c>false</c> to release only unmanaged resources.</param>
  67. protected void Dispose(bool disposing)
  68. {
  69. if (disposing)
  70. {
  71. if (m_simulationTimer != null)
  72. {
  73. m_simulationTimer.Dispose();
  74. m_simulationTimer = null;
  75. }
  76. }
  77. }
  78. #endregion
  79. #region Public Methods
  80. /// <summary>
  81. /// Initializes this instance.
  82. /// </summary>
  83. public void Initialize()
  84. {
  85. // load the configuration file.
  86. Load();
  87. // start the simulation timer.
  88. m_simulationTimer = new Timer(DoSimulation, null, 1000, 1000);
  89. }
  90. /// <summary>
  91. /// Gets the blockAddress configurations.
  92. /// </summary>
  93. /// <returns></returns>
  94. public IEnumerable<BlockConfiguration> GetBlocks()
  95. {
  96. return m_blocks.Values;
  97. }
  98. /// <summary>
  99. /// Reads the tag value.
  100. /// </summary>
  101. /// <param name="blockAddress">The blockAddress.</param>
  102. /// <param name="tag">The tag.</param>
  103. /// <returns>The value. null if no value exists.</returns>
  104. public object Read(int blockAddress, int tag)
  105. {
  106. lock (m_lock)
  107. {
  108. if (blockAddress < 0 || tag < 0)
  109. {
  110. return null;
  111. }
  112. if (blockAddress + tag > m_position - sizeof(int))
  113. {
  114. return null;
  115. }
  116. BlockConfiguration controller = null;
  117. if (!m_blocks.TryGetValue(blockAddress, out controller))
  118. {
  119. return null;
  120. }
  121. foreach (BlockProperty property in controller.Properties)
  122. {
  123. if (property.Offset == tag)
  124. {
  125. if (property.DataType == DataTypeIds.Double)
  126. {
  127. return (double)BitConverter.ToSingle(m_registers, blockAddress + tag);
  128. }
  129. if (property.DataType == DataTypeIds.Int32)
  130. {
  131. return BitConverter.ToInt32(m_registers, blockAddress + tag);
  132. }
  133. }
  134. }
  135. return null;
  136. }
  137. }
  138. /// <summary>
  139. /// Writes the tag value.
  140. /// </summary>
  141. /// <param name="blockAddress">The blockAddress.</param>
  142. /// <param name="tag">The tag.</param>
  143. /// <param name="value">The value.</param>
  144. /// <returns>
  145. /// True if the write was successful.
  146. /// </returns>
  147. public bool Write(int blockAddress, int tag, object value)
  148. {
  149. lock (m_lock)
  150. {
  151. if (blockAddress < 0 || tag < 0)
  152. {
  153. return false;
  154. }
  155. if (blockAddress + tag > m_position - sizeof(int))
  156. {
  157. return false;
  158. }
  159. BlockConfiguration controller = null;
  160. if (!m_blocks.TryGetValue(blockAddress, out controller))
  161. {
  162. return false;
  163. }
  164. foreach (BlockProperty property in controller.Properties)
  165. {
  166. if (property.Offset == tag)
  167. {
  168. if (!property.Writeable)
  169. {
  170. return false;
  171. }
  172. if (property.DataType == DataTypeIds.Double)
  173. {
  174. Write(blockAddress, tag, (double)value);
  175. return true;
  176. }
  177. if (property.DataType == DataTypeIds.Int32)
  178. {
  179. Write(blockAddress, tag, (int)value);
  180. return true;
  181. }
  182. }
  183. }
  184. return false;
  185. }
  186. }
  187. /// <summary>
  188. /// Starts the specified object id.
  189. /// </summary>
  190. /// <param name="blockAddress">The blockAddress.</param>
  191. /// <returns></returns>
  192. public StatusCode Start(int blockAddress)
  193. {
  194. lock (m_lock)
  195. {
  196. BlockConfiguration controller = null;
  197. if (!m_blocks.TryGetValue(blockAddress, out controller))
  198. {
  199. return StatusCodes.BadNodeIdUnknown;
  200. }
  201. foreach (BlockProperty property in controller.Properties)
  202. {
  203. if (property.Name == "State")
  204. {
  205. Write(blockAddress, property.Offset, (int)1);
  206. break;
  207. }
  208. }
  209. return StatusCodes.Good;
  210. }
  211. }
  212. /// <summary>
  213. /// Stops the specified object id.
  214. /// </summary>
  215. /// <param name="blockAddress">The blockAddress.</param>
  216. /// <returns></returns>
  217. public StatusCode Stop(int blockAddress)
  218. {
  219. lock (m_lock)
  220. {
  221. BlockConfiguration controller = null;
  222. if (!m_blocks.TryGetValue(blockAddress, out controller))
  223. {
  224. return StatusCodes.BadNodeIdUnknown;
  225. }
  226. foreach (BlockProperty property in controller.Properties)
  227. {
  228. if (property.Name == "State")
  229. {
  230. Write(blockAddress, property.Offset, (int)0);
  231. break;
  232. }
  233. }
  234. return StatusCodes.Good;
  235. }
  236. }
  237. /// <summary>
  238. /// Called when to start the simulation with a set point.
  239. /// </summary>
  240. /// <param name="blockAddress">The blockAddress.</param>
  241. /// <param name="temperatureSetPoint">The temperature set point.</param>
  242. /// <param name="humditySetPoint">The humdity set point.</param>
  243. /// <returns></returns>
  244. public StatusCode StartWithSetPoint(int blockAddress, double temperatureSetPoint, double humditySetPoint)
  245. {
  246. lock (m_lock)
  247. {
  248. BlockConfiguration controller = null;
  249. if (!m_blocks.TryGetValue(blockAddress, out controller))
  250. {
  251. return StatusCodes.BadNodeIdUnknown;
  252. }
  253. foreach (BlockProperty property in controller.Properties)
  254. {
  255. if (property.Name == "TemperatureSetPoint")
  256. {
  257. Write(blockAddress, property.Offset, temperatureSetPoint);
  258. }
  259. else if (property.Name == "HumiditySetPoint")
  260. {
  261. Write(blockAddress, property.Offset, humditySetPoint);
  262. }
  263. else if (property.Name == "State")
  264. {
  265. Write(blockAddress, property.Offset, (int)1);
  266. }
  267. }
  268. return StatusCodes.Good;
  269. }
  270. }
  271. #endregion
  272. #region Private Method
  273. /// <summary>
  274. /// Loads the configuration for the system.
  275. /// </summary>
  276. private void Load()
  277. {
  278. foreach (string resourceName in Assembly.GetExecutingAssembly().GetManifestResourceNames())
  279. {
  280. if (resourceName.EndsWith(".SystemConfiguration.xml"))
  281. {
  282. using (Stream istrm = Assembly.GetExecutingAssembly().GetManifestResourceStream(resourceName))
  283. {
  284. XmlSerializer serializer = new XmlSerializer(typeof(Configuration));
  285. m_configuration = (Configuration)serializer.Deserialize(istrm);
  286. }
  287. }
  288. }
  289. if (m_configuration.Controllers != null)
  290. {
  291. for (int ii = 0; ii < m_configuration.Controllers.Length; ii++)
  292. {
  293. ControllerConfiguration controller = m_configuration.Controllers[ii];
  294. int blockAddress = m_position;
  295. int offset = m_position - blockAddress;
  296. BlockConfiguration data = new BlockConfiguration()
  297. {
  298. Address = blockAddress,
  299. Name = controller.Name,
  300. Type = controller.Type,
  301. Properties = new List<BlockProperty>()
  302. };
  303. if (controller.Properties != null)
  304. {
  305. for (int jj = 0; jj < controller.Properties.Length; jj++)
  306. {
  307. ControllerProperty property = controller.Properties[jj];
  308. NodeId dataTypeId = NodeId.Parse(property.DataType);
  309. string value = property.Value;
  310. Range range = null;
  311. if (!String.IsNullOrEmpty(property.Range))
  312. {
  313. try
  314. {
  315. NumericRange nr = NumericRange.Parse(property.Range);
  316. range = new Range() { High = nr.End, Low = nr.Begin };
  317. }
  318. catch (Exception)
  319. {
  320. range = null;
  321. }
  322. }
  323. data.Properties.Add(new BlockProperty()
  324. {
  325. Offset = offset,
  326. Name = controller.Properties[jj].Name,
  327. DataType = dataTypeId,
  328. Writeable = controller.Properties[jj].Writeable,
  329. Range = range
  330. });
  331. switch ((uint)dataTypeId.Identifier)
  332. {
  333. case DataTypes.Int32:
  334. {
  335. Write(blockAddress, offset, (int)TypeUtils.Cast(value, BuiltInType.Int32));
  336. offset += 4;
  337. break;
  338. }
  339. case DataTypes.Double:
  340. {
  341. Write(blockAddress, offset, (double)TypeUtils.Cast(value, BuiltInType.Double));
  342. offset += 4;
  343. break;
  344. }
  345. }
  346. }
  347. }
  348. m_position += offset;
  349. m_blocks[blockAddress] = data;
  350. }
  351. }
  352. }
  353. /// <summary>
  354. /// Writes the specified offset.
  355. /// </summary>
  356. /// <param name="offset">The offset.</param>
  357. /// <param name="value">The value.</param>
  358. private void Write(int blockAddress, int offset, int value)
  359. {
  360. byte[] bytes = BitConverter.GetBytes(value);
  361. Array.Copy(bytes, 0, m_registers, blockAddress + offset, bytes.Length);
  362. }
  363. /// <summary>
  364. /// Writes the specified offset.
  365. /// </summary>
  366. /// <param name="offset">The offset.</param>
  367. /// <param name="value">The value.</param>
  368. private void Write(int blockAddress, int offset, double value)
  369. {
  370. byte[] bytes = BitConverter.GetBytes((float)value);
  371. Array.Copy(bytes, 0, m_registers, blockAddress + offset, bytes.Length);
  372. }
  373. /// <summary>
  374. /// Does the simulation.
  375. /// </summary>
  376. /// <param name="state">The state.</param>
  377. private void DoSimulation(object state)
  378. {
  379. try
  380. {
  381. lock (m_lock)
  382. {
  383. foreach (var blockAddress in m_blocks)
  384. {
  385. for (int ii = 0; ii < blockAddress.Value.Properties.Count - 1; ii++)
  386. {
  387. string firstName = blockAddress.Value.Properties[ii].Name;
  388. string secondName = blockAddress.Value.Properties[ii + 1].Name;
  389. if (!secondName.StartsWith(firstName) || !secondName.EndsWith("SetPoint"))
  390. {
  391. continue;
  392. }
  393. int valueOffset = blockAddress.Value.Properties[ii].Offset;
  394. int setpointOffset = blockAddress.Value.Properties[ii + 1].Offset;
  395. double value = (double)Read(blockAddress.Key, valueOffset);
  396. double setpoint = (double)Read(blockAddress.Key, setpointOffset);
  397. Write(blockAddress.Key, valueOffset, Adjust(value, setpoint));
  398. }
  399. }
  400. }
  401. }
  402. catch (Exception e)
  403. {
  404. TraceServer.Error(e, "Failed run simulation.");
  405. }
  406. }
  407. /// <summary>
  408. /// Adjusts the specified value.
  409. /// </summary>
  410. /// <param name="value">The value.</param>
  411. /// <param name="setPoint">The set point.</param>
  412. /// <returns></returns>
  413. private double Adjust(double value, double setPoint)
  414. {
  415. Random random = new Random();
  416. double delta = (Math.Abs(setPoint - value) + 1) * random.NextDouble();
  417. return value + ((random.Next() % 2 == 0) ? delta : -delta);
  418. }
  419. #endregion
  420. #region Configuration File Classes
  421. [XmlType(TypeName = "UnderlyingSystem.ControllerProperty", Namespace = "http://yourcompany.com/underlyingsystem")]
  422. public class ControllerProperty
  423. {
  424. [XmlElement(Order = 1)]
  425. public string Name { get; set; }
  426. [XmlElement(Order = 2)]
  427. public string DataType { get; set; }
  428. [XmlElement(Order = 3)]
  429. public string Value { get; set; }
  430. [XmlElement(Order = 4)]
  431. public bool Writeable { get; set; }
  432. [XmlElement(Order = 5)]
  433. public string Range { get; set; }
  434. }
  435. [XmlType(TypeName = "UnderlyingSystem.ControllerConfiguration", Namespace = "http://yourcompany.com/underlyingsystem")]
  436. public class ControllerConfiguration
  437. {
  438. [XmlElement(Order = 1)]
  439. public string Name { get; set; }
  440. [XmlElement(Order = 2)]
  441. public int Type { get; set; }
  442. [XmlElement(Order = 3)]
  443. public ControllerProperty[] Properties;
  444. }
  445. [XmlRoot(ElementName = "UnderlyingSystem.Configuration", Namespace = "http://yourcompany.com/underlyingsystem")]
  446. public class Configuration
  447. {
  448. [XmlElement(Order = 1)]
  449. public ControllerConfiguration[] Controllers;
  450. }
  451. #endregion
  452. #region Private Fields
  453. private object m_lock = new object();
  454. private byte[] m_registers;
  455. private int m_position;
  456. private Dictionary<int, BlockConfiguration> m_blocks;
  457. private Configuration m_configuration;
  458. private Timer m_simulationTimer;
  459. #endregion
  460. }
  461. #region BlockProperty Class
  462. /// <summary>
  463. /// The configuration for a property of a blockAddress.
  464. /// </summary>
  465. public class BlockProperty
  466. {
  467. public int Offset;
  468. public string Name;
  469. public NodeId DataType;
  470. public bool Writeable;
  471. public Range Range;
  472. }
  473. #endregion
  474. #region BlockConfiguration Class
  475. /// <summary>
  476. /// The configuration for a blockAddress.
  477. /// </summary>
  478. public class BlockConfiguration
  479. {
  480. public int Address;
  481. public string Name;
  482. public int Type;
  483. public List<BlockProperty> Properties;
  484. }
  485. #endregion
  486. #region BlockType Class
  487. public static class BlockType
  488. {
  489. public const int AirConditioner = 1;
  490. public const int Furnace = 2;
  491. }
  492. #endregion
  493. }