Guest User

Untitled

a guest
May 23rd, 2022
148
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 78.45 KB | None | 0 0
  1. //
  2. // --------------------------------------------------------------------------
  3. // Gurux Ltd
  4. //
  5. //
  6. //
  7. // Filename: $HeadURL$
  8. //
  9. // Version: $Revision$,
  10. // $Date$
  11. // $Author$
  12. //
  13. // Copyright (c) Gurux Ltd
  14. //
  15. //---------------------------------------------------------------------------
  16. //
  17. // DESCRIPTION
  18. //
  19. // This file is a part of Gurux Device Framework.
  20. //
  21. // Gurux Device Framework is Open Source software; you can redistribute it
  22. // and/or modify it under the terms of the GNU General Public License
  23. // as published by the Free Software Foundation; version 2 of the License.
  24. // Gurux Device Framework is distributed in the hope that it will be useful,
  25. // but WITHOUT ANY WARRANTY; without even the implied warranty of
  26. // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
  27. // See the GNU General Public License for more details.
  28. //
  29. // More information of Gurux products: http://www.gurux.org
  30. //
  31. // This code is licensed under the GNU General Public License v2.
  32. // Full text may be retrieved at http://www.gnu.org/licenses/gpl-2.0.txt
  33. //---------------------------------------------------------------------------
  34. #include <EEPROM.h>
  35. #include "GXDLMSServer.h"
  36.  
  37. #ifdef ARDUINO_ARCH_ESP8266
  38. #include <ESP8266WiFi.h>
  39.  
  40. //---------------------------------------------------------------------------
  41. // Change WIFI settings.
  42. //---------------------------------------------------------------------------
  43. const char* ssid = "Kurunsaari1";
  44. const char* password = "kissa123";
  45. const int port = 4059; //Port number
  46. static WiFiServer tcpServer(port);
  47. #else
  48. #define USE_TIME_INTERRUPT
  49. #endif //ARDUINO_ARCH_ESP8266
  50.  
  51. //---------------------------------------------------------------------------
  52. // Un-comment ignored objects from ArduinoIgnore.h to improve performance
  53. // and memory usage.
  54. //---------------------------------------------------------------------------
  55.  
  56. //2000 bytes is for settings.
  57. //1000 bytes is for load profile
  58. //1000 bytes is for event profile
  59.  
  60. #define SETTINGS_BUFFER_SIZE 2000
  61. #define LOAD_PROFILE_BUFFER_SIZE 1000
  62. #define EVENT_PROFILE_BUFFER_SIZE 1000
  63.  
  64. //Ignore time_now warning.
  65. #pragma GCC diagnostic ignored "-Wunused-but-set-parameter"
  66.  
  67. uint32_t SERIALIZER_SIZE()
  68. {
  69. return EEPROM.length();
  70. }
  71.  
  72. int SERIALIZER_LOAD(uint32_t index, uint32_t count, void* value)
  73. {
  74. if (index + count > SERIALIZER_SIZE())
  75. {
  76. return DLMS_ERROR_CODE_SERIALIZATION_LOAD_FAILURE;
  77. }
  78. unsigned char* p = (unsigned char*) value;
  79. uint32_t pos;
  80. for (pos = 0; pos != count; ++pos)
  81. {
  82. *p = EEPROM.read(index + pos);
  83. ++p;
  84. }
  85. return 0;
  86. }
  87.  
  88. int SERIALIZER_SAVE(uint32_t index, uint32_t count, const void* value)
  89. {
  90. if (index + count > SERIALIZER_SIZE())
  91. {
  92. return DLMS_ERROR_CODE_SERIALIZATION_LOAD_FAILURE;
  93. }
  94. unsigned char* p = (unsigned char*) value;
  95. uint32_t pos;
  96. for (pos = 0; pos != count; ++pos)
  97. {
  98. EEPROM.write(index + pos, *p);
  99. ++p;
  100. }
  101. return 0;
  102. }
  103.  
  104. /////////////////////////////////////////////////////////////////////////////
  105. //DLMS settings.
  106. unsigned char hdlcChanged = 0;
  107. const static char *FLAG_ID = "GRX";
  108. uint32_t SERIAL_NUMBER = 303;
  109.  
  110. #define HDLC_HEADER_SIZE 17
  111. #define HDLC_BUFFER_SIZE 128
  112. #define PDU_BUFFER_SIZE 512
  113. #define WRAPPER_BUFFER_SIZE 8 + PDU_BUFFER_SIZE
  114. //Buffer where frames are saved.
  115. static unsigned char frameBuff[HDLC_BUFFER_SIZE + HDLC_HEADER_SIZE];
  116. //Buffer where PDUs are saved.
  117. static unsigned char pduBuff[PDU_BUFFER_SIZE];
  118. static unsigned char replyFrame[HDLC_BUFFER_SIZE + HDLC_HEADER_SIZE];
  119. //Define server system title.
  120. static unsigned char SERVER_SYSTEM_TITLE[8] = { 0 };
  121.  
  122. static gxByteBuffer reply;
  123.  
  124. //Define profile generic buffer row data for Load profile.
  125. typedef struct
  126. {
  127. //Date-time value of the clock.
  128. uint32_t time;
  129. //Active power L1 value.
  130. uint16_t activePowerL1;
  131. } gxLoadProfileData;
  132.  
  133. //Define profile generic buffer row data for event log.
  134. typedef struct
  135. {
  136. //Date-time value of the clock.
  137. uint32_t time;
  138. //Occurred event.
  139. uint16_t event;
  140. } gxEventLogData;
  141.  
  142. //Define Logical Device Name.
  143. char LDN[17];
  144.  
  145. static gxData ldn;
  146. //Is meter in test mode. This is used to serialize data and it's not shown in association view.
  147. static gxData testMode;
  148. //blockCipherKey. This is used to serialize data and it's not shown in association view.
  149. static gxData blockCipherKey;
  150. //authenticationKey. This is used to serialize data and it's not shown in association view.
  151. static gxData authenticationKey;
  152. //KEK. This is used to serialize data and it's not shown in association view.
  153. static gxData kek;
  154. //Server invocationCounter. This is used to serialize data and it's not shown in association view.
  155. static gxData serverInvocationCounter;
  156. static gxData eeprom;
  157. static gxData eventCode;
  158. static gxData unixTime;
  159. static gxData invocationCounter;
  160. //IEC HDLC Setup.
  161. gxIecHdlcSetup hdlc;
  162. //Don't use clock as a name. Some compilers are using clock as reserved word.
  163. gxClock clock1;
  164. static gxAssociationLogicalName associationNone;
  165. static gxAssociationLogicalName associationLow;
  166. static gxAssociationLogicalName associationHigh;
  167. static gxAssociationLogicalName associationHighGMac;
  168. static gxScriptTable scriptTableGlobalMeterReset;
  169. static gxScriptTable scriptTableDisconnectControl;
  170. static gxScriptTable scriptTableActivatetestMode;
  171. static gxScriptTable scriptTableActivateNormalMode;
  172. static gxProfileGeneric eventLog;
  173. static gxActionSchedule actionScheduleDisconnectOpen;
  174. static gxActionSchedule actionScheduleDisconnectClose;
  175. static gxPushSetup pushSetup;
  176. static gxDisconnectControl disconnectControl;
  177. static gxProfileGeneric profileGeneric;
  178. //static gxSapAssignment sapAssignment;
  179. static gxSecuritySetup securitySetupLow;
  180. static gxSecuritySetup securitySetupHigh;
  181.  
  182. static gxRegister activePowerL1;
  183. static gxRegister instantVoltageL1, instantVoltageL2, instantVoltageL3, instantCurrentsL1, instantCurrentsL2, instantCurrentsL3, instantCurrentsN, temperature;
  184.  
  185. static gxSerializerSettings serializerSettings;
  186.  
  187. //static gxObject* NONE_OBJECTS[] = { BASE(associationNone), BASE(ldn), BASE(eeprom), BASE(sapAssignment), BASE(clock1) };
  188.  
  189. /////////////////////////////////////////////////////////////////
  190. //Append new COSEM object to the end so serialization will work correctly.
  191. static gxObject* ALL_OBJECTS[] = { BASE(associationNone), BASE(associationLow), BASE(associationHigh), BASE(associationHighGMac), BASE(securitySetupLow), BASE(securitySetupHigh),
  192. BASE(ldn), BASE(eeprom), BASE(testMode), BASE(eventCode),
  193. BASE(clock1), BASE(activePowerL1), BASE(instantVoltageL1), BASE(instantVoltageL2), BASE(instantVoltageL3),
  194. BASE(instantCurrentsL1), BASE(instantCurrentsL2), BASE(instantCurrentsL3), BASE(instantCurrentsN),
  195. BASE(temperature), BASE(pushSetup), BASE(scriptTableGlobalMeterReset), BASE(scriptTableDisconnectControl),
  196. BASE(scriptTableActivatetestMode), BASE(scriptTableActivateNormalMode), BASE(profileGeneric), BASE(eventLog), BASE(hdlc),
  197. BASE(disconnectControl), BASE(actionScheduleDisconnectOpen), BASE(actionScheduleDisconnectClose),
  198. BASE(unixTime), BASE(invocationCounter),
  199. BASE(blockCipherKey), BASE(authenticationKey), BASE(kek), BASE(serverInvocationCounter)
  200. };
  201.  
  202. //List of COSEM objects that are removed from association view(s).
  203. //Objects can be used to save meter internal data.
  204. static gxObject* INTERNAL_OBJECTS[] = { BASE(testMode), BASE(blockCipherKey), BASE(authenticationKey), BASE(kek), BASE(serverInvocationCounter)};
  205.  
  206. ////////////////////////////////////////////////////
  207. //Define what is serialized to decrease EEPROM usage.
  208. static gxSerializerIgnore NON_SERIALIZED_OBJECTS[] = {
  209. //Nothing is saved when authentication is not used.
  210. IGNORE_ATTRIBUTE(BASE(associationNone), GET_ATTRIBUTE_ALL()),
  211. //Only password is saved for low and high authentication.
  212. IGNORE_ATTRIBUTE(BASE(associationLow), GET_ATTRIBUTE_EXCEPT(7)),
  213. IGNORE_ATTRIBUTE(BASE(associationHigh), GET_ATTRIBUTE_EXCEPT(7)),
  214. //Only scaler and unit are saved for all register objects.
  215. IGNORE_ATTRIBUTE_BY_TYPE(DLMS_OBJECT_TYPE_REGISTER, GET_ATTRIBUTE(2)),
  216. //Association object list or association atatus are never saved.
  217. IGNORE_ATTRIBUTE_BY_TYPE(DLMS_OBJECT_TYPE_ASSOCIATION_LOGICAL_NAME, GET_ATTRIBUTE(2, 8)),
  218. //Profile generic buffer is not saved.
  219. IGNORE_ATTRIBUTE_BY_TYPE(DLMS_OBJECT_TYPE_PROFILE_GENERIC, GET_ATTRIBUTE(2)),
  220. //EEPROM is not serialized.
  221. IGNORE_ATTRIBUTE(BASE(eeprom) , GET_ATTRIBUTE_ALL())
  222. };
  223.  
  224. #ifndef USE_TIME_INTERRUPT
  225. static uint32_t started = 0;
  226. #endif //USE_TIME_INTERRUPT
  227.  
  228. static uint32_t executeTime = 0;
  229.  
  230. static uint16_t activePowerL1Value = 0;
  231.  
  232. typedef enum
  233. {
  234. //Meter is powered.
  235. GURUX_EVENT_CODES_POWER_UP = 0x1,
  236. //User has change the time.
  237. GURUX_EVENT_CODES_TIME_CHANGE = 0x2,
  238. //DST status is changed.
  239. GURUX_EVENT_CODES_DST = 0x4,
  240. //Push message is sent.
  241. GURUX_EVENT_CODES_PUSH = 0x8,
  242. //Meter makes auto connect.
  243. GURUX_EVENT_CODES_AUTO_CONNECT = 0x10,
  244. //User has change the password.
  245. GURUX_EVENT_CODES_PASSWORD_CHANGED = 0x20,
  246. //Wrong password tried 3 times.
  247. GURUX_EVENT_CODES_WRONG_PASSWORD = 0x40,
  248. //Disconnect control state is changed.
  249. GURUX_EVENT_CODES_OUTPUT_RELAY_STATE = 0x80,
  250. //User has reset the meter.
  251. GURUX_EVENT_CODES_GLOBAL_METER_RESET = 0x100
  252. } GURUX_EVENT_CODES;
  253.  
  254. uint16_t eventLogRowIndex = 0;
  255.  
  256. void captureEventLog(uint16_t value)
  257. {
  258. gxEventLogData row;
  259. // Profile generic Capture is called. Save data to the buffer.
  260. // Ring buffer is used here.
  261. row.time = time_current();
  262. row.event = value;
  263. SERIALIZER_SAVE(SETTINGS_BUFFER_SIZE + LOAD_PROFILE_BUFFER_SIZE + eventLogRowIndex * sizeof(gxEventLogData), sizeof(gxEventLogData), &row);
  264. //Update how many entries is used until buffer is full.
  265. if (eventLog.entriesInUse != eventLog.profileEntries)
  266. {
  267. ++eventLog.entriesInUse;
  268. }
  269. //Update row index where next row is added.
  270. ++eventLogRowIndex;
  271. eventLogRowIndex = eventLogRowIndex % eventLog.profileEntries;
  272. saveSettings(BASE(eventLog), GET_ATTRIBUTE(7));
  273. }
  274.  
  275. void updateState(uint16_t value)
  276. {
  277. GX_UINT16(eventCode.value) = value;
  278. captureEventLog(value);
  279. //Update Entries in use for even log.
  280. saveSettings(BASE(eventLog), GET_ATTRIBUTE(7));
  281. }
  282.  
  283. ///////////////////////////////////////////////////////////////////////
  284. // Write trace to the serial port.
  285. //
  286. // This can be used for debugging.
  287. ///////////////////////////////////////////////////////////////////////
  288. void GXTRACE(const char* str, const char* data)
  289. {
  290. //Send trace to the serial port in test mode.
  291. if (GX_GET_BOOL(testMode.value))
  292. {
  293. byte c;
  294. Serial1.write("\t:", 2);
  295. while ((c = pgm_read_byte(str++)) != 0)
  296. {
  297. Serial1.write(c);
  298. }
  299. if (data != NULL)
  300. {
  301. Serial1.write(data, strlen(data));
  302. }
  303. Serial1.write("\0", 1);
  304. }
  305. }
  306.  
  307. ///////////////////////////////////////////////////////////////////////
  308. // Write trace to the serial port.
  309. //
  310. // This can be used for debugging.
  311. ///////////////////////////////////////////////////////////////////////
  312. void GXTRACE_INT(const char* str, int32_t value)
  313. {
  314. char data[10];
  315. sprintf(data, " %ld", value);
  316. GXTRACE(str, data);
  317. }
  318.  
  319. ///////////////////////////////////////////////////////////////////////
  320. // Write trace to the serial port.
  321. //
  322. // This can be used for debugging.
  323. ///////////////////////////////////////////////////////////////////////
  324. void GXTRACE_LN(const char* str, uint16_t type, unsigned char* ln)
  325. {
  326. char buff[30];
  327. sprintf(buff, "%d %d.%d.%d.%d.%d.%d", type, ln[0], ln[1], ln[2], ln[3], ln[4], ln[5]);
  328. GXTRACE(str, buff);
  329. }
  330.  
  331. /////////////////////////////////////////////////////////////////////////////
  332. // Save data to the EEPROM.
  333. //
  334. // Only updated value is saved. This is done because write to EEPROM is slow
  335. // and there is a limit how many times value can be written to the EEPROM.
  336. /////////////////////////////////////////////////////////////////////////////
  337. int saveSettings(gxObject* savedObject, uint16_t savedAttributes)
  338. {
  339. int ret = 0;
  340. serializerSettings.savedObject = savedObject;
  341. serializerSettings.savedAttributes = savedAttributes;
  342. if ((ret = Server.saveObjects(&serializerSettings, ALL_OBJECTS, sizeof(ALL_OBJECTS) / sizeof(ALL_OBJECTS[0]))) != 0)
  343. {
  344. GXTRACE_INT(GET_STR_FROM_EEPROM("saveObjects failed: "), ret);
  345. }
  346. else
  347. {
  348. GXTRACE_INT(GET_STR_FROM_EEPROM("saveObjects succeeded. Index: "), serializerSettings.updateStart);
  349. GXTRACE_INT(GET_STR_FROM_EEPROM("Count: "), serializerSettings.updateEnd - serializerSettings.updateStart);
  350. }
  351. return ret;
  352. }
  353.  
  354.  
  355. /////////////////////////////////////////////////////////////////////////////
  356. // Load data from the EEPROM.
  357. // Returns serialization version or zero if data is not saved.
  358. /////////////////////////////////////////////////////////////////////////////
  359. int loadSettings()
  360. {
  361. int ret = 0;
  362. serializerSettings.position = 0;
  363. ret = Server.loadObjects(&serializerSettings, ALL_OBJECTS, sizeof(ALL_OBJECTS) / sizeof(ALL_OBJECTS[0]));
  364. if (ret != 0)
  365. {
  366. GXTRACE_INT(GET_STR_FROM_EEPROM("Failed to load settings from EEPROM."), serializerSettings.position);
  367. }
  368. return ret;
  369. }
  370.  
  371. ///////////////////////////////////////////////////////////////////////
  372. // Returns the number of milliseconds passed since the Arduino board began running the current program.
  373. // This number will overflow (go back to zero), after approximately 50 days.
  374. ///////////////////////////////////////////////////////////////////////
  375. uint32_t time_elapsed(void)
  376. {
  377. return millis();
  378. }
  379.  
  380. ///////////////////////////////////////////////////////////////////////
  381. //Get current time.
  382. //Note! Real clock is missing from the Arduino.
  383. //Because there is no clock, clock object keeps base time and uptime is added to that.
  384. ///////////////////////////////////////////////////////////////////////
  385. uint32_t time_current(void)
  386. {
  387. #ifdef USE_TIME_INTERRUPT
  388. return time_toUnixTime2(&clock1.time);
  389. #else
  390. uint32_t tmp = time_elapsed() - started;
  391. tmp /= 1000;
  392. tmp += time_toUnixTime2(&clock1.time);
  393. return tmp;
  394. #endif //USE_TIME_INTERRUPT
  395. }
  396.  
  397. ///////////////////////////////////////////////////////////////////////
  398. // Returns current time.
  399. // Get current time.
  400. // Because there is no clock, clock object keeps base time and uptime is added to that.
  401. ///////////////////////////////////////////////////////////////////////
  402. void time_now(gxtime* value, unsigned char meterTime)
  403. {
  404. #ifdef USE_TIME_INTERRUPT
  405. value = &clock1.time;
  406. #else
  407. uint32_t offset = time_current();
  408. time_initUnix(value, offset);
  409. //If date time is wanted in meter time, not in utc time.
  410. if (meterTime)
  411. {
  412. clock_utcToMeterTime(&clock1, value);
  413. }
  414. #endif //USE_TIME_INTERRUPT
  415. }
  416.  
  417. ///////////////////////////////////////////////////////////////////////
  418. //This method adds example Logical Name Association object.
  419. ///////////////////////////////////////////////////////////////////////
  420. int addAssociationNone()
  421. {
  422. int ret;
  423. const unsigned char ln[6] = { 0, 0, 40, 0, 1, 255 };
  424. if ((ret = INIT_OBJECT(associationNone, DLMS_OBJECT_TYPE_ASSOCIATION_LOGICAL_NAME, ln)) == 0)
  425. {
  426. //All objects are shown also without authentication.
  427. OA_ATTACH(associationNone.objectList, ALL_OBJECTS);
  428. //Uncomment this if you want to show only part of the objects without authentication.
  429. //OA_ATTACH(associationNone.objectList, NONE_OBJECTS);
  430. associationNone.authenticationMechanismName.mechanismId = DLMS_AUTHENTICATION_NONE;
  431. associationNone.clientSAP = 0x10;
  432. //Max PDU is half of PDU size. This is for demonstration purposes only.
  433. associationNone.xDLMSContextInfo.maxSendPduSize = associationNone.xDLMSContextInfo.maxReceivePduSize = PDU_BUFFER_SIZE / 2;
  434. associationNone.xDLMSContextInfo.conformance = DLMS_CONFORMANCE_GET;
  435. }
  436. return ret;
  437. }
  438.  
  439. ///////////////////////////////////////////////////////////////////////
  440. //This method adds example Logical Name Association object.
  441. ///////////////////////////////////////////////////////////////////////
  442. int addAssociationLow()
  443. {
  444. int ret;
  445. const unsigned char ln[6] = { 0, 0, 40, 0, 2, 255 };
  446. static unsigned char SECRET[20];
  447. if ((ret = INIT_OBJECT(associationLow, DLMS_OBJECT_TYPE_ASSOCIATION_LOGICAL_NAME, ln)) == 0)
  448. {
  449. BB_ATTACH(associationLow.secret, SECRET, 0);
  450. //Only Logical Device Name is add to this Association View.
  451. OA_ATTACH(associationLow.objectList, ALL_OBJECTS);
  452. associationLow.authenticationMechanismName.mechanismId = DLMS_AUTHENTICATION_LOW;
  453. associationLow.clientSAP = 0x11;
  454. associationLow.xDLMSContextInfo.maxSendPduSize = associationLow.xDLMSContextInfo.maxReceivePduSize = PDU_BUFFER_SIZE;
  455. associationLow.xDLMSContextInfo.conformance = (DLMS_CONFORMANCE)(DLMS_CONFORMANCE_BLOCK_TRANSFER_WITH_ACTION |
  456. DLMS_CONFORMANCE_BLOCK_TRANSFER_WITH_SET_OR_WRITE |
  457. DLMS_CONFORMANCE_BLOCK_TRANSFER_WITH_GET_OR_READ |
  458. DLMS_CONFORMANCE_SET |
  459. DLMS_CONFORMANCE_SELECTIVE_ACCESS |
  460. DLMS_CONFORMANCE_ACTION |
  461. DLMS_CONFORMANCE_MULTIPLE_REFERENCES |
  462. DLMS_CONFORMANCE_GET);
  463. memcpy((char*) SECRET, "Gurux", 5);
  464. associationLow.secret.size = 5;
  465. #ifndef DLMS_IGNORE_OBJECT_POINTERS
  466. associationLow.securitySetup = &securitySetupLow;
  467. #else
  468. memcpy(associationLow.securitySetupReference, securitySetupLow.base.logicalName, 6);
  469. #endif //DLMS_IGNORE_OBJECT_POINTERS
  470. }
  471. return ret;
  472. }
  473.  
  474. ///////////////////////////////////////////////////////////////////////
  475. //This method adds example Logical Name Association object for High authentication.
  476. // UA in Indian standard.
  477. ///////////////////////////////////////////////////////////////////////
  478. int addAssociationHigh()
  479. {
  480. int ret;
  481. static unsigned char SECRET[20];
  482. //Dedicated key.
  483. static unsigned char CYPHERING_INFO[16] = { 0 };
  484. const unsigned char ln[6] = { 0, 0, 40, 0, 3, 255 };
  485. if ((ret = INIT_OBJECT(associationHigh, DLMS_OBJECT_TYPE_ASSOCIATION_LOGICAL_NAME, ln)) == 0)
  486. {
  487. associationHigh.authenticationMechanismName.mechanismId = DLMS_AUTHENTICATION_HIGH;
  488. OA_ATTACH(associationHigh.objectList, ALL_OBJECTS);
  489. BB_ATTACH(associationHigh.xDLMSContextInfo.cypheringInfo, CYPHERING_INFO, 0);
  490. associationHigh.clientSAP = 0x12;
  491. associationHigh.xDLMSContextInfo.maxSendPduSize = associationHigh.xDLMSContextInfo.maxReceivePduSize = PDU_BUFFER_SIZE;
  492. associationHigh.xDLMSContextInfo.conformance = (DLMS_CONFORMANCE)(DLMS_CONFORMANCE_BLOCK_TRANSFER_WITH_ACTION |
  493. DLMS_CONFORMANCE_BLOCK_TRANSFER_WITH_SET_OR_WRITE |
  494. DLMS_CONFORMANCE_BLOCK_TRANSFER_WITH_GET_OR_READ |
  495. DLMS_CONFORMANCE_SET |
  496. DLMS_CONFORMANCE_SELECTIVE_ACCESS |
  497. DLMS_CONFORMANCE_ACTION |
  498. DLMS_CONFORMANCE_MULTIPLE_REFERENCES |
  499. DLMS_CONFORMANCE_GET);
  500. BB_ATTACH(associationHigh.secret, SECRET, 0);
  501. memcpy((char*) SECRET, "Gurux", 5);
  502. associationHigh.secret.size = 5;
  503. #ifndef DLMS_IGNORE_OBJECT_POINTERS
  504. associationHigh.securitySetup = &securitySetupHigh;
  505. #else
  506. memcpy(associationHigh.securitySetupReference, securitySetupHigh.base.logicalName, 6);
  507. #endif //DLMS_IGNORE_OBJECT_POINTERS
  508. }
  509. return ret;
  510. }
  511.  
  512.  
  513. ///////////////////////////////////////////////////////////////////////
  514. //This method adds example Logical Name Association object for GMAC High authentication.
  515. // UA in Indian standard.
  516. ///////////////////////////////////////////////////////////////////////
  517. int addAssociationHighGMac()
  518. {
  519. int ret;
  520. //If you are getting 'gxUser' does not name a type; did you mean 'gxKey'?
  521. //Uncomment #define DLMS_IGNORE_MALLOC from gxignore.h
  522. //This error is coming because this example is not using malloc
  523. //and there are no way to give compiler arguments in Arduino IDE.
  524.  
  525. //Dedicated key.
  526. static unsigned char CYPHERING_INFO[16] = { 0 };
  527. const unsigned char ln[6] = { 0, 0, 40, 0, 4, 255 };
  528. if ((ret = INIT_OBJECT(associationHighGMac, DLMS_OBJECT_TYPE_ASSOCIATION_LOGICAL_NAME, ln)) == 0)
  529. {
  530. associationHighGMac.authenticationMechanismName.mechanismId = DLMS_AUTHENTICATION_HIGH_GMAC;
  531. OA_ATTACH(associationHighGMac.objectList, ALL_OBJECTS);
  532. BB_ATTACH(associationHighGMac.xDLMSContextInfo.cypheringInfo, CYPHERING_INFO, 0);
  533. associationHighGMac.clientSAP = 0x1;
  534. associationHighGMac.xDLMSContextInfo.maxSendPduSize = associationHighGMac.xDLMSContextInfo.maxReceivePduSize = PDU_BUFFER_SIZE;
  535. associationHighGMac.xDLMSContextInfo.conformance = (DLMS_CONFORMANCE)(DLMS_CONFORMANCE_BLOCK_TRANSFER_WITH_ACTION |
  536. DLMS_CONFORMANCE_BLOCK_TRANSFER_WITH_SET_OR_WRITE |
  537. DLMS_CONFORMANCE_BLOCK_TRANSFER_WITH_GET_OR_READ |
  538. DLMS_CONFORMANCE_SET |
  539. DLMS_CONFORMANCE_SELECTIVE_ACCESS |
  540. DLMS_CONFORMANCE_ACTION |
  541. DLMS_CONFORMANCE_MULTIPLE_REFERENCES |
  542. DLMS_CONFORMANCE_GET);
  543. //GMAC authentication don't need password.
  544. #ifndef DLMS_IGNORE_OBJECT_POINTERS
  545. associationHighGMac.securitySetup = &securitySetupHigh;
  546. #else
  547. memcpy(associationHighGMac.securitySetupReference, securitySetupHigh.base.logicalName, 6);
  548. #endif //DLMS_IGNORE_OBJECT_POINTERS
  549. }
  550. return ret;
  551. }
  552.  
  553. ///////////////////////////////////////////////////////////////////////
  554. //This method adds security setup object for Low authentication.
  555. ///////////////////////////////////////////////////////////////////////
  556. int addSecuritySetupLow()
  557. {
  558. int ret;
  559. //Define client system title.
  560. static unsigned char CLIENT_SYSTEM_TITLE[8] = { 0 };
  561. const unsigned char ln[6] = { 0, 0, 43, 0, 1, 255 };
  562. if ((ret = INIT_OBJECT(securitySetupLow, DLMS_OBJECT_TYPE_SECURITY_SETUP, ln)) == 0)
  563. {
  564. BB_ATTACH(securitySetupLow.serverSystemTitle, SERVER_SYSTEM_TITLE, 8);
  565. BB_ATTACH(securitySetupLow.clientSystemTitle, CLIENT_SYSTEM_TITLE, 8);
  566. securitySetupLow.securityPolicy = DLMS_SECURITY_POLICY_NOTHING;
  567. securitySetupLow.securitySuite = DLMS_SECURITY_SUITE_V0;
  568. }
  569. return ret;
  570. }
  571.  
  572.  
  573. ///////////////////////////////////////////////////////////////////////
  574. //This method adds security setup object for High authentication.
  575. ///////////////////////////////////////////////////////////////////////
  576. int addSecuritySetupHigh()
  577. {
  578. int ret;
  579. //Define client system title.
  580. static unsigned char CLIENT_SYSTEM_TITLE[8] = { 0 };
  581. const unsigned char ln[6] = { 0, 0, 43, 0, 2, 255 };
  582. if ((ret = INIT_OBJECT(securitySetupHigh, DLMS_OBJECT_TYPE_SECURITY_SETUP, ln)) == 0)
  583. {
  584. BB_ATTACH(securitySetupHigh.serverSystemTitle, SERVER_SYSTEM_TITLE, 8);
  585. BB_ATTACH(securitySetupHigh.clientSystemTitle, CLIENT_SYSTEM_TITLE, 8);
  586. securitySetupHigh.securityPolicy = DLMS_SECURITY_POLICY_NOTHING;
  587. securitySetupHigh.securitySuite = DLMS_SECURITY_SUITE_V0;
  588. }
  589. return ret;
  590. }
  591.  
  592. ///////////////////////////////////////////////////////////////////////
  593. //Add Logical Device Name. 123456 is meter serial number.
  594. ///////////////////////////////////////////////////////////////////////
  595. // COSEM Logical Device Name is defined as an octet-string of 16 octets.
  596. // The first three octets uniquely identify the manufacturer of the device and it corresponds
  597. // to the manufacturer's identification in IEC 62056-21.
  598. // The following 13 octets are assigned by the manufacturer.
  599. //The manufacturer is responsible for guaranteeing the uniqueness of these octets.
  600. int addLogicalDeviceName()
  601. {
  602. int ret;
  603. const unsigned char ln[6] = { 0, 0, 42, 0, 0, 255 };
  604. if ((ret = INIT_OBJECT(ldn, DLMS_OBJECT_TYPE_DATA, ln)) == 0)
  605. {
  606. sprintf(LDN, "%s%.13lu", FLAG_ID, SERIAL_NUMBER);
  607. GX_OCTET_STRING(ldn.value, LDN, sizeof(LDN));
  608. }
  609. return ret;
  610. }
  611.  
  612.  
  613. ///////////////////////////////////////////////////////////////////////
  614. // User can read content of the EEPROM. This is for debugging purposes only.
  615. int addEeprom()
  616. {
  617. int ret;
  618. const unsigned char ln[6] = { 0, 128, 0, 0, 0, 255 };
  619. if ((ret = INIT_OBJECT(eeprom, DLMS_OBJECT_TYPE_DATA, ln)) == 0)
  620. {
  621. eeprom.value.vt = DLMS_DATA_TYPE_OCTET_STRING;
  622. }
  623. return ret;
  624. }
  625. //Add event code object.
  626. int addEventCode()
  627. {
  628. int ret;
  629. const unsigned char ln[6] = { 0, 0, 96, 11, 0, 255 };
  630. if ((ret = INIT_OBJECT(eventCode, DLMS_OBJECT_TYPE_DATA, ln)) == 0)
  631. {
  632. GX_UINT16(eventCode.value) = 0;
  633. }
  634. return ret;
  635. }
  636.  
  637.  
  638. //Add unix time object.
  639. int addUnixTime()
  640. {
  641. int ret;
  642. const unsigned char ln[6] = { 0, 0, 1, 1, 0, 255 };
  643. if ((ret = INIT_OBJECT(unixTime, DLMS_OBJECT_TYPE_DATA, ln)) == 0)
  644. {
  645. //Set initial value.
  646. GX_UINT32(unixTime.value) = 0;
  647. }
  648. return ret;
  649. }
  650.  
  651. //Add invocation counter object.
  652. int addInvocationCounter()
  653. {
  654. int ret;
  655. const unsigned char ln[6] = { 0, 0, 43, 1, 0, 255 };
  656. if ((ret = INIT_OBJECT(invocationCounter, DLMS_OBJECT_TYPE_DATA, ln)) == 0)
  657. {
  658. //Initial invocation counter value.
  659. GX_UINT32_BYREF(invocationCounter.value, securitySetupHigh.minimumInvocationCounter);
  660. }
  661. return ret;
  662. }
  663.  
  664.  
  665. ///////////////////////////////////////////////////////////////////////
  666. // Is meter in test mode.
  667. // This is used to serialize the data and it's not in association view.
  668. int addTestMode()
  669. {
  670. int ret;
  671. const unsigned char ln[6] = { 0, 128, 1, 0, 0, 255 };
  672. if ((ret = INIT_OBJECT(testMode, DLMS_OBJECT_TYPE_DATA, ln)) == 0)
  673. {
  674. GX_BOOL(testMode.value) = 1;
  675. }
  676. return ret;
  677. }
  678.  
  679.  
  680. ///////////////////////////////////////////////////////////////////////
  681. // BlockCipher key.
  682. // This is used to serialize the data and it's not in association view.
  683. int addBlockCipherKey()
  684. {
  685. int ret;
  686. const unsigned char ln[6] = { 0, 128, 2, 0, 0, 255 };
  687. if ((ret = INIT_OBJECT(blockCipherKey, DLMS_OBJECT_TYPE_DATA, ln)) == 0)
  688. {
  689. Server.assingBlockCipherKey(&blockCipherKey.value);
  690. }
  691. return ret;
  692. }
  693.  
  694. ///////////////////////////////////////////////////////////////////////
  695. // Authentication key.
  696. // This is used to serialize the data and it's not in association view.
  697. int addAuthenticationKey()
  698. {
  699. int ret;
  700. const unsigned char ln[6] = { 0, 128, 3, 0, 0, 255 };
  701. if ((ret = INIT_OBJECT(authenticationKey, DLMS_OBJECT_TYPE_DATA, ln)) == 0)
  702. {
  703. Server.assingAuthenticationKey(&authenticationKey.value);
  704. }
  705. return ret;
  706. }
  707.  
  708. ///////////////////////////////////////////////////////////////////////
  709. // Kek.
  710. // This is used to serialize the data and it's not in association view.
  711. int addKek()
  712. {
  713. int ret;
  714. const unsigned char ln[6] = { 0, 128, 4, 0, 0, 255 };
  715. if ((ret = INIT_OBJECT(kek, DLMS_OBJECT_TYPE_DATA, ln)) == 0)
  716. {
  717. Server.assingAuthenticationKey(&kek.value);
  718. }
  719. return ret;
  720. }
  721.  
  722. ///////////////////////////////////////////////////////////////////////
  723. // Server Invocation Counter.
  724. // This is used to serialize the data and it's not in association view.
  725. int addServerInvocationCounter()
  726. {
  727. int ret;
  728. const unsigned char ln[6] = { 0, 128, 5, 0, 0, 255 };
  729. if ((ret = INIT_OBJECT(serverInvocationCounter, DLMS_OBJECT_TYPE_DATA, ln)) == 0)
  730. {
  731. Server.assignServerInvocationCounter(&serverInvocationCounter.value);
  732. }
  733. return ret;
  734. }
  735.  
  736. ///////////////////////////////////////////////////////////////////////
  737. //Add push setup object. (On Connectivity)
  738. ///////////////////////////////////////////////////////////////////////
  739. int addPushSetup()
  740. {
  741. int ret;
  742. const unsigned char ln[6] = { 0, 0, 25, 9, 0, 255 };
  743. static gxTimePair COMMUNICATION_WINDOW[10];
  744. static unsigned char DESTINATION[20] = { 0 };
  745. static gxTarget PUSH_OBJECTS[6];
  746. if ((ret = INIT_OBJECT(pushSetup, DLMS_OBJECT_TYPE_PUSH_SETUP, ln)) == 0)
  747. {
  748. pushSetup.service = DLMS_SERVICE_TYPE_HDLC;
  749. BB_ATTACH(pushSetup.destination, DESTINATION, 0);
  750. ARR_ATTACH(pushSetup.communicationWindow, COMMUNICATION_WINDOW, 2);
  751. ARR_ATTACH(pushSetup.pushObjectList, PUSH_OBJECTS, 2);
  752. //This push is sent every minute, but max 10 seconds over.
  753. time_init(&COMMUNICATION_WINDOW[0].first, -1, -1, -1, -1, -1, 0, 0, 0);
  754. time_init(&COMMUNICATION_WINDOW[0].second, -1, -1, -1, -1, -1, 10, 0, 0);
  755. //This push is sent every half minute, but max 40 seconds over.
  756. time_init(&COMMUNICATION_WINDOW[1].first, -1, -1, -1, -1, -1, 30, 0, 0);
  757. time_init(&COMMUNICATION_WINDOW[1].second, -1, -1, -1, -1, -1, 40, 0, 0);
  758. // Add logical device name.
  759. PUSH_OBJECTS[0].target = BASE(ldn);
  760. PUSH_OBJECTS[0].attributeIndex = 2;
  761. PUSH_OBJECTS[0].dataIndex = 0;
  762. // Add push object logical name. This is needed to tell structure of data to the Push listener.
  763. // Also capture object list can be used here.
  764. PUSH_OBJECTS[1].target = BASE(pushSetup);
  765. PUSH_OBJECTS[1].attributeIndex = 1;
  766. PUSH_OBJECTS[1].dataIndex = 0;
  767. }
  768. return ret;
  769. }
  770.  
  771. ///////////////////////////////////////////////////////////////////////
  772. //This method adds example clock object.
  773. ///////////////////////////////////////////////////////////////////////
  774. int addClockObject()
  775. {
  776. int ret = 0;
  777. //Add default clock. Clock's Logical Name is 0.0.1.0.0.255.
  778. const unsigned char ln[6] = { 0, 0, 1, 0, 0, 255 };
  779. if ((ret = INIT_OBJECT(clock1, DLMS_OBJECT_TYPE_CLOCK, ln)) == 0)
  780. {
  781. //Set default values.
  782. time_init(&clock1.begin, -1, 3, -1, 2, 0, 0, 0, 0);
  783. clock1.begin.extraInfo = DLMS_DATE_TIME_EXTRA_INFO_LAST_DAY;
  784. time_init(&clock1.end, -1, 10, -1, 3, 0, 0, 0, 0);
  785. clock1.end.extraInfo = DLMS_DATE_TIME_EXTRA_INFO_LAST_DAY;
  786. //Meter is using UTC time zone.
  787. clock1.timeZone = 0;
  788. //Deviation is 60 minutes.
  789. clock1.deviation = 60;
  790. clock1.clockBase = DLMS_CLOCK_BASE_FREQUENCY_50;
  791. }
  792. return ret;
  793. }
  794.  
  795. ///////////////////////////////////////////////////////////////////////
  796. //This method adds example register object.
  797. ///////////////////////////////////////////////////////////////////////
  798. int addRegisterObject()
  799. {
  800. int ret;
  801. // RMSMeasuresRegs* ptrRMS = ade9000GetRMSPtr();
  802. // TemperatureRegs* ptrTemp = ade9000GetTempPtr();
  803. const unsigned char ln[6] = { 1, 1, 21, 25, 0, 255 };
  804. if ((ret = INIT_OBJECT(activePowerL1, DLMS_OBJECT_TYPE_REGISTER, ln)) == 0)
  805. {
  806. activePowerL1Value = 10;
  807. GX_UINT16_BYREF(activePowerL1.value, activePowerL1Value);
  808. //10 ^ 3 = 1000
  809. activePowerL1.scaler = 3;
  810. activePowerL1.unit = DLMS_UNIT_ACTIVE_ENERGY;
  811. }
  812.  
  813. // Voltages
  814. ///////////////////////////////////////////////////////////////////
  815. const unsigned char lnInstantVoltageL1[6] = { 1, 1, 32, 7, 0, 255 };
  816. if ((ret = INIT_OBJECT(instantVoltageL1, DLMS_OBJECT_TYPE_REGISTER, lnInstantVoltageL1)) == 0)
  817. {
  818. //GX_UINT32_BYREF(instantVoltageL1.value, (ptrRMS->AVRMS));
  819. //10 ^ 2 = 100
  820. instantVoltageL1.scaler = -2;
  821. instantVoltageL1.unit = 35;
  822. }
  823.  
  824. const unsigned char lnInstantVoltageL2[6] = { 1, 1, 52, 7, 0, 255 };
  825. if ((ret = INIT_OBJECT(instantVoltageL2, DLMS_OBJECT_TYPE_REGISTER, lnInstantVoltageL2)) == 0)
  826. {
  827. // GX_UINT32_BYREF(instantVoltageL2.value, (ptrRMS->BVRMS));
  828. //10 ^ 2 = 100
  829. instantVoltageL2.scaler = -2;
  830. instantVoltageL2.unit = 35;
  831. }
  832.  
  833. const unsigned char lnInstantVoltageL3[6] = { 1, 1, 72, 7, 0, 255 };
  834. if ((ret = INIT_OBJECT(instantVoltageL3, DLMS_OBJECT_TYPE_REGISTER, lnInstantVoltageL3)) == 0)
  835. {
  836. // GX_UINT32_BYREF(instantVoltageL3.value, (ptrRMS->CVRMS));
  837. instantVoltageL3.scaler = -2;
  838. instantVoltageL3.unit = 35;
  839. }
  840. // Currents
  841. ///////////////////////////////////////////////////////////////////
  842. const unsigned char lnInstantCurrentsL1[6] = { 1, 1, 31, 7, 0, 255 };
  843. if ((ret = INIT_OBJECT(instantCurrentsL1, DLMS_OBJECT_TYPE_REGISTER, lnInstantCurrentsL1)) == 0)
  844. {
  845. // GX_UINT32_BYREF(instantCurrentsL1.value, (ptrRMS->AIRMS));
  846. //10 ^ 2 = 100
  847. instantCurrentsL1.scaler = -2;
  848. instantCurrentsL1.unit = 33;
  849. }
  850.  
  851. const unsigned char lnInstantCurrentsL2[6] = { 1, 1, 51, 7, 0, 255 };
  852. if ((ret = INIT_OBJECT(instantCurrentsL2, DLMS_OBJECT_TYPE_REGISTER, lnInstantCurrentsL2)) == 0)
  853. {
  854. // GX_UINT32_BYREF(instantCurrentsL2.value, (ptrRMS->BIRMS));
  855. //10 ^ 2 = 100
  856. instantCurrentsL2.scaler = -2;
  857. instantCurrentsL2.unit = 33;
  858. }
  859.  
  860. const unsigned char lnInstantCurrentsL3[6] = { 1, 1, 71, 7, 0, 255 };
  861. if ((ret = INIT_OBJECT(instantCurrentsL3, DLMS_OBJECT_TYPE_REGISTER, lnInstantCurrentsL3)) == 0)
  862. {
  863. // GX_UINT32_BYREF(instantCurrentsL3.value, (ptrRMS->CIRMS));
  864. instantCurrentsL3.scaler = -2;
  865. instantCurrentsL3.unit = 33;
  866. }
  867.  
  868. const unsigned char lnInstantCurrentsN[6] = { 1, 1, 91, 7, 0, 255 };
  869. if ((ret = INIT_OBJECT(instantCurrentsN, DLMS_OBJECT_TYPE_REGISTER, lnInstantCurrentsN)) == 0)
  870. {
  871. // GX_UINT32_BYREF(instantCurrentsN.value, (ptrRMS->NIRMS));
  872. instantCurrentsN.scaler = -2;
  873. instantCurrentsN.unit = 33;
  874. }
  875.  
  876. // Temperature
  877. ///////////////////////////////////////////////////////////////////
  878. const unsigned char lnTemperature[6] = { 0, 0, 96, 9, 0, 255 };
  879. if ((ret = INIT_OBJECT(temperature, DLMS_OBJECT_TYPE_REGISTER, lnTemperature)) == 0)
  880. {
  881. // GX_UINT32_BYREF(temperature.value, (ptrTemp->TemperatureValue));
  882. temperature.scaler = -2;
  883. temperature.unit = 52;
  884. }
  885. return ret;
  886. }
  887.  
  888. uint16_t readActivePowerValue()
  889. {
  890. return ++activePowerL1Value;
  891. }
  892.  
  893. uint16_t readEventCode()
  894. {
  895. return eventCode.value.uiVal;
  896. }
  897. ///////////////////////////////////////////////////////////////////////
  898. //Add script table object for meter reset. This will erase the EEPROM.
  899. ///////////////////////////////////////////////////////////////////////
  900. int addscriptTableGlobalMeterReset()
  901. {
  902. int ret;
  903. static gxScript SCRIPTS[1] = { 0 };
  904. const unsigned char ln[6] = { 0, 0, 10, 0, 0, 255 };
  905. if ((ret = INIT_OBJECT(scriptTableGlobalMeterReset, DLMS_OBJECT_TYPE_SCRIPT_TABLE, ln)) == 0)
  906. {
  907. SCRIPTS[0].id = 1;
  908. ARR_ATTACH(scriptTableGlobalMeterReset.scripts, SCRIPTS, 1);
  909. }
  910. return ret;
  911. }
  912.  
  913. /////////////////////////////////////////////////////////////////////
  914. //Add script table object for disconnect control.
  915. //Action 1 calls remote_disconnect #1 (close).
  916. //Action 2 calls remote_connect #2(open).
  917. ///////////////////////////////////////////////////////////////////////
  918. int addscriptTableDisconnectControl()
  919. {
  920. int ret;
  921. static gxScript SCRIPTS[2] = { 0 };
  922. static gxScriptAction ACTIONS1[1] = { 0 };
  923. static gxScriptAction ACTIONS2[1] = { 0 };
  924. const unsigned char ln[6] = { 0, 0, 10, 0, 106, 255 };
  925. if ((ret = INIT_OBJECT(scriptTableDisconnectControl, DLMS_OBJECT_TYPE_SCRIPT_TABLE, ln)) == 0)
  926. {
  927. SCRIPTS[0].id = 1;
  928. SCRIPTS[1].id = 2;
  929. ARR_ATTACH(scriptTableDisconnectControl.scripts, SCRIPTS, 2);
  930. ARR_ATTACH(SCRIPTS[0].actions, ACTIONS1, 1);
  931. ACTIONS1[0].type = DLMS_SCRIPT_ACTION_TYPE_EXECUTE;
  932. ACTIONS1[0].target = BASE(disconnectControl);
  933. ACTIONS1[0].index = 1;
  934. var_init(&ACTIONS1[0].parameter);
  935. //Action data is Int8 zero.
  936. GX_INT8(ACTIONS1[0].parameter) = 0;
  937.  
  938. ARR_ATTACH(SCRIPTS[1].actions, ACTIONS2, 1);
  939. ACTIONS2[0].type = DLMS_SCRIPT_ACTION_TYPE_EXECUTE;
  940. ACTIONS2[0].target = BASE(disconnectControl);
  941. ACTIONS2[0].index = 2;
  942. var_init(&ACTIONS2[0].parameter);
  943. //Action data is Int8 zero.
  944. GX_INT8(ACTIONS2[0].parameter) = 0;
  945. }
  946. return ret;
  947. }
  948.  
  949. ///////////////////////////////////////////////////////////////////////
  950. //Add script table object for test mode. In test mode meter is sending trace to the serial port.
  951. ///////////////////////////////////////////////////////////////////////
  952. int addscriptTableActivatetestMode()
  953. {
  954. int ret;
  955. static gxScript SCRIPTS[1] = { 0 };
  956. const unsigned char ln[6] = { 0, 0, 10, 0, 101, 255};
  957. if ((ret = INIT_OBJECT(scriptTableActivatetestMode, DLMS_OBJECT_TYPE_SCRIPT_TABLE, ln)) == 0)
  958. {
  959. SCRIPTS[0].id = 1;
  960. ARR_ATTACH(scriptTableActivatetestMode.scripts, SCRIPTS, 1);
  961. }
  962. return ret;
  963. }
  964.  
  965. ///////////////////////////////////////////////////////////////////////
  966. //Add script table object for Normal mode. In normal mode meter is NOT sending trace to the serial port.
  967. ///////////////////////////////////////////////////////////////////////
  968. int addscriptTableActivateNormalMode()
  969. {
  970. int ret;
  971. static gxScript SCRIPTS[1];
  972. const unsigned char ln[6] = { 0, 0, 10, 0, 102, 255};
  973. if ((ret = INIT_OBJECT(scriptTableActivateNormalMode, DLMS_OBJECT_TYPE_SCRIPT_TABLE, ln)) == 0)
  974. {
  975. SCRIPTS[0].id = 1;
  976. ARR_ATTACH(scriptTableActivateNormalMode.scripts, SCRIPTS, 1);
  977. }
  978. return ret;
  979. }
  980.  
  981. ///////////////////////////////////////////////////////////////////////
  982. //Add profile generic (historical data) object.
  983. ///////////////////////////////////////////////////////////////////////
  984. int addLoadProfileProfileGeneric()
  985. {
  986. int ret;
  987. //Two capture objects.
  988. static gxTarget CAPTURE_OBJECT[2] = { 0 };
  989. const unsigned char ln[6] = { 1, 0, 99, 1, 0, 255 };
  990. if ((ret = INIT_OBJECT(profileGeneric, DLMS_OBJECT_TYPE_PROFILE_GENERIC, ln)) == 0)
  991. {
  992. profileGeneric.capturePeriod = 60;
  993. //Maximum row count. One row takes 6 bytes. Allocate 150 rows = 900B.
  994. profileGeneric.profileEntries = 150;
  995. profileGeneric.sortMethod = DLMS_SORT_METHOD_FIFO;
  996. //entries in use.
  997. profileGeneric.entriesInUse = 0;
  998. ///////////////////////////////////////////////////////////////////
  999. //Add 2 columns.
  1000. ARR_ATTACH(profileGeneric.captureObjects, CAPTURE_OBJECT, 2);
  1001. //Add clock object.
  1002. CAPTURE_OBJECT[0].target = BASE(clock1);
  1003. CAPTURE_OBJECT[0].attributeIndex = 2;
  1004. CAPTURE_OBJECT[0].dataIndex = 0;
  1005. //Add active power.
  1006. CAPTURE_OBJECT[1].target = BASE(activePowerL1);
  1007. CAPTURE_OBJECT[1].attributeIndex = 2;
  1008. CAPTURE_OBJECT[1].dataIndex = 0;
  1009. //Set clock to sort object.
  1010. profileGeneric.sortObject = BASE(clock1);
  1011. profileGeneric.sortObjectAttributeIndex = 2;
  1012. }
  1013. return 0;
  1014. }
  1015.  
  1016. ///////////////////////////////////////////////////////////////////////
  1017. //Add profile generic (historical data) object.
  1018. ///////////////////////////////////////////////////////////////////////
  1019. int addEventLogProfileGeneric()
  1020. {
  1021. int ret;
  1022. //Two capture objects. Clock and event code
  1023. static gxTarget CAPTURE_OBJECT[2] = { 0 };
  1024. const unsigned char ln[6] = { 1, 0, 99, 98, 0, 255 };
  1025. if ((ret = INIT_OBJECT(eventLog, DLMS_OBJECT_TYPE_PROFILE_GENERIC, ln)) == 0)
  1026. {
  1027. //events are not captured.
  1028. eventLog.capturePeriod = 0;
  1029. //Maximum row count. One row takes 6 bytes. Allocate 150 rows = 900B.
  1030. eventLog.profileEntries = 150;
  1031. eventLog.sortMethod = DLMS_SORT_METHOD_FIFO;
  1032. //entries in use.
  1033. eventLog.entriesInUse = 0;
  1034. ///////////////////////////////////////////////////////////////////
  1035. //Add 2 columns.
  1036. ARR_ATTACH(eventLog.captureObjects, CAPTURE_OBJECT, 2);
  1037. //Add clock object.
  1038. CAPTURE_OBJECT[0].target = BASE(clock1);
  1039. CAPTURE_OBJECT[0].attributeIndex = 2;
  1040. CAPTURE_OBJECT[0].dataIndex = 0;
  1041. //Add active power.
  1042. CAPTURE_OBJECT[1].target = BASE(eventCode);
  1043. CAPTURE_OBJECT[1].attributeIndex = 2;
  1044. CAPTURE_OBJECT[1].dataIndex = 0;
  1045. //Set clock to sort object.
  1046. eventLog.sortObject = BASE(clock1);
  1047. eventLog.sortObjectAttributeIndex = 2;
  1048. }
  1049. return 0;
  1050. }
  1051. ///////////////////////////////////////////////////////////////////////
  1052. //Add action schedule object for disconnect control to close the led.
  1053. ///////////////////////////////////////////////////////////////////////
  1054. int addActionScheduleDisconnectClose()
  1055. {
  1056. int ret;
  1057. const unsigned char ln[6] = { 0, 0, 15, 0, 1, 255 };
  1058. static gxtime EXECUTION_TIMES[10];
  1059. if ((ret = INIT_OBJECT(actionScheduleDisconnectClose, DLMS_OBJECT_TYPE_ACTION_SCHEDULE, ln)) == 0)
  1060. {
  1061. actionScheduleDisconnectClose.executedScript = &scriptTableDisconnectControl;
  1062. actionScheduleDisconnectClose.executedScriptSelector = 1;
  1063. actionScheduleDisconnectClose.type = DLMS_SINGLE_ACTION_SCHEDULE_TYPE1;
  1064. ARR_ATTACH(actionScheduleDisconnectClose.executionTime, EXECUTION_TIMES, 0);
  1065. }
  1066. return ret;
  1067. }
  1068.  
  1069. ///////////////////////////////////////////////////////////////////////
  1070. //Add action schedule object for disconnect control to open the led.
  1071. ///////////////////////////////////////////////////////////////////////
  1072. int addActionScheduleDisconnectOpen()
  1073. {
  1074. int ret;
  1075. const unsigned char ln[6] = { 0, 0, 15, 0, 3, 255 };
  1076. static gxtime EXECUTION_TIMES[10];
  1077. //Action schedule execution times.
  1078. if ((ret = INIT_OBJECT(actionScheduleDisconnectOpen, DLMS_OBJECT_TYPE_ACTION_SCHEDULE, ln)) == 0)
  1079. {
  1080. actionScheduleDisconnectOpen.executedScript = &scriptTableDisconnectControl;
  1081. actionScheduleDisconnectOpen.executedScriptSelector = 2;
  1082. actionScheduleDisconnectOpen.type = DLMS_SINGLE_ACTION_SCHEDULE_TYPE1;
  1083. ARR_ATTACH(actionScheduleDisconnectOpen.executionTime, EXECUTION_TIMES, 0);
  1084. }
  1085. return ret;
  1086. }
  1087.  
  1088. ///////////////////////////////////////////////////////////////////////
  1089. //Add Disconnect control object.
  1090. ///////////////////////////////////////////////////////////////////////
  1091. int addDisconnectControl()
  1092. {
  1093. int ret;
  1094. const unsigned char ln[6] = { 0, 0, 96, 3, 10, 255 };
  1095. if ((ret = INIT_OBJECT(disconnectControl, DLMS_OBJECT_TYPE_DISCONNECT_CONTROL, ln)) == 0)
  1096. {
  1097. }
  1098. return ret;
  1099. }
  1100.  
  1101.  
  1102. ///////////////////////////////////////////////////////////////////////
  1103. //Add IEC HDLC Setup object.
  1104. ///////////////////////////////////////////////////////////////////////
  1105. int addIecHdlcSetup()
  1106. {
  1107. int ret = 0;
  1108. unsigned char ln[6] = { 0, 0, 22, 0, 0, 255 };
  1109. if ((ret = INIT_OBJECT(hdlc, DLMS_OBJECT_TYPE_IEC_HDLC_SETUP, ln)) == 0)
  1110. {
  1111. hdlc.communicationSpeed = DLMS_BAUD_RATE_9600;
  1112. hdlc.windowSizeReceive = hdlc.windowSizeTransmit = 1;
  1113. hdlc.maximumInfoLengthTransmit = hdlc.maximumInfoLengthReceive = 128;
  1114. hdlc.inactivityTimeout = 120;
  1115. hdlc.deviceAddress = 0x10;
  1116. }
  1117. Server.setHdlc(&hdlc);
  1118. return ret;
  1119. }
  1120.  
  1121. #ifdef USE_TIME_INTERRUPT
  1122.  
  1123. #ifndef ESP_PLATFORM
  1124. // Increase the time once per second.
  1125. ISR(TIMER1_COMPA_vect) {
  1126. ++clock1.time.value;
  1127. }
  1128. #else
  1129. hw_timer_t * timer = NULL;
  1130. void IRAM_ATTR onTime() {
  1131. ++clock1.time.value;
  1132. }
  1133. #endif //ESP_PLATFORM
  1134.  
  1135. /*
  1136. Use interrupts to increase the time.
  1137. */
  1138. void setTimer()
  1139. {
  1140. #ifndef ESP_PLATFORM
  1141. //Stop interrupts.
  1142. cli();
  1143. //set timer1 interrupt at 1Hz
  1144. TCCR1A = 0;
  1145. TCCR1B = 0;
  1146. //Initialize counter value to 0
  1147. TCNT1 = 0;
  1148. // set compare match register for 1hz increments
  1149. OCR1A = 15624;// = (16*10^6) / (1*1024) - 1 (must be < 65536)
  1150. // turn on CTC mode
  1151. TCCR1B |= (1 << WGM12);
  1152. // Set CS12 and CS10 bits for 1024 prescaler
  1153. TCCR1B |= (1 << CS12) | (1 << CS10);
  1154. // enable timer compare interrupt
  1155. TIMSK1 |= (1 << OCIE1A);
  1156. //Allow interrupts.
  1157. sei();
  1158. #else
  1159. timer = timerBegin(0, 80, true);
  1160. timerAttachInterrupt(timer, &onTime, true);
  1161. timerAlarmWrite(timer, 1000000, true);
  1162. timerAlarmEnable(timer);
  1163. #endif //ESP_PLATFORM
  1164. }
  1165.  
  1166. #endif //USE_TIME_INTERRUPT
  1167.  
  1168. //Create objects and load values from EEPROM.
  1169. void createObjects()
  1170. {
  1171. int ret;
  1172. if ((ret = addLogicalDeviceName()) != 0 ||
  1173. (ret = addEeprom()) != 0 ||
  1174. (ret = addTestMode()) != 0 ||
  1175. (ret = addBlockCipherKey()) != 0 ||
  1176. (ret = addAuthenticationKey()) != 0 ||
  1177. (ret = addKek()) != 0 ||
  1178. (ret = addServerInvocationCounter()) != 0 ||
  1179. (ret = addEventCode()) != 0 ||
  1180. (ret = addUnixTime()) != 0 ||
  1181. (ret = addInvocationCounter()) != 0 ||
  1182. (ret = addClockObject()) != 0 ||
  1183. (ret = addRegisterObject()) != 0 ||
  1184. (ret = addAssociationNone()) != 0 ||
  1185. (ret = addAssociationLow()) != 0 ||
  1186. (ret = addAssociationHigh()) != 0 ||
  1187. (ret = addAssociationHighGMac()) != 0 ||
  1188. (ret = addSecuritySetupLow()) != 0 ||
  1189. (ret = addSecuritySetupHigh()) != 0 ||
  1190. (ret = addPushSetup()) != 0 ||
  1191. (ret = addscriptTableGlobalMeterReset()) != 0 ||
  1192. (ret = addscriptTableDisconnectControl()) != 0 ||
  1193. (ret = addscriptTableActivatetestMode()) != 0 ||
  1194. (ret = addscriptTableActivateNormalMode()) != 0 ||
  1195. (ret = addLoadProfileProfileGeneric()) != 0 ||
  1196. (ret = addEventLogProfileGeneric()) != 0 ||
  1197. (ret = addActionScheduleDisconnectOpen()) != 0 ||
  1198. (ret = addActionScheduleDisconnectClose()) != 0 ||
  1199. (ret = addDisconnectControl()) != 0 ||
  1200. (ret = addIecHdlcSetup()) != 0 ||
  1201. (ret = Server.initObjects(ALL_OBJECTS, sizeof(ALL_OBJECTS) / sizeof(ALL_OBJECTS[0]))) != 0 ||
  1202. (ret = Server.internalObjects(INTERNAL_OBJECTS, sizeof(INTERNAL_OBJECTS) / sizeof(INTERNAL_OBJECTS[0]))) != 0 ||
  1203. //Start server
  1204. (ret = Server.initialize()) != 0)
  1205. {
  1206. GXTRACE_INT(GET_STR_FROM_EEPROM("Failed to start the meter!"), ret);
  1207. executeTime = 0;
  1208. return;
  1209. }
  1210. if ((ret = loadSettings()) != 0)
  1211. {
  1212. GXTRACE_INT(GET_STR_FROM_EEPROM("Failed to load settings from EEPROM."), ret);
  1213. executeTime = 0;
  1214. }
  1215. GXTRACE(GET_STR_FROM_EEPROM("Meter started."), NULL);
  1216. }
  1217.  
  1218. //Get HDLC communication speed.
  1219. int32_t getCommunicationSpeed()
  1220. {
  1221. int32_t ret = 9600;
  1222. switch (hdlc.communicationSpeed)
  1223. {
  1224. case DLMS_BAUD_RATE_300:
  1225. ret = 300;
  1226. break;
  1227. case DLMS_BAUD_RATE_600:
  1228. ret = 600;
  1229. break;
  1230. case DLMS_BAUD_RATE_1200:
  1231. ret = 1200;
  1232. break;
  1233. case DLMS_BAUD_RATE_2400:
  1234. ret = 2400;
  1235. break;
  1236. case DLMS_BAUD_RATE_4800:
  1237. ret = 4800;
  1238. break;
  1239. case DLMS_BAUD_RATE_9600:
  1240. ret = 9600;
  1241. break;
  1242. case DLMS_BAUD_RATE_19200:
  1243. ret = 19200;
  1244. break;
  1245. case DLMS_BAUD_RATE_38400:
  1246. ret = 38400;
  1247. break;
  1248. case DLMS_BAUD_RATE_57600:
  1249. ret = 57600;
  1250. break;
  1251. case DLMS_BAUD_RATE_115200:
  1252. ret = 115200;
  1253. break;
  1254. }
  1255. return ret;
  1256. }
  1257.  
  1258. void setup() {
  1259. //Initialize serialization settings.
  1260. ser_init(&serializerSettings);
  1261. serializerSettings.ignoredAttributes = NON_SERIALIZED_OBJECTS;
  1262. serializerSettings.count = sizeof(NON_SERIALIZED_OBJECTS) / sizeof(NON_SERIALIZED_OBJECTS[0]);
  1263.  
  1264. //Add FLAG ID.
  1265. memcpy(SERVER_SYSTEM_TITLE, FLAG_ID, 3);
  1266. //ADD serial number.
  1267. memcpy(SERVER_SYSTEM_TITLE + 4, &SERIAL_NUMBER, 4);
  1268. #ifndef ARDUINO_ARCH_ESP32
  1269. // initialize digital pin LED_BUILTIN as an output.
  1270. pinMode(LED_BUILTIN, OUTPUT);
  1271. #endif //ARDUINO_ARCH_ESP32
  1272. bb_attach(&reply, replyFrame, 0, sizeof(replyFrame));
  1273. Server.init(true, DLMS_INTERFACE_TYPE_HDLC, HDLC_BUFFER_SIZE, PDU_BUFFER_SIZE, frameBuff, sizeof(frameBuff), pduBuff, sizeof(pduBuff));
  1274. Server.SetPushClientAddress(64);
  1275. //Serial 1 is used to send trace.
  1276. Serial1.begin(9600);
  1277. createObjects();
  1278. //Set default clock.
  1279. Server.setDefaultClock(&clock1);
  1280. char testmode = GX_GET_BOOL(testMode.value);
  1281. GX_BOOL(testMode.value) = 1;
  1282. //Communication speed is trace always because this is causing most of the problems.
  1283. GXTRACE_INT(GET_STR_FROM_EEPROM("Communication speed"), getCommunicationSpeed());
  1284. if (testmode)
  1285. {
  1286. GXTRACE(GET_STR_FROM_EEPROM("Test mode Is ON."), NULL);
  1287. }
  1288. else
  1289. {
  1290. GXTRACE(GET_STR_FROM_EEPROM("Test mode Is OFF."), NULL);
  1291. }
  1292. GXTRACE(GET_STR_FROM_EEPROM("LLS password: "), (char*)associationLow.secret.data);
  1293. GXTRACE(GET_STR_FROM_EEPROM("HLS password: "), (char*)associationHigh.secret.data);
  1294. GX_BOOL(testMode.value) = testmode;
  1295. // start serial port with wanted communication speed:
  1296. Serial.begin(getCommunicationSpeed());
  1297. while (!Serial) {
  1298. // ; // wait for serial port to connect. Needed for native USB port only
  1299. }
  1300. updateState(GURUX_EVENT_CODES_POWER_UP);
  1301. GXTRACE_INT(GET_STR_FROM_EEPROM("EEPROM size"), EEPROM.length());
  1302.  
  1303. #ifdef ARDUINO_ARCH_ESP8266
  1304. //Start Wifi.
  1305. WiFi.mode(WIFI_STA);
  1306. WiFi.begin(ssid, password);
  1307. while (WiFi.waitForConnectResult() != WL_CONNECTED) {
  1308. GXTRACE(GET_STR_FROM_EEPROM("Connection Failed! Rebooting..."), NULL);
  1309. delay(2000);
  1310. }
  1311. tcpServer.begin();
  1312. Serial.print(WiFi.localIP().toString().c_str());
  1313. GXTRACE(PSTR("Server started with IP address."), WiFi.localIP().toString().c_str());
  1314. #endif //ARDUINO_ARCH_ESP8266
  1315.  
  1316. #ifdef USE_TIME_INTERRUPT
  1317. setTimer();
  1318. #endif //USE_TIME_INTERRUPT
  1319. executeTime = 0;
  1320. GXTRACE(GET_STR_FROM_EEPROM("Server started."), NULL);
  1321. }
  1322.  
  1323. void loop() {
  1324. static unsigned char tmp[50];
  1325. uint32_t start = time_current();
  1326. int available;
  1327. //Execute invokes when needed.
  1328. if (executeTime <= start)
  1329. {
  1330. Server.run(start, &executeTime);
  1331. }
  1332. #ifdef ARDUINO_ARCH_ESP8266
  1333. WiFiClient client = tcpServer.available();
  1334. if (client)
  1335. {
  1336. if (client.connected())
  1337. {
  1338. GXTRACE(PSTR("Client Connected"), NULL);
  1339. }
  1340. while (client.connected()) {
  1341. //Execute invokes when needed.
  1342. if (executeTime <= start)
  1343. {
  1344. Server.run(start, &executeTime);
  1345. }
  1346. available = client.available();
  1347. if (available > 0)
  1348. {
  1349. if (available > sizeof(tmp))
  1350. {
  1351. available = sizeof(tmp);
  1352. }
  1353. available = client.readBytes(tmp, available);
  1354. if ((available = Server.handleRequest(tmp, available, &reply)) != 0)
  1355. {
  1356. GXTRACE_INT(PSTR("handleRequest failed:"), available);
  1357. bb_clear(&reply);
  1358. }
  1359. if (reply.size != 0)
  1360. {
  1361. //Send reply.
  1362. client.write(reply.data, reply.size);
  1363. bb_clear(&reply);
  1364. }
  1365. }
  1366. }
  1367. client.stop();
  1368. GXTRACE(PSTR("Client disconnected"), NULL);
  1369. }
  1370. #endif //ARDUINO_ARCH_ESP8266
  1371. available = Serial.available();
  1372. if (available > 0)
  1373. {
  1374. if (available > sizeof(tmp))
  1375. {
  1376. available = sizeof(tmp);
  1377. }
  1378. available = Serial.readBytes((char*) tmp, available);
  1379. if ((available = Server.handleRequest(tmp, available, &reply)) != 0)
  1380. {
  1381. GXTRACE_INT(GET_STR_FROM_EEPROM("handleRequest failed:"), available);
  1382. bb_clear(&reply);
  1383. }
  1384. if (reply.size != 0)
  1385. {
  1386. //Send reply.
  1387. Serial.write(reply.data, reply.size);
  1388. Serial.flush();
  1389. bb_clear(&reply);
  1390. }
  1391. }
  1392. }
  1393.  
  1394.  
  1395. int svr_findObject(
  1396. dlmsSettings* settings,
  1397. DLMS_OBJECT_TYPE objectType,
  1398. int sn,
  1399. unsigned char* ln,
  1400. gxValueEventArg* e)
  1401. {
  1402. GXTRACE_LN(GET_STR_FROM_EEPROM("findObject"), objectType, ln);
  1403. if (objectType == DLMS_OBJECT_TYPE_ASSOCIATION_LOGICAL_NAME)
  1404. {
  1405. if (settings->authentication == DLMS_AUTHENTICATION_NONE)
  1406. {
  1407. e->target = BASE(associationNone);
  1408. }
  1409. else if (settings->authentication == DLMS_AUTHENTICATION_LOW)
  1410. {
  1411. e->target = BASE(associationLow);
  1412. }
  1413. else if (settings->authentication == DLMS_AUTHENTICATION_HIGH)
  1414. {
  1415. e->target = BASE(associationHigh);
  1416. }
  1417. else if (settings->authentication == DLMS_AUTHENTICATION_HIGH_GMAC)
  1418. {
  1419. e->target = BASE(associationHighGMac);
  1420. }
  1421. }
  1422. return 0;
  1423. }
  1424.  
  1425. /**
  1426. Find restricting object.
  1427. */
  1428. int getRestrictingObject(dlmsSettings* settings, gxValueEventArg* e, gxObject** obj, short* index)
  1429. {
  1430. int ret;
  1431. unsigned char ln[6];
  1432. uint16_t ot;
  1433. signed char aIndex;
  1434. uint16_t dIndex;
  1435. if ((ret = cosem_checkStructure(e->parameters.byteArr, 4)) == 0 &&
  1436. (ret = cosem_checkStructure(e->parameters.byteArr, 4)) == 0 &&
  1437. (ret = cosem_getUInt16(e->parameters.byteArr, &ot)) == 0 &&
  1438. (ret = cosem_getOctetString2(e->parameters.byteArr, ln, 6, NULL)) == 0 &&
  1439. (ret = cosem_getInt8(e->parameters.byteArr, &aIndex)) == 0 &&
  1440. (ret = cosem_getUInt16(e->parameters.byteArr, &dIndex)) == 0)
  1441. {
  1442. }
  1443. return ret;
  1444. }
  1445.  
  1446. /**
  1447. Find start index and row count using start and end date time.
  1448.  
  1449. settings: DLMS settings.
  1450. Start time.
  1451. type: Profile Generic type.
  1452. e: Parameters
  1453. */
  1454. int getProfileGenericDataByRangeFromRingBuffer(
  1455. dlmsSettings* settings,
  1456. unsigned char type,
  1457. gxValueEventArg* e)
  1458. {
  1459. gxtime start;
  1460. gxtime end;
  1461. uint32_t pos;
  1462. uint32_t last = 0;
  1463. int ret;
  1464. gxObject* obj = NULL;
  1465. short index;
  1466. if ((ret = getRestrictingObject(settings, e, &obj, &index)) != 0 ||
  1467. (ret = cosem_getDateTimeFromOctetString(e->parameters.byteArr, &start)) != 0 ||
  1468. (ret = cosem_getDateTimeFromOctetString(e->parameters.byteArr, &end)) != 0)
  1469. {
  1470. return ret;
  1471. }
  1472. uint32_t s = time_toUnixTime2(&start);
  1473. uint32_t l = time_toUnixTime2(&end);
  1474. uint32_t t;
  1475. gxLoadProfileData lp;
  1476. gxEventLogData event1;
  1477. gxProfileGeneric* p = (gxProfileGeneric*)e->target;
  1478. for (pos = 0; pos != p->entriesInUse; ++pos)
  1479. {
  1480. //Load data from EEPROM.
  1481. if (type == 0)
  1482. {
  1483. SERIALIZER_LOAD(SETTINGS_BUFFER_SIZE + (pos * sizeof(gxLoadProfileData)), sizeof(gxLoadProfileData), &lp);
  1484. t = lp.time;
  1485. }
  1486. else
  1487. {
  1488. SERIALIZER_LOAD(SETTINGS_BUFFER_SIZE + LOAD_PROFILE_BUFFER_SIZE + (pos * sizeof(gxEventLogData)), sizeof(gxEventLogData), &event1);
  1489. t = event1.time;
  1490. }
  1491. //If value is inside of start and end time.
  1492. if (t >= s && t <= l)
  1493. {
  1494. if (last == 0)
  1495. {
  1496. //Save end position if we have only one row.
  1497. e->transactionEndIndex = e->transactionStartIndex = 1 + pos;
  1498. }
  1499. else
  1500. {
  1501. if (last <= t)
  1502. {
  1503. e->transactionEndIndex = pos + 1;
  1504. }
  1505. else
  1506. {
  1507. //Index is one based, not zero.
  1508. if (e->transactionEndIndex == 0)
  1509. {
  1510. ++e->transactionEndIndex;
  1511. }
  1512. e->transactionEndIndex += p->entriesInUse - 1;
  1513. e->transactionStartIndex = pos;
  1514. break;
  1515. }
  1516. }
  1517. last = t;
  1518. }
  1519. }
  1520. return ret;
  1521. }
  1522.  
  1523. int readProfileGeneric(
  1524. dlmsSettings* settings,
  1525. gxProfileGeneric* pg,
  1526. unsigned char type,
  1527. gxValueEventArg* e)
  1528. {
  1529. unsigned char first = e->transactionEndIndex == 0;
  1530. int ret = 0;
  1531. gxArray captureObjects;
  1532. gxTarget CAPTURE_OBJECT[10] = { 0 };
  1533. ARR_ATTACH(captureObjects, CAPTURE_OBJECT, 0);
  1534.  
  1535. e->byteArray = 1;
  1536. e->handled = 1;
  1537. // If reading first time.
  1538. if (first)
  1539. {
  1540. //Read all.
  1541. if (e->selector == 0)
  1542. {
  1543. e->transactionStartIndex = 1;
  1544. e->transactionEndIndex = pg->entriesInUse;
  1545. }
  1546. else if (e->selector == 1)
  1547. {
  1548. //Read by entry. Find start and end index from the ring buffer.
  1549. if ((ret = getProfileGenericDataByRangeFromRingBuffer(settings, type, e)) != 0 ||
  1550. (ret = cosem_getColumns(&pg->captureObjects, e->selector, &e->parameters, &captureObjects)) != 0)
  1551. {
  1552. e->transactionStartIndex = e->transactionEndIndex = 0;
  1553. }
  1554. }
  1555. else if (e->selector == 2)
  1556. {
  1557. if ((ret = cosem_checkStructure(e->parameters.byteArr, 4)) != 0 ||
  1558. (ret = cosem_getUInt32(e->parameters.byteArr, &e->transactionStartIndex)) != 0 ||
  1559. (ret = cosem_getUInt32(e->parameters.byteArr, &e->transactionEndIndex)) != 0 ||
  1560. (ret = cosem_getColumns(&pg->captureObjects, e->selector, &e->parameters, &captureObjects)) != 0)
  1561. {
  1562. e->transactionStartIndex = e->transactionEndIndex = 0;
  1563. }
  1564. else
  1565. {
  1566. //If start index is too high.
  1567. if (e->transactionStartIndex > pg->entriesInUse)
  1568. {
  1569. e->transactionStartIndex = e->transactionEndIndex = 0;
  1570. }
  1571. //If end index is too high.
  1572. if (e->transactionEndIndex > pg->entriesInUse)
  1573. {
  1574. e->transactionEndIndex = pg->entriesInUse;
  1575. }
  1576. }
  1577. }
  1578. }
  1579. bb_clear(e->value.byteArr);
  1580. if (ret == 0 && first)
  1581. {
  1582. if (e->transactionEndIndex == 0)
  1583. {
  1584. ret = cosem_setArray(e->value.byteArr, 0);
  1585. }
  1586. else
  1587. {
  1588. ret = cosem_setArray(e->value.byteArr, (uint16_t)(e->transactionEndIndex - e->transactionStartIndex + 1));
  1589. }
  1590. }
  1591. if (ret == 0 && e->transactionEndIndex != 0)
  1592. {
  1593. //Loop items.
  1594. uint32_t pos;
  1595. gxtime tm;
  1596. uint16_t pduSize;
  1597. gxLoadProfileData lp;
  1598. gxEventLogData event1;
  1599. for (pos = e->transactionStartIndex - 1; pos != e->transactionEndIndex; ++pos)
  1600. {
  1601. pduSize = e->value.byteArr->size;
  1602. //Load data from EEPROM.
  1603. if (type == 0)
  1604. {
  1605. SERIALIZER_LOAD(SETTINGS_BUFFER_SIZE + (pos * sizeof(gxLoadProfileData)), sizeof(gxLoadProfileData), &lp);
  1606. time_initUnix(&tm, lp.time);
  1607. if ((ret = cosem_setStructure(e->value.byteArr, 2)) != 0 ||
  1608. (ret = cosem_setDateTimeAsOctetString(e->value.byteArr, &tm)) != 0 ||
  1609. (ret = cosem_setUInt16(e->value.byteArr, lp.activePowerL1)) != 0)
  1610. {
  1611. //Error is handled later.
  1612. }
  1613. }
  1614. else
  1615. {
  1616. SERIALIZER_LOAD(SETTINGS_BUFFER_SIZE + LOAD_PROFILE_BUFFER_SIZE + (pos * sizeof(gxEventLogData)), sizeof(gxEventLogData), &event1);
  1617. time_initUnix(&tm, event1.time);
  1618. if ((ret = cosem_setStructure(e->value.byteArr, 2)) != 0 ||
  1619. (ret = cosem_setDateTimeAsOctetString(e->value.byteArr, &tm)) != 0 ||
  1620. (ret = cosem_setUInt16(e->value.byteArr, event1.event)) != 0)
  1621. {
  1622. //Error is handled later.
  1623. }
  1624. }
  1625. if (ret != 0)
  1626. {
  1627. //Don't set error if PDU is full,
  1628. if (ret == DLMS_ERROR_CODE_OUTOFMEMORY)
  1629. {
  1630. e->value.byteArr->size = pduSize;
  1631. ret = 0;
  1632. }
  1633. else
  1634. {
  1635. break;
  1636. }
  1637. break;
  1638. }
  1639. ++e->transactionStartIndex;
  1640. }
  1641. }
  1642. return ret;
  1643. }
  1644.  
  1645. /////////////////////////////////////////////////////////////////////////////
  1646. //
  1647. /////////////////////////////////////////////////////////////////////////////
  1648. void svr_preRead(
  1649. dlmsSettings* settings,
  1650. gxValueEventCollection* args)
  1651. {
  1652. gxValueEventArg* e;
  1653. int ret, pos;
  1654. DLMS_OBJECT_TYPE type;
  1655. for (pos = 0; pos != args->size; ++pos)
  1656. {
  1657. if ((ret = vec_getByIndex(args, pos, &e)) != 0)
  1658. {
  1659. return;
  1660. }
  1661. GXTRACE_LN(GET_STR_FROM_EEPROM("svr_preRead: "), e->target->objectType, e->target->logicalName);
  1662. //Let framework handle Logical Name read.
  1663. if (e->index == 1)
  1664. {
  1665. continue;
  1666. }
  1667. if (e->target == BASE(eeprom))
  1668. {
  1669. //If EEPROM is read.
  1670. gxSerializerSettings serializerSettings;
  1671. ser_init(&serializerSettings);
  1672. if (e->transactionEndIndex == 0)
  1673. {
  1674. uint32_t size;
  1675. if ((ret = ser_getDataSize(&serializerSettings, &size)) != 0)
  1676. {
  1677. GXTRACE_INT(GET_STR_FROM_EEPROM("ser_getDataSize failed: "), ret);
  1678. e->error = DLMS_ERROR_CODE_INVALID_PARAMETER;
  1679. break;
  1680. }
  1681. //Add version and data size to the data.
  1682. size += 5;
  1683. e->transactionStartIndex = 0;
  1684. e->transactionEndIndex = size;
  1685. bb_clear(e->value.byteArr);
  1686. bb_setUInt8(e->value.byteArr, DLMS_DATA_TYPE_OCTET_STRING);
  1687. hlp_setObjectCount(size, e->value.byteArr);
  1688. }
  1689. uint16_t count = (e->transactionEndIndex - e->transactionStartIndex);
  1690. if (count > 100)
  1691. {
  1692. count = 100;
  1693. }
  1694. unsigned char ch;
  1695. while (count != 0)
  1696. {
  1697. SERIALIZER_LOAD(e->transactionStartIndex, 1, &ch);
  1698. bb_setUInt8(e->value.byteArr, ch);
  1699. ++e->transactionStartIndex;
  1700. --count;
  1701. }
  1702. e->handled = 1;
  1703. }
  1704.  
  1705. //Get target type.
  1706. type = (DLMS_OBJECT_TYPE)e->target->objectType;
  1707. //Let Framework will handle Association objects and profile generic automatically.
  1708. if (type == DLMS_OBJECT_TYPE_ASSOCIATION_LOGICAL_NAME ||
  1709. type == DLMS_OBJECT_TYPE_ASSOCIATION_SHORT_NAME)
  1710. {
  1711. continue;
  1712. }
  1713. //Update value by one every time when user reads register.
  1714. //Get time if user want to read date and time.
  1715. if (e->target == BASE(clock1) && e->index == 2)
  1716. {
  1717. #ifndef USE_TIME_INTERRUPT
  1718. gxtime dt;
  1719. time_now(&dt, 1);
  1720. e->error = (DLMS_ERROR_CODE) cosem_setDateTimeAsOctetString(e->value.byteArr, &dt);
  1721. e->value.vt = DLMS_DATA_TYPE_DATETIME;
  1722. e->handled = 1;
  1723. #endif //USE_TIME_INTERRUPT
  1724. }
  1725. else if (e->target == BASE(profileGeneric) && e->index == 2)
  1726. {
  1727. e->error = (DLMS_ERROR_CODE)readProfileGeneric(settings, &profileGeneric, 0, e);
  1728. }
  1729. else if (e->target == BASE(eventLog) && e->index == 2)
  1730. {
  1731. e->error = (DLMS_ERROR_CODE)readProfileGeneric(settings, &eventLog, 1, e);
  1732. }
  1733. }
  1734. }
  1735.  
  1736. /////////////////////////////////////////////////////////////////////////////
  1737. //
  1738. /////////////////////////////////////////////////////////////////////////////
  1739. void svr_preWrite(
  1740. dlmsSettings* settings,
  1741. gxValueEventCollection* args)
  1742. {
  1743. gxValueEventArg* e;
  1744. int ret, pos;
  1745. for (pos = 0; pos != args->size; ++pos)
  1746. {
  1747. if ((ret = vec_getByIndex(args, pos, &e)) != 0)
  1748. {
  1749. return;
  1750. }
  1751. //Set new base time if user wants to set date and time.
  1752. if (e->target == BASE(clock1) && e->index == 2)
  1753. {
  1754. updateState(GURUX_EVENT_CODES_TIME_CHANGE);
  1755. #ifndef USE_TIME_INTERRUPT
  1756. started = time_elapsed();
  1757. #endif //USE_TIME_INTERRUPT
  1758. }
  1759. GXTRACE_LN(GET_STR_FROM_EEPROM("svr_preWrite: "), e->target->objectType, e->target->logicalName);
  1760. }
  1761. }
  1762.  
  1763. int sendPush(
  1764. dlmsSettings* settings,
  1765. gxPushSetup* push)
  1766. {
  1767. GXTRACE_LN(GET_STR_FROM_EEPROM("sendPush"), push->base.objectType, push->base.logicalName);
  1768. int ret, pos;
  1769. message messages;
  1770. if (push->pushObjectList.size == 0)
  1771. {
  1772. GXTRACE(GET_STR_FROM_EEPROM("sendPush Failed. No objects selected."), NULL);
  1773. return DLMS_ERROR_CODE_INVALID_PARAMETER;
  1774. }
  1775. unsigned char pduBuff[PDU_BUFFER_SIZE];
  1776. gxByteBuffer pdu;
  1777. bb_attach(&pdu, pduBuff, 0, sizeof(pduBuff));
  1778. settings->serializedPdu = &pdu;
  1779. unsigned char data[PDU_BUFFER_SIZE];
  1780. gxByteBuffer bb;
  1781. bb_attach(&bb, data, 0, sizeof(data));
  1782. gxByteBuffer* tmp[] = { &bb };
  1783. mes_attach(&messages, tmp, 1);
  1784. if ((ret = Server.generatePushSetupMessages(push, &messages)) == 0)
  1785. {
  1786. for (pos = 0; pos != messages.size; ++pos)
  1787. {
  1788. Serial.write(bb.data, bb.size);
  1789. Serial.flush();
  1790. }
  1791. }
  1792. if (ret != 0)
  1793. {
  1794. GXTRACE(GET_STR_FROM_EEPROM("generatePushSetupMessages Failed."), NULL);
  1795. }
  1796. mes_clear(&messages);
  1797. return ret;
  1798. }
  1799.  
  1800. uint16_t loadProfileRowIndex = 0;
  1801.  
  1802. void handleLoadProfileActions(
  1803. gxValueEventArg* it)
  1804. {
  1805. if (it->index == 1)
  1806. {
  1807. // Profile generic clear is called. Clear data.
  1808. profileGeneric.entriesInUse = 0;
  1809. loadProfileRowIndex = 0;
  1810. }
  1811. else if (it->index == 2)
  1812. {
  1813. gxLoadProfileData row;
  1814. // Profile generic Capture is called. Save data to the buffer.
  1815. //We are using ring buffer here.
  1816. row.time = time_current();
  1817. row.activePowerL1 = readActivePowerValue();
  1818. SERIALIZER_SAVE(SETTINGS_BUFFER_SIZE + loadProfileRowIndex * sizeof(gxLoadProfileData), sizeof(gxLoadProfileData), &row);
  1819. //Update how many entries is used until buffer is full.
  1820. if (profileGeneric.entriesInUse != profileGeneric.profileEntries)
  1821. {
  1822. ++profileGeneric.entriesInUse;
  1823. }
  1824. loadProfileRowIndex = loadProfileRowIndex % profileGeneric.profileEntries;
  1825. saveSettings(BASE(profileGeneric), GET_ATTRIBUTE(7));
  1826. }
  1827. }
  1828.  
  1829. void handleEventLogActions(
  1830. gxValueEventArg* it)
  1831. {
  1832. if (it->index == 1)
  1833. {
  1834. // Profile generic clear is called. Clear data.
  1835. eventLog.entriesInUse = 0;
  1836. eventLogRowIndex = 0;
  1837. }
  1838. else if (it->index == 2)
  1839. {
  1840. captureEventLog(readEventCode());
  1841. }
  1842. }
  1843.  
  1844. /////////////////////////////////////////////////////////////////////////////
  1845. //
  1846. /////////////////////////////////////////////////////////////////////////////
  1847. void svr_preAction(
  1848. dlmsSettings * settings,
  1849. gxValueEventCollection * args)
  1850. {
  1851. gxValueEventArg* e;
  1852. int ret, pos;
  1853. for (pos = 0; pos != args->size; ++pos)
  1854. {
  1855. if ((ret = vec_getByIndex(args, pos, &e)) != 0)
  1856. {
  1857. return;
  1858. }
  1859. GXTRACE_LN(GET_STR_FROM_EEPROM("svr_preAction: "), e->target->objectType, e->target->logicalName);
  1860. if (e->target == BASE(profileGeneric))
  1861. {
  1862. handleLoadProfileActions(e);
  1863. e->handled = 1;
  1864. }
  1865. else if (e->target == BASE(eventLog))
  1866. {
  1867. handleEventLogActions(e);
  1868. e->handled = 1;
  1869. }
  1870. else if (e->target == BASE(pushSetup) && e->index == 1)
  1871. {
  1872. updateState(GURUX_EVENT_CODES_PUSH);
  1873. sendPush(settings, (gxPushSetup*)e->target);
  1874. e->handled = 1;
  1875. }
  1876. //If client wants to clear EEPROM data using Global meter reset script.
  1877. else if (e->target == BASE(scriptTableGlobalMeterReset) && e->index == 1)
  1878. {
  1879. //Initialize serialization version number so default values are used on next connection.
  1880. EEPROM.write(0, 0);
  1881. //Load objects again.
  1882. createObjects();
  1883. //Uncomment this if you want to clear all data from the EEPROM.
  1884. //It's taking a long time.
  1885. /*
  1886. for (int i = 0; i < EEPROM.length(); i++)
  1887. {
  1888. EEPROM.write(i, 0xFF);
  1889. }
  1890. */
  1891. updateState(GURUX_EVENT_CODES_GLOBAL_METER_RESET);
  1892. e->handled = 1;
  1893. }
  1894. else if (e->target == BASE(disconnectControl))
  1895. {
  1896. updateState(GURUX_EVENT_CODES_OUTPUT_RELAY_STATE);
  1897. //Disconnect. Turn led OFF.
  1898. if (e->index == 1)
  1899. {
  1900. //If there is not buildin LED.
  1901. #ifndef ARDUINO_ARCH_ESP32
  1902. digitalWrite(LED_BUILTIN, LOW);
  1903. #endif //ARDUINO_ARCH_ESP32
  1904. }
  1905. else //Reconnnect. Turn LED ON.
  1906. {
  1907. //If there is not buildin LED.
  1908. #ifndef ARDUINO_ARCH_ESP32
  1909. digitalWrite(LED_BUILTIN, HIGH);
  1910. #endif //ARDUINO_ARCH_ESP32
  1911. }
  1912. }
  1913. else if (e->target == BASE(scriptTableActivatetestMode))
  1914. {
  1915. //Activate test mode.
  1916. GX_BOOL(testMode.value) = 1;
  1917. saveSettings(BASE(testMode), GET_ATTRIBUTE(2));
  1918. }
  1919. else if (e->target == BASE(scriptTableActivateNormalMode))
  1920. {
  1921. //Activate normal mode.
  1922. GX_BOOL(testMode.value) = 0;
  1923. saveSettings(BASE(testMode), GET_ATTRIBUTE(2));
  1924. }
  1925. }
  1926. }
  1927.  
  1928. /////////////////////////////////////////////////////////////////////////////
  1929. //
  1930. /////////////////////////////////////////////////////////////////////////////
  1931. void svr_postRead(
  1932. dlmsSettings * settings,
  1933. gxValueEventCollection * args)
  1934. {
  1935. gxValueEventArg* e;
  1936. int ret, pos;
  1937. for (pos = 0; pos != args->size; ++pos)
  1938. {
  1939. if ((ret = vec_getByIndex(args, pos, &e)) != 0)
  1940. {
  1941. return;
  1942. }
  1943. GXTRACE_LN(GET_STR_FROM_EEPROM("svr_postRead: "), e->target->objectType, e->target->logicalName);
  1944. }
  1945. }
  1946.  
  1947.  
  1948. /////////////////////////////////////////////////////////////////////////////
  1949. // Only updated value is saved. This is done because write to EEPROM is slow
  1950. // and there is a limit how many times value can be written to the EEPROM.
  1951. /////////////////////////////////////////////////////////////////////////////
  1952. void svr_postWrite(
  1953. dlmsSettings * settings,
  1954. gxValueEventCollection * args)
  1955. {
  1956. gxValueEventArg* e;
  1957. int ret, pos;
  1958. for (pos = 0; pos != args->size; ++pos)
  1959. {
  1960. if ((ret = vec_getByIndex(args, pos, &e)) != 0)
  1961. {
  1962. return;
  1963. }
  1964. GXTRACE_LN(GET_STR_FROM_EEPROM("svr_postWrite: "), e->target->objectType, e->target->logicalName);
  1965. if (e->error == 0)
  1966. {
  1967. //Save settings to EEPROM.
  1968. saveSettings(e->target, GET_ATTRIBUTE(e->index));
  1969. //This is only for serialization testing. It can be remove later.
  1970. loadSettings();
  1971. }
  1972. else
  1973. {
  1974. //Reject changes loading previous settings if there is an error.
  1975. loadSettings();
  1976. }
  1977. }
  1978. //Reset execute time to update execute time if user add new execute times or changes the time.
  1979. executeTime = 0;
  1980. }
  1981.  
  1982. /////////////////////////////////////////////////////////////////////////////
  1983. //
  1984. /////////////////////////////////////////////////////////////////////////////
  1985. void svr_postAction(
  1986. dlmsSettings * settings,
  1987. gxValueEventCollection * args)
  1988. {
  1989. gxValueEventArg* e;
  1990. int ret, pos;
  1991. uint32_t action;
  1992. for (pos = 0; pos != args->size; ++pos)
  1993. {
  1994. if ((ret = vec_getByIndex(args, pos, &e)) != 0)
  1995. {
  1996. return;
  1997. }
  1998. GXTRACE_LN(GET_STR_FROM_EEPROM("svr_postAction: "), e->target->objectType, e->target->logicalName);
  1999. if ((action = Server.isChangedWithAction((DLMS_OBJECT_TYPE)e->target->objectType, e->index)) != 0)
  2000. {
  2001. //Save settings to EEPROM.
  2002. if (e->error == 0)
  2003. {
  2004. saveSettings(e->target, action);
  2005. }
  2006. else
  2007. {
  2008. //Load default settings if there is an error.
  2009. loadSettings();
  2010. }
  2011. }
  2012. }
  2013. }
  2014.  
  2015. unsigned char svr_isTarget(
  2016. dlmsSettings * settings,
  2017. uint32_t serverAddress,
  2018. uint32_t clientAddress)
  2019. {
  2020. GXTRACE(GET_STR_FROM_EEPROM("svr_isTarget."), NULL);
  2021. objectArray objects;
  2022. oa_init(&objects);
  2023. unsigned char ret = 0;
  2024. uint16_t pos;
  2025. gxObject* tmp[6];
  2026. oa_attach(&objects, tmp, sizeof(tmp) / sizeof(tmp[0]));
  2027. objects.size = 0;
  2028. if (oa_getObjects(&settings->objects, DLMS_OBJECT_TYPE_ASSOCIATION_LOGICAL_NAME, &objects) == 0)
  2029. {
  2030. gxAssociationLogicalName* a;
  2031. for (pos = 0; pos != objects.size; ++pos)
  2032. {
  2033. if (oa_getByIndex(&objects, pos, (gxObject**)&a) == 0)
  2034. {
  2035. if (a->clientSAP == clientAddress)
  2036. {
  2037. ret = 1;
  2038. switch (a->authenticationMechanismName.mechanismId)
  2039. {
  2040. case DLMS_AUTHENTICATION_NONE:
  2041. //Client connects without authentication.
  2042. GXTRACE(GET_STR_FROM_EEPROM("Connecting without authentication."), NULL);
  2043. break;
  2044. case DLMS_AUTHENTICATION_LOW:
  2045. //Client connects using low authentication.
  2046. GXTRACE(GET_STR_FROM_EEPROM("Connecting using Low authentication."), NULL);
  2047. break;
  2048. default:
  2049. //Client connects using High authentication.
  2050. GXTRACE(GET_STR_FROM_EEPROM("Connecting using High authentication."), NULL);
  2051. break;
  2052. }
  2053. break;
  2054. }
  2055. }
  2056. }
  2057. }
  2058. if (ret == 0)
  2059. {
  2060. GXTRACE_INT(GET_STR_FROM_EEPROM("Invalid authentication level."), clientAddress);
  2061. //Authentication is now allowed. Meter is quiet and doesn't return an error.
  2062. }
  2063. else
  2064. {
  2065. // If address is not broadcast or serial number.
  2066. if (!(serverAddress == 1 || serverAddress == 0x3FFF || serverAddress == 0x7F ||
  2067. (serverAddress & 0x3FFF) == SERIAL_NUMBER % 10000 + 1000))
  2068. {
  2069. ret = 0;
  2070. }
  2071. if (ret == 0)
  2072. {
  2073. GXTRACE_INT(GET_STR_FROM_EEPROM("Invalid server address"), serverAddress);
  2074. }
  2075. }
  2076. return ret;
  2077. }
  2078.  
  2079. DLMS_SOURCE_DIAGNOSTIC svr_validateAuthentication(
  2080. dlmsServerSettings * settings,
  2081. DLMS_AUTHENTICATION authentication,
  2082. gxByteBuffer * password)
  2083. {
  2084. GXTRACE(GET_STR_FROM_EEPROM("svr_validateAuthentication"), NULL);
  2085. if (authentication == DLMS_AUTHENTICATION_NONE)
  2086. {
  2087. //Uncomment this if authentication is always required.
  2088. //return DLMS_SOURCE_DIAGNOSTIC_AUTHENTICATION_MECHANISM_NAME_REQUIRED;
  2089. return DLMS_SOURCE_DIAGNOSTIC_NONE;
  2090. }
  2091. //Check Low Level security..
  2092. if (authentication == DLMS_AUTHENTICATION_LOW)
  2093. {
  2094. if (bb_compare(password, associationLow.secret.data, associationLow.secret.size) == 0)
  2095. {
  2096. GXTRACE(GET_STR_FROM_EEPROM("Invalid low level password."), (char*) password->data);
  2097. return DLMS_SOURCE_DIAGNOSTIC_AUTHENTICATION_FAILURE;
  2098. }
  2099. GXTRACE(GET_STR_FROM_EEPROM("Valid low level password."), (char*)password->data);
  2100. }
  2101. // High authentication levels are check on phase two.
  2102. return DLMS_SOURCE_DIAGNOSTIC_NONE;
  2103. }
  2104.  
  2105. //Get attribute access level for profile generic.
  2106. DLMS_ACCESS_MODE getProfileGenericAttributeAccess(
  2107. dlmsSettings* settings,
  2108. gxObject* obj,
  2109. unsigned char index)
  2110. {
  2111. //Only read is allowed for event log.
  2112. if (obj == BASE(eventLog))
  2113. {
  2114. return DLMS_ACCESS_MODE_READ;
  2115. }
  2116. //Write is allowed only for High authentication.
  2117. if (settings->authentication > DLMS_AUTHENTICATION_LOW)
  2118. {
  2119. switch (index)
  2120. {
  2121. case 4://capturePeriod
  2122. return DLMS_ACCESS_MODE_READ_WRITE;
  2123. default:
  2124. break;
  2125. }
  2126. }
  2127. return DLMS_ACCESS_MODE_READ;
  2128. }
  2129.  
  2130. //Get attribute access level for Push Setup.
  2131. DLMS_ACCESS_MODE getPushSetupAttributeAccess(
  2132. dlmsSettings* settings,
  2133. unsigned char index)
  2134. {
  2135. //Write is allowed only for High authentication.
  2136. if (settings->authentication > DLMS_AUTHENTICATION_LOW)
  2137. {
  2138. switch (index)
  2139. {
  2140. case 2://pushObjectList
  2141. case 4://communicationWindow
  2142. return DLMS_ACCESS_MODE_READ_WRITE;
  2143. default:
  2144. break;
  2145. }
  2146. }
  2147. return DLMS_ACCESS_MODE_READ;
  2148. }
  2149.  
  2150. //Get attribute access level for Disconnect Control.
  2151. DLMS_ACCESS_MODE getDisconnectControlAttributeAccess(
  2152. dlmsSettings* settings,
  2153. unsigned char index)
  2154. {
  2155. return DLMS_ACCESS_MODE_READ;
  2156. }
  2157.  
  2158. //Get attribute access level for register schedule.
  2159. DLMS_ACCESS_MODE getActionSchduleAttributeAccess(
  2160. dlmsSettings* settings,
  2161. unsigned char index)
  2162. {
  2163. //Write is allowed only for High authentication.
  2164. if (settings->authentication > DLMS_AUTHENTICATION_LOW)
  2165. {
  2166. switch (index)
  2167. {
  2168. case 4://Execution time.
  2169. return DLMS_ACCESS_MODE_READ_WRITE;
  2170. default:
  2171. break;
  2172. }
  2173. }
  2174. return DLMS_ACCESS_MODE_READ;
  2175. }
  2176.  
  2177. //Get attribute access level for register.
  2178. DLMS_ACCESS_MODE getRegisterAttributeAccess(
  2179. dlmsSettings* settings,
  2180. unsigned char index)
  2181. {
  2182. return DLMS_ACCESS_MODE_READ;
  2183. }
  2184.  
  2185. //Get attribute access level for data objects.
  2186. DLMS_ACCESS_MODE getDataAttributeAccess(
  2187. dlmsSettings* settings,
  2188. unsigned char index)
  2189. {
  2190. return DLMS_ACCESS_MODE_READ;
  2191. }
  2192.  
  2193. //Get attribute access level for script table.
  2194. DLMS_ACCESS_MODE getScriptTableAttributeAccess(
  2195. dlmsSettings* settings,
  2196. unsigned char index)
  2197. {
  2198. return DLMS_ACCESS_MODE_READ;
  2199. }
  2200.  
  2201. //Get attribute access level for IEC HDLS setup.
  2202. DLMS_ACCESS_MODE getHdlcSetupAttributeAccess(
  2203. dlmsSettings* settings,
  2204. unsigned char index)
  2205. {
  2206. //Write is allowed only for High authentication.
  2207. if (settings->authentication > DLMS_AUTHENTICATION_LOW)
  2208. {
  2209. switch (index)
  2210. {
  2211. case 2: //Communication speed.
  2212. case 7:
  2213. case 8:
  2214. return DLMS_ACCESS_MODE_READ_WRITE;
  2215. default:
  2216. break;
  2217. }
  2218. }
  2219. return DLMS_ACCESS_MODE_READ;
  2220. }
  2221.  
  2222.  
  2223. //Get attribute access level for association LN.
  2224. DLMS_ACCESS_MODE getAssociationAttributeAccess(
  2225. dlmsSettings* settings,
  2226. unsigned char index)
  2227. {
  2228. //If secret
  2229. if (settings->authentication == DLMS_AUTHENTICATION_LOW && index == 7)
  2230. {
  2231. return DLMS_ACCESS_MODE_READ_WRITE;
  2232. }
  2233. return DLMS_ACCESS_MODE_READ;
  2234. }
  2235.  
  2236. /**
  2237. Get attribute access level.
  2238. */
  2239. DLMS_ACCESS_MODE svr_getAttributeAccess(
  2240. dlmsSettings * settings,
  2241. gxObject * obj,
  2242. unsigned char index)
  2243. {
  2244. //GXTRACE("svr_getAttributeAccess", NULL);
  2245. // Only read is allowed if authentication is not used.
  2246. if (index == 1 || settings->authentication == DLMS_AUTHENTICATION_NONE)
  2247. {
  2248. return DLMS_ACCESS_MODE_READ;
  2249. }
  2250. if (obj->objectType == DLMS_OBJECT_TYPE_ASSOCIATION_LOGICAL_NAME)
  2251. {
  2252. return getAssociationAttributeAccess(settings, index);
  2253. }
  2254. if (obj->objectType == DLMS_OBJECT_TYPE_PROFILE_GENERIC)
  2255. {
  2256. return getProfileGenericAttributeAccess(settings, obj, index);
  2257. }
  2258. if (obj->objectType == DLMS_OBJECT_TYPE_PUSH_SETUP)
  2259. {
  2260. return getPushSetupAttributeAccess(settings, index);
  2261. }
  2262. if (obj->objectType == DLMS_OBJECT_TYPE_DISCONNECT_CONTROL)
  2263. {
  2264. return getDisconnectControlAttributeAccess(settings, index);
  2265. }
  2266. if (obj->objectType == DLMS_OBJECT_TYPE_DISCONNECT_CONTROL)
  2267. {
  2268. return getDisconnectControlAttributeAccess(settings, index);
  2269. }
  2270. if (obj->objectType == DLMS_OBJECT_TYPE_ACTION_SCHEDULE)
  2271. {
  2272. return getActionSchduleAttributeAccess(settings, index);
  2273. }
  2274. if (obj->objectType == DLMS_OBJECT_TYPE_SCRIPT_TABLE)
  2275. {
  2276. return getScriptTableAttributeAccess(settings, index);
  2277. }
  2278. if (obj->objectType == DLMS_OBJECT_TYPE_REGISTER)
  2279. {
  2280. return getRegisterAttributeAccess(settings, index);
  2281. }
  2282. if (obj->objectType == DLMS_OBJECT_TYPE_DATA)
  2283. {
  2284. return getDataAttributeAccess(settings, index);
  2285. }
  2286. if (obj->objectType == DLMS_OBJECT_TYPE_IEC_HDLC_SETUP)
  2287. {
  2288. return getHdlcSetupAttributeAccess(settings, index);
  2289. }
  2290.  
  2291. // Only read is allowed for Low authentication.
  2292. if (settings->authentication == DLMS_AUTHENTICATION_LOW)
  2293. {
  2294. return DLMS_ACCESS_MODE_READ;
  2295. }
  2296. // All writes are allowed for High authentication.
  2297. return DLMS_ACCESS_MODE_READ_WRITE;
  2298. }
  2299.  
  2300. /**
  2301. Get method access level.
  2302. */
  2303. DLMS_METHOD_ACCESS_MODE svr_getMethodAccess(
  2304. dlmsSettings * settings,
  2305. gxObject * obj,
  2306. unsigned char index)
  2307. {
  2308. // Methods are not allowed.
  2309. if (settings->authentication == DLMS_AUTHENTICATION_NONE)
  2310. {
  2311. return DLMS_METHOD_ACCESS_MODE_NONE;
  2312. }
  2313. // Only clock methods are allowed.
  2314. if (settings->authentication == DLMS_AUTHENTICATION_LOW)
  2315. {
  2316. if (obj->objectType == DLMS_OBJECT_TYPE_CLOCK)
  2317. {
  2318. return DLMS_METHOD_ACCESS_MODE_ACCESS;
  2319. }
  2320. return DLMS_METHOD_ACCESS_MODE_NONE;
  2321. }
  2322. return DLMS_METHOD_ACCESS_MODE_ACCESS;
  2323. }
  2324.  
  2325. /////////////////////////////////////////////////////////////////////////////
  2326. //Client has made connection to the server.
  2327. /////////////////////////////////////////////////////////////////////////////
  2328. int svr_connected(
  2329. dlmsServerSettings * settings)
  2330. {
  2331. if (settings->base.connected == DLMS_CONNECTION_STATE_NONE)
  2332. {
  2333. GXTRACE(GET_STR_FROM_EEPROM("svr_connected to HDLC level."), NULL);
  2334. }
  2335. else if ((settings->base.connected & DLMS_CONNECTION_STATE_DLMS) != 0)
  2336. {
  2337. GXTRACE(GET_STR_FROM_EEPROM("svr_connected DLMS level."), NULL);
  2338. }
  2339. return 0;
  2340. }
  2341.  
  2342. /////////////////////////////////////////////////////////////////////////////
  2343. // Client has try to made invalid connection. Password is incorrect.
  2344. /////////////////////////////////////////////////////////////////////////////
  2345. int svr_invalidConnection(dlmsServerSettings * settings)
  2346. {
  2347. GXTRACE(GET_STR_FROM_EEPROM("svr_invalidConnection"), NULL);
  2348. updateState(GURUX_EVENT_CODES_WRONG_PASSWORD);
  2349. return 0;
  2350. }
  2351.  
  2352. /////////////////////////////////////////////////////////////////////////////
  2353. // Client has close the connection.
  2354. /////////////////////////////////////////////////////////////////////////////
  2355. int svr_disconnected(
  2356. dlmsServerSettings * settings)
  2357. {
  2358. GXTRACE(GET_STR_FROM_EEPROM("svr_disconnected"), NULL);
  2359. if (hdlcChanged)
  2360. {
  2361. hdlcChanged = 0;
  2362. //Communication speed is trace always because this is causing most of the problems.
  2363. GXTRACE_INT(GET_STR_FROM_EEPROM("Communication speed"), getCommunicationSpeed());
  2364. //Start to use new serial port settings.
  2365. Serial.begin(getCommunicationSpeed());
  2366. while (!Serial) {
  2367. // ; // wait for serial port to connect. Needed for native USB port only
  2368. }
  2369. }
  2370. return 0;
  2371. }
  2372.  
  2373. void svr_preGet(
  2374. dlmsSettings * settings,
  2375. gxValueEventCollection * args)
  2376. {
  2377. gxValueEventArg* e;
  2378. int ret, pos;
  2379. for (pos = 0; pos != args->size; ++pos)
  2380. {
  2381. if ((ret = vec_getByIndex(args, pos, &e)) != 0)
  2382. {
  2383. return;
  2384. }
  2385. }
  2386. }
  2387.  
  2388. void svr_postGet(
  2389. dlmsSettings * settings,
  2390. gxValueEventCollection * args)
  2391. {
  2392.  
  2393. }
  2394.  
  2395. //Print detailed information to the serial port.
  2396. void svr_trace(const char* str, const char* data)
  2397. {
  2398. GXTRACE(str, data);
  2399. }
Add Comment
Please, Sign In to add comment