114 Commits

Author SHA1 Message Date
e2384d01ec command changes 2020-12-01 12:52:04 +01:00
fe1b2e5b40 split commands 2020-12-01 12:43:43 +01:00
765c3b077c device configuration prepared 2020-12-01 12:43:18 +01:00
f019f7eb77 device configuration prepared 2020-12-01 12:23:26 +01:00
0ed710e652 device configuration prepared 2020-12-01 12:20:02 +01:00
24f2d0a01d device configuration prepared 2020-12-01 12:05:35 +01:00
78d32a7cc9 device configuration prepared 2020-12-01 11:39:12 +01:00
a14928b035 device configuration prepared 2020-11-30 19:07:26 +01:00
11265fc979 device configuration prepared 2020-11-30 19:06:37 +01:00
fe694e75d2 device configuration prepared 2020-11-30 19:05:19 +01:00
bde9f148a0 device configuration prepared 2020-11-30 19:03:43 +01:00
77141319ea device configuration prepared 2020-11-30 19:01:53 +01:00
b4170ec6dc device configuration prepared 2020-11-30 18:57:56 +01:00
6a2646b93c device configuration prepared 2020-11-30 18:57:19 +01:00
243c487546 device configuration prepared 2020-11-30 18:55:40 +01:00
7d03900ada device configuration prepared 2020-11-30 18:52:56 +01:00
98c0a9d7a2 device configuration prepared 2020-11-30 18:48:48 +01:00
f22c821ca3 device configuration prepared 2020-11-30 18:29:53 +01:00
76ff0d8e24 rename config mode to admin mode 2020-11-28 22:33:15 +01:00
518abe4e1c configuration 2020-11-27 16:55:09 +01:00
bc15e23f10 configuration 2020-11-27 16:36:46 +01:00
2c392cce53 configuration 2020-11-27 16:33:58 +01:00
a26a2878f4 configuration 2020-11-27 16:33:03 +01:00
6e96a27141 configuration 2020-11-27 16:24:14 +01:00
a43e42a99f configuration 2020-11-27 16:23:34 +01:00
d2c5943014 configuration 2020-11-27 16:23:14 +01:00
f409d3fb22 configuration 2020-11-27 16:19:33 +01:00
ba6ac21069 configuration 2020-11-27 16:19:01 +01:00
39ca9d963b configuration 2020-11-27 16:17:28 +01:00
4e3f086fa0 configuration 2020-11-27 16:16:40 +01:00
44523a4ed3 configuration 2020-11-27 16:14:46 +01:00
9a7e8ee297 configuration 2020-11-27 16:14:34 +01:00
eaf658de51 configuration 2020-11-27 16:07:23 +01:00
9e99d5510d configuration 2020-11-27 16:06:16 +01:00
159750bcf6 configuration 2020-11-27 16:05:36 +01:00
aaad534d21 configuration 2020-11-27 16:02:42 +01:00
e0c3394725 configuration 2020-11-27 15:58:17 +01:00
638171b494 configuration 2020-11-27 15:56:59 +01:00
d4b00cf391 configuration 2020-11-27 15:56:09 +01:00
544163f4a3 configuration 2020-11-27 15:54:16 +01:00
6d7119c0e2 configuration 2020-11-27 15:25:19 +01:00
cb5dd5f79a configuration 2020-11-27 13:37:57 +01:00
9223cbda73 configuration 2020-11-27 13:33:41 +01:00
975ecf40f9 configuration 2020-11-27 13:32:12 +01:00
0b1c6217c4 configuration 2020-11-27 13:27:24 +01:00
3c25a7d9e1 introduce dns for syslog too 2020-11-27 12:50:45 +01:00
b4ef9d29f9 introduce dns for syslog too 2020-11-27 12:49:03 +01:00
7aded82145 prepare configuration 2020-11-27 12:29:21 +01:00
8894036679 introduce dns 2020-11-27 12:28:56 +01:00
3e1a7946c2 disable show debug output 2020-11-26 11:52:54 +01:00
4e04ad6567 consider noise as real error too 2020-11-26 09:50:44 +01:00
cbc3ca6f20 Merge branch 'master' of ssh://home.hottis.de:2922/wolutator/mbusgateway3variant 2020-11-26 09:43:07 +01:00
73c1360978 delay enabling frontend after end of sending 2020-11-26 09:42:51 +01:00
56ac741079 adjust insert script 2020-11-25 15:15:27 +01:00
7a12bba4df change 2020-11-25 13:38:44 +01:00
397c3d2a56 do not consider noise error 2020-11-25 13:35:54 +01:00
f5f8aa0660 consider noise error 2020-11-25 13:33:46 +01:00
1357b17bb8 changes 2020-11-25 13:25:33 +01:00
e2ed18e71d start refactoring transmitting 2020-11-25 13:20:37 +01:00
c9b5f16542 start refactoring transmitting 2020-11-25 13:15:02 +01:00
7b8535e84e start refactoring transmitting 2020-11-25 12:56:24 +01:00
3b3894b3f0 start refactoring transmitting 2020-11-25 12:55:10 +01:00
03cadcdd58 start refactoring transmitting 2020-11-25 12:46:09 +01:00
8fe627e6b0 start refactoring transmitting 2020-11-25 12:42:33 +01:00
e1640be4c0 start refactoring transmitting 2020-11-25 12:36:36 +01:00
b328e41984 start refactoring transmitting 2020-11-25 12:08:13 +01:00
02c093723e start refactoring transmitting 2020-11-25 12:04:27 +01:00
802fec74e2 start refactoring transmitting 2020-11-25 12:00:01 +01:00
96d0599e20 start refactoring transmitting 2020-11-25 11:57:54 +01:00
d86f767dc3 start refactoring transmitting 2020-11-25 11:56:09 +01:00
3e31693cf8 start refactoring transmitting 2020-11-25 11:51:55 +01:00
4bae6dce3c start refactoring transmitting 2020-11-25 11:43:27 +01:00
f5d33445d9 start refactoring transmitting 2020-11-25 11:34:45 +01:00
30cfa20855 start refactoring transmitting 2020-11-25 11:33:09 +01:00
d8bd9eae5d start refactoring transmitting 2020-11-25 11:32:48 +01:00
c308b0ba89 start refactoring transmitting 2020-11-25 11:32:24 +01:00
622aad3cc1 start refactoring transmitting 2020-11-25 11:24:25 +01:00
ab6fc41acf start refactoring transmitting 2020-11-25 11:23:05 +01:00
081fe26daf start refactoring transmitting 2020-11-25 11:06:10 +01:00
354a1670ee start refactoring transmitting 2020-11-25 11:04:36 +01:00
c14d4fe892 working now? 2020-11-25 10:08:20 +01:00
edf1942ad3 working now? 2020-11-25 10:02:38 +01:00
7c63579390 debug 2020-11-25 09:16:00 +01:00
d171dced70 debug 2020-11-25 08:58:59 +01:00
b15321d774 changes 2020-11-25 08:55:54 +01:00
a05598d89a works better now 2020-11-24 22:57:33 +01:00
950c7b07d2 not yet working correctly again 2020-11-24 22:43:02 +01:00
d5c568a63c refactoring meterbus 2020-11-24 19:38:52 +01:00
14bf178664 refactoring meterbus 2020-11-24 19:36:47 +01:00
bdba2a79cd refactoring meterbus 2020-11-24 15:03:09 +01:00
53ccd32a0c refactoring meterbus 2020-11-24 15:00:56 +01:00
f88a4984be refactoring meterbus 2020-11-24 15:00:36 +01:00
9198753e4b refactoring meterbus 2020-11-24 14:54:57 +01:00
6d3b3e12ca refactoring meterbus 2020-11-24 14:51:05 +01:00
ae9c397e85 refactoring meterbus 2020-11-24 14:50:20 +01:00
a9b71f481a refactoring meterbus 2020-11-24 14:47:21 +01:00
0397d61e56 refactoring meterbus 2020-11-24 14:31:37 +01:00
a1c602a021 refactoring meterbus 2020-11-24 14:21:05 +01:00
d2c4efc8db refactoring meterbus 2020-11-24 14:19:12 +01:00
f37361b659 changes 2020-11-24 14:13:51 +01:00
7a088f19f2 refactoring meterbus 2020-11-24 13:50:06 +01:00
eb47d41e5a refactoring meterbus 2020-11-24 13:48:19 +01:00
7d816f6ed0 refactoring meterbus 2020-11-24 13:46:51 +01:00
89edf7f7bb refactoring meterbus 2020-11-24 13:42:26 +01:00
5cae5a1de3 refactoring meterbus 2020-11-24 13:18:18 +01:00
c1949f4cd3 start refactoring 2 2020-11-23 22:23:53 +01:00
491a60f515 start refactoring 2020-11-23 19:30:57 +01:00
b8513b2112 additional debug output 2020-11-23 19:14:22 +01:00
04405d1b84 faster requests 2020-11-23 18:50:03 +01:00
3dd954d379 log all meterbus uart errors 2020-11-22 22:59:41 +01:00
bd435dd5d6 overrun error in meterbus uart handled 2020-11-22 21:23:52 +01:00
3fd30aaa36 debug failing receive process 2020-11-21 18:23:16 +01:00
eea6b7de3b meterbus debug 2020-11-20 22:05:46 +01:00
1408c4942c spi settings for display 2020-11-20 17:25:17 +01:00
27 changed files with 1185 additions and 464 deletions

View File

@ -80,8 +80,8 @@ void MX_SPI3_Init(void)
hspi3.Init.Mode = SPI_MODE_MASTER; hspi3.Init.Mode = SPI_MODE_MASTER;
hspi3.Init.Direction = SPI_DIRECTION_2LINES; hspi3.Init.Direction = SPI_DIRECTION_2LINES;
hspi3.Init.DataSize = SPI_DATASIZE_8BIT; hspi3.Init.DataSize = SPI_DATASIZE_8BIT;
hspi3.Init.CLKPolarity = SPI_POLARITY_HIGH; hspi3.Init.CLKPolarity = SPI_POLARITY_LOW;
hspi3.Init.CLKPhase = SPI_PHASE_2EDGE; hspi3.Init.CLKPhase = SPI_PHASE_1EDGE;
hspi3.Init.NSS = SPI_NSS_SOFT; hspi3.Init.NSS = SPI_NSS_SOFT;
hspi3.Init.BaudRatePrescaler = SPI_BAUDRATEPRESCALER_2; hspi3.Init.BaudRatePrescaler = SPI_BAUDRATEPRESCALER_2;
hspi3.Init.FirstBit = SPI_FIRSTBIT_MSB; hspi3.Init.FirstBit = SPI_FIRSTBIT_MSB;

View File

@ -261,6 +261,9 @@ void UART4_IRQHandler(void)
/* USER CODE END UART4_IRQn 1 */ /* USER CODE END UART4_IRQn 1 */
} }
void mbusCommISR();
/** /**
* @brief This function handles UART5 global interrupt. * @brief This function handles UART5 global interrupt.
*/ */
@ -269,9 +272,11 @@ void UART5_IRQHandler(void)
/* USER CODE BEGIN UART5_IRQn 0 */ /* USER CODE BEGIN UART5_IRQn 0 */
/* USER CODE END UART5_IRQn 0 */ /* USER CODE END UART5_IRQn 0 */
HAL_UART_IRQHandler(&huart5); // HAL_UART_IRQHandler(&huart5);
/* USER CODE BEGIN UART5_IRQn 1 */ /* USER CODE BEGIN UART5_IRQn 1 */
mbusCommISR();
/* USER CODE END UART5_IRQn 1 */ /* USER CODE END UART5_IRQn 1 */
} }

View File

@ -2014,6 +2014,10 @@ HAL_StatusTypeDef HAL_UART_AbortReceive_IT(UART_HandleTypeDef *huart)
return HAL_OK; return HAL_OK;
} }
inline void dts(uint8_t v) {
while (v--) HAL_GPIO_TogglePin(GPIOB, GPIO_PIN_10);
}
/** /**
* @brief This function handles UART interrupt request. * @brief This function handles UART interrupt request.
* @param huart Pointer to a UART_HandleTypeDef structure that contains * @param huart Pointer to a UART_HandleTypeDef structure that contains
@ -2022,6 +2026,8 @@ HAL_StatusTypeDef HAL_UART_AbortReceive_IT(UART_HandleTypeDef *huart)
*/ */
void HAL_UART_IRQHandler(UART_HandleTypeDef *huart) void HAL_UART_IRQHandler(UART_HandleTypeDef *huart)
{ {
HAL_GPIO_TogglePin(GPIOE, GPIO_PIN_12);
uint32_t isrflags = READ_REG(huart->Instance->SR); uint32_t isrflags = READ_REG(huart->Instance->SR);
uint32_t cr1its = READ_REG(huart->Instance->CR1); uint32_t cr1its = READ_REG(huart->Instance->CR1);
uint32_t cr3its = READ_REG(huart->Instance->CR3); uint32_t cr3its = READ_REG(huart->Instance->CR3);
@ -2035,6 +2041,7 @@ void HAL_UART_IRQHandler(UART_HandleTypeDef *huart)
/* UART in mode Receiver -------------------------------------------------*/ /* UART in mode Receiver -------------------------------------------------*/
if (((isrflags & USART_SR_RXNE) != RESET) && ((cr1its & USART_CR1_RXNEIE) != RESET)) if (((isrflags & USART_SR_RXNE) != RESET) && ((cr1its & USART_CR1_RXNEIE) != RESET))
{ {
dts(1);
UART_Receive_IT(huart); UART_Receive_IT(huart);
return; return;
} }
@ -2043,6 +2050,7 @@ void HAL_UART_IRQHandler(UART_HandleTypeDef *huart)
/* If some errors occur */ /* If some errors occur */
if ((errorflags != RESET) && (((cr3its & USART_CR3_EIE) != RESET) || ((cr1its & (USART_CR1_RXNEIE | USART_CR1_PEIE)) != RESET))) if ((errorflags != RESET) && (((cr3its & USART_CR3_EIE) != RESET) || ((cr1its & (USART_CR1_RXNEIE | USART_CR1_PEIE)) != RESET)))
{ {
dts(2);
/* UART parity error interrupt occurred ----------------------------------*/ /* UART parity error interrupt occurred ----------------------------------*/
if (((isrflags & USART_SR_PE) != RESET) && ((cr1its & USART_CR1_PEIE) != RESET)) if (((isrflags & USART_SR_PE) != RESET) && ((cr1its & USART_CR1_PEIE) != RESET))
{ {
@ -2070,10 +2078,14 @@ void HAL_UART_IRQHandler(UART_HandleTypeDef *huart)
/* Call UART Error Call back function if need be --------------------------*/ /* Call UART Error Call back function if need be --------------------------*/
if (huart->ErrorCode != HAL_UART_ERROR_NONE) if (huart->ErrorCode != HAL_UART_ERROR_NONE)
{ {
dts(3);
/* UART in mode Receiver -----------------------------------------------*/ /* UART in mode Receiver -----------------------------------------------*/
if (((isrflags & USART_SR_RXNE) != RESET) && ((cr1its & USART_CR1_RXNEIE) != RESET)) if (((isrflags & USART_SR_RXNE) != RESET) && ((cr1its & USART_CR1_RXNEIE) != RESET))
{ {
dts(4);
UART_Receive_IT(huart); UART_Receive_IT(huart);
} else {
dts(5);
} }
/* If Overrun error occurs, or if any error occurs in DMA mode reception, /* If Overrun error occurs, or if any error occurs in DMA mode reception,

View File

@ -37,7 +37,7 @@ BUILD_DIR = build
###################################### ######################################
# C sources # C sources
C_SOURCES = \ C_SOURCES = \
User/Src/oled.c User/Src/cmdHandler.c User/Src/eeprom.c User/Src/frontend.c User/Src/logger.c User/Src/loopCtrl.c User/Src/main2.c User/Src/mbusComm.c User/Src/mbusParserExt.c User/Src/mqttComm.c User/Src/ports.c User/Src/ringbuffer.c User/Src/show.c User/Src/utils.c User/Src/wizHelper.c hottislib/PontCoopScheduler.c \ User/Src/regularCmds.c User/Src/adminCmds.c User/Src/configCmds.c User/Src/config.c User/Src/oled.c User/Src/cmdHandler.c User/Src/eeprom.c User/Src/frontend.c User/Src/logger.c User/Src/loopCtrl.c User/Src/main2.c User/Src/mbusComm.c User/Src/mbusParserExt.c User/Src/mqttComm.c User/Src/ports.c User/Src/ringbuffer.c User/Src/show.c User/Src/utils.c User/Src/wizHelper.c hottislib/PontCoopScheduler.c \
libmbus/mbus/mbus-protocol.c \ libmbus/mbus/mbus-protocol.c \
Core/Src/main.c \ Core/Src/main.c \
Core/Src/gpio.c \ Core/Src/gpio.c \
@ -125,6 +125,7 @@ C_INCLUDES = \
-Ilibmbus \ -Ilibmbus \
-IUser/Inc \ -IUser/Inc \
-IioLibrary_Driver/Internet/DHCP \ -IioLibrary_Driver/Internet/DHCP \
-IioLibrary_Driver/Internet/DNS \
-IioLibrary_Driver/Ethernet \ -IioLibrary_Driver/Ethernet \
-ICore/Inc \ -ICore/Inc \
-IDrivers/STM32F1xx_HAL_Driver/Inc \ -IDrivers/STM32F1xx_HAL_Driver/Inc \

23
cube/User/Inc/cmdHelper.h Normal file
View File

@ -0,0 +1,23 @@
#ifndef _CMDHELPER_H_
#define _CMDHELPER_H_
#include <stdint.h>
#include <stdbool.h>
typedef bool (*cmdFunc_t)(uint8_t argc, char **args);
typedef struct {
char name[16];
char help[512];
cmdFunc_t cmdFunc;
} cmd_t;
void sendString(const char *buf);
bool sendFormatString(const char *format, ...);
const cmd_t *getRegularCommands();
const cmd_t *getAdminCommands();
const cmd_t *getConfigCommands();
#endif /* _CMDHELPER_H_ */

42
cube/User/Inc/config.h Normal file
View File

@ -0,0 +1,42 @@
#ifndef _CONFIG_H_
#define _CONFIG_H_
#include <stdint.h>
#include <spi.h>
#include <assert.h>
#define CONFIG_MAGIC 0xdead000a
#define DEVICE_MAGIC 0xaffe0000
typedef struct __attribute__((__packed__)) s_configBlock {
uint32_t configMagic;
char deviceName[16];
uint8_t macAddress[6];
int32_t frontendThreshold;
char brokerName[64];
char watchdogTopic[64];
char startupTopic[64];
char statusTopic[64];
char mbusDataTopic[64];
char syslogServerName[64];
uint8_t numOfDeviceBlocks;
uint8_t filler[1];
} t_configBlock;
#define MBUSDEVICE_NAMELENGTH 16
#define MBUSDEVICE_NUM_OF_CONSIDEREDFIELDS 4
typedef struct __attribute__((__packed__)) s_deviceBlock {
uint32_t deviceMagic;
char deviceName[MBUSDEVICE_NAMELENGTH];
uint8_t address;
int8_t consideredField[MBUSDEVICE_NUM_OF_CONSIDEREDFIELDS];
int32_t period;
uint8_t filler[3];
} t_deviceBlock;
void configInit();
t_configBlock* getConfig();
#endif /* _CONFIG_H_ */

View File

@ -3,20 +3,48 @@
#include <stdint.h> #include <stdint.h>
#include <spi.h> #include <spi.h>
#include <config.h>
#include <assert.h>
#define EEPROM_WRITE_BLOCK_SIZE 32
#define EEPROM_AFTER_WRITE_DELAY 7
typedef struct __attribute__((__packed__)) s_eepromHeader {
uint32_t magic;
uint32_t writeCounter;
} t_eepromHeader;
static_assert((sizeof(t_eepromHeader) <= EEPROM_WRITE_BLOCK_SIZE), "t_eepromHeader has illegal size, must be less than or equal 32");
typedef struct __attribute__((__packed__)) s_deviceStats { typedef struct __attribute__((__packed__)) s_deviceStats {
uint32_t totalRunningHours; uint32_t totalRunningHours;
uint32_t totalPowercycles; uint32_t totalPowercycles;
uint32_t totalRequests; uint32_t totalRequests;
uint32_t totalFailures; uint32_t totalFailures;
} t_deviceStats; } t_deviceStats;
static_assert((sizeof(t_deviceStats) <= EEPROM_WRITE_BLOCK_SIZE), "t_deviceStats has illegal size, must be less than or equal 32");
static_assert((sizeof(t_configBlock) % 32 == 0), "t_configBlock has illegal size, must be dividable by 32");
static_assert((sizeof(t_deviceBlock) % 32 == 0), "t_deviceBlock has illegal size, must be dividable by 32");
#define EEPROM_BASE_ADDR 0
#define EEPROM_DEVICE_STATS_ADDR 32
#define EEPROM_CONFIG_BLOCK_ADDR 64
#define EEPROM_DEVICE_BLOCK_BASE_ADDR (EEPROM_CONFIG_BLOCK_ADDR + sizeof(t_configBlock))
void eepromInit(); void eepromInit();
void eepromWrite(uint16_t addr, uint8_t *buf, uint8_t len); void eepromWrite(uint16_t addr, uint8_t *buf, uint8_t len);
void eepromRead(uint16_t addr, uint8_t *buf, uint8_t len); void eepromRead(uint16_t addr, uint8_t *buf, uint8_t len);
void eepromSpiTxCpltCallback(SPI_HandleTypeDef *hspi); void eepromSpiTxCpltCallback(SPI_HandleTypeDef *hspi);
t_deviceStats* getGlobalDeviceStats(); t_deviceStats* getGlobalDeviceStats();
void eepromReadConfigBlock(t_configBlock *destConfigBlock);
void eepromWriteConfigBlock(t_configBlock *srcConfigBlock);
void eepromReadDeviceBlock(uint8_t blockNum, t_deviceBlock *destDeviceBlock);
void eepromWriteDeviceBlock(uint8_t blockNum, t_deviceBlock *srcDeviceBlock);
#endif /* EEPROM_H_ */ #endif /* EEPROM_H_ */

View File

@ -9,6 +9,5 @@ void frontendInit();
void frontendAdcCallback(ADC_HandleTypeDef* hadc); void frontendAdcCallback(ADC_HandleTypeDef* hadc);
void frontendEnable(); void frontendEnable();
void frontendDisable(); void frontendDisable();
void frontendSetThreshold(int32_t threshold);
#endif // _FRONTEND_H_ #endif // _FRONTEND_H_

View File

@ -4,10 +4,9 @@
#include <main.h> #include <main.h>
#include <stdint.h> #include <stdint.h>
#include <stdbool.h> #include <stdbool.h>
#include <config.h>
#define MBUSDEVICE_NAMELENGTH 24
#define MBUSDEVICE_NUM_OF_CONSIDEREDFIELDS 4
typedef struct { typedef struct {
char deviceName[MBUSDEVICE_NAMELENGTH]; char deviceName[MBUSDEVICE_NAMELENGTH];
uint8_t address; uint8_t address;
@ -17,6 +16,7 @@ typedef struct {
int32_t period; int32_t period;
int32_t delay; int32_t delay;
bool waiting; bool waiting;
bool active;
} t_mbusDevice; } t_mbusDevice;
typedef enum { typedef enum {
@ -26,16 +26,25 @@ typedef enum {
} e_mbusCommRequestResult; } e_mbusCommRequestResult;
typedef struct { typedef struct {
uint32_t requestCnt; uint32_t mbusRequestCnt;
uint32_t errorCnt; uint32_t mbusErrorCnt;
uint32_t uartOctetCnt;
uint32_t uartOverrunCnt;
uint32_t uartFramingErrCnt;
uint32_t uartParityErrCnt;
uint32_t uartNoiseErrCnt;
} t_mbusCommStats; } t_mbusCommStats;
// e_mbusCommRequestResult mbusCommRequest(t_mbusDevice *mbusDevice); // e_mbusCommRequestResult mbusCommRequest(t_mbusDevice *mbusDevice);
void mbusCommInit(); void mbusCommInit();
void mbusCommExec();
void mbusCommEnable(bool enable); void mbusCommEnable(bool enable);
void mbusCommTxCpltCallback(UART_HandleTypeDef *huart); void mbusCommTxCpltCallback(UART_HandleTypeDef *huart);
void mbusCommRxCpltCallback(UART_HandleTypeDef *huart); void mbusCommRxCpltCallback(UART_HandleTypeDef *huart);
void mbusCommErrorCallback(UART_HandleTypeDef *huart);
void mbusCommSetStats(t_mbusCommStats stats); void mbusCommSetStats(t_mbusCommStats stats);
t_mbusCommStats *mbusCommGetStats(); t_mbusCommStats *mbusCommGetStats();
void mbusCommAddDevice(t_deviceBlock *deviceBlock);
#endif // _MBUSCOMM_H_ #endif // _MBUSCOMM_H_

View File

@ -4,9 +4,10 @@
#include <stdbool.h> #include <stdbool.h>
#include <stdint.h> #include <stdint.h>
int wizInit(); int wizInit();
bool isNetworkAvailable(); bool isNetworkAvailable();
uint8_t* wizGetIPAddress(); uint8_t* wizGetIPAddress();
bool wizDnsQuery(char *name, uint8_t *ip);
#endif // _WIZHELPER_H_ #endif // _WIZHELPER_H_

81
cube/User/Src/adminCmds.c Normal file
View File

@ -0,0 +1,81 @@
#include <cmdHelper.h>
#include <logger.h>
#include <string.h>
#include <mbusComm.h>
#include <loopCtrl.h>
// clear statistics
static bool clearCmd(uint8_t argc, char **args) {
t_mbusCommStats zeroedStats = { .mbusRequestCnt = 0, .mbusErrorCnt = 0, .uartOctetCnt = 0, .uartOverrunCnt = 0, .uartFramingErrCnt = 0, .uartParityErrCnt = 0, .uartNoiseErrCnt = 0 };
mbusCommSetStats(zeroedStats);
coloredMsg(LOG_YELLOW, true, "ch cc global statistics cleared");
return true;
}
static bool mbusCommEnableCmd(uint8_t argc, char **args) {
bool retCode = true;
if (argc == 2) {
if (0 == strcmp("false", args[1])) {
mbusCommEnable(false);
coloredMsg(LOG_YELLOW, true, "ch mcec Meterbus communication disabled");
} else if (0 == strcmp("true", args[1])) {
mbusCommEnable(true);
coloredMsg(LOG_YELLOW, true, "ch mcec Meterbus communication enabled");
} else {
retCode = false;
}
} else {
retCode = false;
}
return retCode;
}
static bool loopEnableCmd(uint8_t argc, char **args) {
bool retCode = true;
if (argc == 2) {
if (0 == strcmp("false", args[1])) {
loopDisable();
coloredMsg(LOG_YELLOW, true, "ch lec loop disabled");
} else if (0 == strcmp("true", args[1])) {
loopEnable();
coloredMsg(LOG_YELLOW, true, "ch lec loop enabled");
} else {
retCode = false;
}
} else {
retCode = false;
}
return retCode;
}
const cmd_t ADMIN_COMMANDS[] = {
{ .name = "clear", .cmdFunc = clearCmd,
.help = \
"clear ................................ Clears the global Meterbus\n\r" \
" statistics\n\r"
},
{ .name = "mbusCommEnable", .cmdFunc = mbusCommEnableCmd,
.help = \
"mbusCommEnable true|false ............ Enables or disables the Meterbus\n\r" \
" communication\n\r"
},
{ .name = "loopEnable", .cmdFunc = loopEnableCmd,
.help = \
"loopEnable true|false ................ Enables or disables the loop.\n\r" \
" Disable Meterbus communication\n\r" \
" first if you want to disable the\n\r" \
" for a longer time, otherwise the\n\r" \
" request will enable it again\n\r"
},
{ .name = "END_OF_CMDS", .help = "",.cmdFunc = NULL }
};
const cmd_t *getAdminCommands() {
return ADMIN_COMMANDS;
}

View File

@ -1,19 +1,18 @@
#include <cmdHandler.h> #include <cmdHandler.h>
#include <cmdHelper.h>
#include <stdint.h> #include <stdint.h>
#include <stdbool.h> #include <stdbool.h>
#include <stdlib.h> #include <stdlib.h>
#include <string.h> #include <string.h>
#include <stdio.h> #include <stdio.h>
#include <stdarg.h>
#include <socket.h> #include <socket.h>
#include <logger.h> #include <logger.h>
#include <PontCoopScheduler.h> #include <PontCoopScheduler.h>
#include <wizHelper.h> #include <wizHelper.h>
#include <mbusComm.h>
#include <loopCtrl.h>
extern const uint8_t CMD_SOCK; extern const uint8_t CMD_SOCK;
@ -31,128 +30,65 @@ typedef enum {
CH_ERROR CH_ERROR
} chState_t; } chState_t;
void sendString(const char *buf) {
typedef bool (*cmdFunc_t)(uint8_t argc, char **args);
typedef struct {
bool requiredConfigMode;
char name[16];
char help[512];
cmdFunc_t cmdFunc;
} cmd_t;
// clear statistics
bool clearCmd(uint8_t argc, char **args) {
t_mbusCommStats zeroedStats = { .requestCnt = 0, .errorCnt = 0 };
mbusCommSetStats(zeroedStats);
coloredMsg(LOG_YELLOW, true, "ch cc global statistics cleared");
return true;
}
bool globalStatsCmd(uint8_t argc, char **args) {
t_mbusCommStats *stats = mbusCommGetStats();
char buf[256];
sprintf(buf, \
"Global statistics\n\r" \
" Requests: %ld\n\r" \
" Errors: %ld\n\r",
stats->requestCnt, stats->errorCnt
);
send(CMD_SOCK, (uint8_t*)buf, strlen(buf)); send(CMD_SOCK, (uint8_t*)buf, strlen(buf));
return true;
} }
bool mbusCommEnableCmd(uint8_t argc, char **args) { bool sendFormatString(const char *format, ...) {
bool retCode = true; bool retCode = true;
if (argc == 2) { va_list vl;
if (0 == strcmp("false", args[1])) { va_start(vl, format);
mbusCommEnable(false); char buf[4096];
coloredMsg(LOG_YELLOW, true, "ch mcec Meterbus communication disabled"); int vcnt = vsnprintf(buf, sizeof(buf), format, vl);
} else if (0 == strcmp("true", args[1])) { retCode = (vcnt < sizeof(buf));
mbusCommEnable(true); va_end(vl);
coloredMsg(LOG_YELLOW, true, "ch mcec Meterbus communication enabled"); sendString(buf);
} else {
retCode = false;
}
} else {
retCode = false;
}
return retCode; return retCode;
} }
bool loopEnableCmd(uint8_t argc, char **args) {
bool retCode = true;
if (argc == 2) {
if (0 == strcmp("false", args[1])) {
loopDisable();
coloredMsg(LOG_YELLOW, true, "ch lec loop disabled");
} else if (0 == strcmp("true", args[1])) {
loopEnable();
coloredMsg(LOG_YELLOW, true, "ch lec loop enabled");
} else {
retCode = false;
}
} else {
retCode = false;
}
return retCode;
}
const static cmd_t COMMANDS[] = {
{ .requiredConfigMode = true, .name = "clear", .cmdFunc = clearCmd,
.help = \
"clear ................................ Clears the global Meterbus\n\r" \
" statistics\n\r" \
" Required configuration mode\n\r"
},
{ .requiredConfigMode = true, .name = "mbusCommEnable", .cmdFunc = mbusCommEnableCmd,
.help = \
"mbusCommEnable true|false ............ Enables or disables the Meterbus\n\r" \
" communication\n\r"
},
{ .requiredConfigMode = true, .name = "loopEnable", .cmdFunc = loopEnableCmd,
.help = \
"loopEnable true|false ................ Enables or disables the loop.\n\r" \
" Disable Meterbus communication\n\r" \
" first if you want to disable the\n\r" \
" for a longer time, otherwise the\n\r" \
" request will enable it again\n\r"
},
{ .requiredConfigMode = false, .name = "globalStats", .cmdFunc = globalStatsCmd,
.help = \
"globalStats .......................... Show the global statistics\n\r" \
" counters requestCnt and errorCnt\n\r"
},
{ .requiredConfigMode = false, .name = "END_OF_CMDS", .help = "",.cmdFunc = NULL }
};
// returns 0 to continue waiting for input // returns 0 to continue waiting for input
// returns -1 to close the connection // returns -1 to close the connection
// returns 1 to toggle to config mode // returns 1 to toggle to admin mode
// returns 2 to toggle back to default mode // returns 2 to toggle to config mode
int8_t cmdExecuteCommand(uint8_t *cmdLine, bool resetConfigMode) { // returns 3 to toggle back to default mode
static int8_t cmdExecuteCommand(uint8_t *cmdLine, bool resetSpecialModes) {
const static char HELP_MSG[] = \ const static char HELP_MSG[] = \
"Usage\n\r" \ "Usage\n\r" \
"\n\r" \ "\n\r" \
"help ................................. Show this help page\n\r" \ "help ................................. Show this help page\n\r" \
"quit ................................. Terminate the console session\n\r" \ "quit ................................. Terminate the console session\n\r" \
"enable ............................... Enable configuration mode\n\r" \ "enable ............................... Enable admin mode\n\r" \
"disable .............................. Disable configuration mode\n\r" \ "config ............................... Enter configuration mode\n\r" \
"disable .............................. Disable admin/config mode\n\r" \
;
const static char CONFIG_INTRO_MSG[] = \
"In configuration mode each command changing the configuration\n\r" \
"will save changes directly to the EEPROM.\n\r" \
"However, the system will only consider these changes after a\n\r" \
"restart since only in this sitution the EEPROM is read.\n\r" \
"\n\r" \
; ;
const static char GOODBYE_MSG[] = "Good bye\n\r"; const static char GOODBYE_MSG[] = "Good bye\n\r";
const static char OK_MSG[] = "OK\n\r"; const static char OK_MSG[] = "OK\n\r";
const static char FAILED_MSG[] = "Failed\n\r"; const static char FAILED_MSG[] = "Failed\n\r";
const static char REQUIRES_CONFIG_MODE_MGS[] = "Not executed, requires config mode\n\r"; const static char UNKNOWN_COMMAND[] = "Unknown command\n\r";
uint8_t *messageToSend = NULL; uint8_t *messageToSend = NULL;
static bool adminMode = false;
static bool configMode = false; static bool configMode = false;
if (resetConfigMode) { if (resetSpecialModes) {
adminMode = false;
configMode = false; configMode = false;
} }
cmd_t const * commands = getRegularCommands();
if (adminMode) {
commands = getAdminCommands();
} else if (configMode) {
commands = getConfigCommands();
}
coloredMsg(LOG_YELLOW, false, "ch cec cmdLine is %s", cmdLine);; coloredMsg(LOG_YELLOW, false, "ch cec cmdLine is %s", cmdLine);;
#define MAX_NUM_OF_ARGS 8 #define MAX_NUM_OF_ARGS 8
@ -175,38 +111,44 @@ int8_t cmdExecuteCommand(uint8_t *cmdLine, bool resetConfigMode) {
messageToSend = (uint8_t*)GOODBYE_MSG; messageToSend = (uint8_t*)GOODBYE_MSG;
retCode = -1; retCode = -1;
} else if (0 == strcmp(cmd, "help")) { } else if (0 == strcmp(cmd, "help")) {
send(CMD_SOCK, (uint8_t*)HELP_MSG, strlen(HELP_MSG)); if (configMode) {
sendString(CONFIG_INTRO_MSG);
}
sendString(HELP_MSG);
uint8_t cmdIdx = 0; uint8_t cmdIdx = 0;
while (true) { while (true) {
cmd_t command = COMMANDS[cmdIdx]; cmd_t command = commands[cmdIdx];
if (0 == strcmp("END_OF_CMDS", command.name)) { if (0 == strcmp("END_OF_CMDS", command.name)) {
break; break;
} }
send(CMD_SOCK, (uint8_t*)command.help, strlen(command.help)); sendString(command.help);
cmdIdx++; cmdIdx++;
} }
messageToSend = NULL; messageToSend = NULL;
} else if (0 == strcmp(cmd, "enable")) { } else if (0 == strcmp(cmd, "enable")) {
coloredMsg(LOG_YELLOW, true, "ch cec enable config mode"); coloredMsg(LOG_YELLOW, true, "ch cec enable admin mode");
configMode = true; adminMode = true;
retCode = 1; retCode = 1;
} else if (0 == strcmp(cmd, "disable")) { } else if (0 == strcmp(cmd, "disable")) {
coloredMsg(LOG_YELLOW, true, "ch cec disable config mode"); coloredMsg(LOG_YELLOW, true, "ch cec disable admin mode");
adminMode = false;
configMode = false; configMode = false;
retCode = 3;
} else if (0 == strcmp(cmd, "config")) {
coloredMsg(LOG_YELLOW, true, "ch cec enable config mode");
configMode = true;
retCode = 2; retCode = 2;
} else { } else {
uint8_t cmdIdx = 0; uint8_t cmdIdx = 0;
while (true) { while (true) {
cmd_t command = COMMANDS[cmdIdx]; cmd_t command = commands[cmdIdx];
if (0 == strcmp("END_OF_CMDS", command.name)) { if (0 == strcmp("END_OF_CMDS", command.name)) {
messageToSend = (uint8_t*) UNKNOWN_COMMAND;
break; break;
} }
if (0 == strcmp(cmd, command.name)) { if (0 == strcmp(cmd, command.name)) {
if (command.requiredConfigMode && !configMode) {
messageToSend = (uint8_t*)REQUIRES_CONFIG_MODE_MGS;
} else {
messageToSend = command.cmdFunc(argc, args) ? (uint8_t*)OK_MSG : (uint8_t*)FAILED_MSG; messageToSend = command.cmdFunc(argc, args) ? (uint8_t*)OK_MSG : (uint8_t*)FAILED_MSG;
} break;
} }
cmdIdx++; cmdIdx++;
} }
@ -219,11 +161,11 @@ int8_t cmdExecuteCommand(uint8_t *cmdLine, bool resetConfigMode) {
return retCode; return retCode;
} }
void cmdHandlerEngine(void *handle) { static void cmdHandlerEngine(void *handle) {
static uint8_t receiveBuffer[256]; static uint8_t receiveBuffer[256];
static chState_t state = CH_INIT; static chState_t state = CH_INIT;
static bool resetConfigMode = false; static bool resetSpecialModes = false;
static char banner[] = \ static char banner[] = \
"MBGW3\n\r" \ "MBGW3\n\r" \
@ -231,8 +173,9 @@ void cmdHandlerEngine(void *handle) {
"or quit to close the connection.\n\r"; "or quit to close the connection.\n\r";
static char *prompt; static char *prompt;
static char defaultPrompt[] = "MBGW3 # "; static char defaultPrompt[] = "MBGW3 > ";
static char elevatedPrompt[] = "MBGW3 (admin) > "; static char adminPrompt[] = "MBGW3 (admin) # ";
static char configPrompt[] = "MBGW3 (config) $ ";
int8_t res = 0; int8_t res = 0;
@ -295,7 +238,7 @@ void cmdHandlerEngine(void *handle) {
resultSend = send(CMD_SOCK, (uint8_t*)banner, strlen(banner)); resultSend = send(CMD_SOCK, (uint8_t*)banner, strlen(banner));
coloredMsg(LOG_YELLOW, false, "ch che sent banner, send returns 0x%02x", resultSend); coloredMsg(LOG_YELLOW, false, "ch che sent banner, send returns 0x%02x", resultSend);
prompt = defaultPrompt; prompt = defaultPrompt;
resetConfigMode = true; resetSpecialModes = true;
state = CH_PROMPT; state = CH_PROMPT;
} }
break; break;
@ -335,8 +278,8 @@ void cmdHandlerEngine(void *handle) {
receiveBuffer[strlen((char*)receiveBuffer) - 1] = 0; receiveBuffer[strlen((char*)receiveBuffer) - 1] = 0;
} }
coloredMsg(LOG_YELLOW, false, "ch che received: %s", receiveBuffer); coloredMsg(LOG_YELLOW, false, "ch che received: %s", receiveBuffer);
int8_t resCEC = cmdExecuteCommand(receiveBuffer, resetConfigMode); int8_t resCEC = cmdExecuteCommand(receiveBuffer, resetSpecialModes);
resetConfigMode = false; resetSpecialModes = false;
switch (resCEC) { switch (resCEC) {
case 0: case 0:
state = CH_PROMPT; state = CH_PROMPT;
@ -345,10 +288,14 @@ void cmdHandlerEngine(void *handle) {
state = CH_DISCONNECT; state = CH_DISCONNECT;
break; break;
case 1: case 1:
prompt = elevatedPrompt; prompt = adminPrompt;
state = CH_PROMPT; state = CH_PROMPT;
break; break;
case 2: case 2:
prompt = configPrompt;
state = CH_PROMPT;
break;
case 3:
prompt = defaultPrompt; prompt = defaultPrompt;
state = CH_PROMPT; state = CH_PROMPT;
break; break;
@ -366,9 +313,9 @@ void cmdHandlerEngine(void *handle) {
break; break;
case CH_DISCONNECT_WAIT: case CH_DISCONNECT_WAIT:
coloredMsg(LOG_YELLOW, false, "ch che waiting after disconnect"); //coloredMsg(LOG_YELLOW, false, "ch che waiting after disconnect");
sockState = getSn_SR(CMD_SOCK); sockState = getSn_SR(CMD_SOCK);
coloredMsg(LOG_YELLOW, false, "ch che sockState is 0x%02x", sockState); //coloredMsg(LOG_YELLOW, false, "ch che sockState is 0x%02x", sockState);
if (sockState == SOCK_CLOSED) { if (sockState == SOCK_CLOSED) {
coloredMsg(LOG_YELLOW, true, "ch che socket is closed now"); coloredMsg(LOG_YELLOW, true, "ch che socket is closed now");
state = CH_INIT; state = CH_INIT;

158
cube/User/Src/config.c Normal file
View File

@ -0,0 +1,158 @@
#include <stdint.h>
#include <stdbool.h>
#include <config.h>
#include <eeprom.h>
#include <logger.h>
#include <mbusComm.h>
#define NUM_OF_DEFAULT_DEVICES 8
t_deviceBlock defaultDeviceBlock[] = {
{
.deviceMagic = DEVICE_MAGIC,
.deviceName = "Total",
.address = 80,
.consideredField = { 0, 17, -1, -1 },
.period = 10,
.filler = { 0, 0, 0 }
},
{
.deviceMagic = DEVICE_MAGIC,
.deviceName = "Computer",
.address = 85,
.consideredField = { 0, 4, 2, 3 },
.period = 10,
.filler = { 0, 0, 0 }
},
{
.deviceMagic = DEVICE_MAGIC,
.deviceName = "Dryer",
.address = 81,
.consideredField = { 0, 4, 2, 3 },
.period = 10,
.filler = { 0, 0, 0 }
},
{
.deviceMagic = DEVICE_MAGIC,
.deviceName = "Laundry",
.address = 82,
.consideredField = { 0, 4, 2, 3 },
.period = 10,
.filler = { 0, 0, 0 }
},
{
.deviceMagic = DEVICE_MAGIC,
.deviceName = "Dishwasher",
.address = 83,
.consideredField = { 0, 4, 2, 3 },
.period = 10,
.filler = { 0, 0, 0 }
},
{
.deviceMagic = DEVICE_MAGIC,
.deviceName = "Light",
.address = 84,
.consideredField = { 0, 4, 2, 3 },
.period = 10,
.filler = { 0, 0, 0 }
},
{
.deviceMagic = DEVICE_MAGIC,
.deviceName = "Freezer",
.address = 86,
.consideredField = { 0, 4, 2, 3 },
.period = 10,
.filler = { 0, 0, 0 }
},
{
.deviceMagic = DEVICE_MAGIC,
.deviceName = "Fridge",
.address = 87,
.consideredField = { 0, 4, 2, 3 },
.period = 10,
.filler = { 0, 0, 0 }
}
};
t_configBlock defaultConfigBlock = {
.configMagic = CONFIG_MAGIC,
.deviceName = "MBGW3",
.macAddress = { 0x00, 0xA0, 0x57, 0x05, 0x3E, 0x0D },
.frontendThreshold = 240,
.brokerName = "mqttbroker",
.watchdogTopic = "IoT/Watchdog",
.startupTopic = "IoT/MBGW3/Startup",
.statusTopic = "IoT/MBGW3/Status",
.mbusDataTopic = "IoT/MBGW3/Measurement",
.syslogServerName = "syslogserver",
.numOfDeviceBlocks = NUM_OF_DEFAULT_DEVICES,
.filler = { 0 }
};
t_configBlock mainConfigBlock;
t_configBlock* getConfig() {
return &mainConfigBlock;
}
void configInit() {
coloredMsg(LOG_BLUE, false, "cfg ci Reading configuration block from eeprom");
eepromReadConfigBlock(&mainConfigBlock);
if (mainConfigBlock.configMagic != CONFIG_MAGIC) {
coloredMsg(LOG_BLUE, false, "cfg ci Invalid configuration block read from eeprom");
eepromWriteConfigBlock(&defaultConfigBlock);
coloredMsg(LOG_BLUE, false, "cfg ci Default configuration block written to eeprom");
for (uint8_t i = 0; i < NUM_OF_DEFAULT_DEVICES; i++) {
eepromWriteDeviceBlock(i, &defaultDeviceBlock[i]);
}
coloredMsg(LOG_BLUE, false, "cfg ci Default device blocks written to eeprom");
coloredMsg(LOG_BLUE, false, "cfg ci Reading configuration block from eeprom again");
eepromReadConfigBlock(&mainConfigBlock);
}
coloredMsg(LOG_BLUE, false, "cfg ci configMagic: %lx", mainConfigBlock.configMagic);
coloredMsg(LOG_BLUE, false, "cfg ci deviceName: %s", mainConfigBlock.deviceName);
coloredMsg(LOG_BLUE, false, "cfg ci MAC address: %02x:%02x:%02x:%02x:%02x:%02x", mainConfigBlock.macAddress[0],
mainConfigBlock.macAddress[1],
mainConfigBlock.macAddress[2],
mainConfigBlock.macAddress[3],
mainConfigBlock.macAddress[4],
mainConfigBlock.macAddress[5]);
coloredMsg(LOG_BLUE, false, "cfg ci frontend threshold: %ld", mainConfigBlock.frontendThreshold);
coloredMsg(LOG_BLUE, false, "cfg ci broker: %s", mainConfigBlock.brokerName);
coloredMsg(LOG_BLUE, false, "cfg ci watchdogTopic: %s", mainConfigBlock.watchdogTopic);
coloredMsg(LOG_BLUE, false, "cfg ci startupTopic: %s", mainConfigBlock.startupTopic);
coloredMsg(LOG_BLUE, false, "cfg ci statusTopic: %s", mainConfigBlock.statusTopic);
coloredMsg(LOG_BLUE, false, "cfg ci mbusDataTopic: %s", mainConfigBlock.mbusDataTopic);
coloredMsg(LOG_BLUE, false, "cfg ci syslog server: %s", mainConfigBlock.syslogServerName);
coloredMsg(LOG_BLUE, false, "cfg ci device block cnt: %d", mainConfigBlock.numOfDeviceBlocks);
for (uint8_t i = 0; i < mainConfigBlock.numOfDeviceBlocks; i++) {
t_deviceBlock tmpDeviceBlock;
eepromReadDeviceBlock(i, &tmpDeviceBlock);
if (tmpDeviceBlock.deviceMagic == DEVICE_MAGIC) {
coloredMsg(LOG_BLUE, false, "cfg ci device %d: ", i);
coloredMsg(LOG_BLUE, false, " Name: %s, Address: %d, Period: %d",
tmpDeviceBlock.deviceName, tmpDeviceBlock.address, tmpDeviceBlock.period);
coloredMsg(LOG_BLUE, false, " Considered Fields: %d %d %d %d",
tmpDeviceBlock.consideredField[0],
tmpDeviceBlock.consideredField[1],
tmpDeviceBlock.consideredField[2],
tmpDeviceBlock.consideredField[3]);
mbusCommAddDevice(&tmpDeviceBlock);
} else {
coloredMsg(LOG_BLUE, false, "magic of device %d does not match, ignored", i);
}
}
}

View File

@ -0,0 +1,76 @@
#include <cmdHelper.h>
#include <logger.h>
#include <eeprom.h>
#include <config.h>
static bool showConfigCmd(uint8_t argc, char **args) {
bool retCode = true;
t_configBlock configBlock;
eepromReadConfigBlock(&configBlock);
sendFormatString("configMagic: %lx\n\r", configBlock.configMagic);
sendFormatString("deviceName: %s\n\r", configBlock.deviceName);
sendFormatString("MAC address: %02x:%02x:%02x:%02x:%02x:%02x\n\r", configBlock.macAddress[0],
configBlock.macAddress[1],
configBlock.macAddress[2],
configBlock.macAddress[3],
configBlock.macAddress[4],
configBlock.macAddress[5]);
sendFormatString("frontend threshold: %ld\n\r", configBlock.frontendThreshold);
sendFormatString("broker: %s\n\r", configBlock.brokerName);
sendFormatString("watchdogTopic: %s\n\r", configBlock.watchdogTopic);
sendFormatString("startupTopic: %s\n\r", configBlock.startupTopic);
sendFormatString("statusTopic: %s\n\r", configBlock.statusTopic);
sendFormatString("mbusDataTopic: %s\n\r", configBlock.mbusDataTopic);
sendFormatString("syslog server: %s\n\r", configBlock.syslogServerName);
sendFormatString("device block cnt: %d\n\r", configBlock.numOfDeviceBlocks);
for (uint8_t i = 0; i < configBlock.numOfDeviceBlocks; i++) {
t_deviceBlock tmpDeviceBlock;
eepromReadDeviceBlock(i, &tmpDeviceBlock);
if (tmpDeviceBlock.deviceMagic == DEVICE_MAGIC) {
sendFormatString("device %d: \n\r", i);
sendFormatString(" Name: %s, Address: %d, Period: %d\n\r",
tmpDeviceBlock.deviceName, tmpDeviceBlock.address, tmpDeviceBlock.period);
sendFormatString(" Considered Fields: %d %d %d %d\n\r",
tmpDeviceBlock.consideredField[0],
tmpDeviceBlock.consideredField[1],
tmpDeviceBlock.consideredField[2],
tmpDeviceBlock.consideredField[3]);
if (tmpDeviceBlock.deviceMagic != DEVICE_MAGIC) {
sendString(" DEVICE MAGIC DOES NOT MATCH\n\r");
}
}
}
return retCode;
}
static bool restartCmd(uint8_t argc, char **args) {
HAL_NVIC_SystemReset();
// you want come here ...
return true;
}
const cmd_t CONFIG_COMMANDS[] = {
{ .name = "show", .cmdFunc = showConfigCmd,
.help = \
"show ................................. Show the configuration\n\r"
},
{ .name = "restart", .cmdFunc = restartCmd,
.help = \
"restart .............................. Restart the system,\n\r" \
" Required to reload config\n\r"
},
{ .name = "END_OF_CMDS", .help = "",.cmdFunc = NULL }
};
const cmd_t *getConfigCommands() {
return CONFIG_COMMANDS;
}

View File

@ -7,6 +7,8 @@
#include <PontCoopScheduler.h> #include <PontCoopScheduler.h>
#include <utils.h> #include <utils.h>
#include <assert.h>
#define HIGH GPIO_PIN_SET #define HIGH GPIO_PIN_SET
#define LOW GPIO_PIN_RESET #define LOW GPIO_PIN_RESET
@ -20,21 +22,18 @@ static const uint8_t EEPROM_WREN = 0x06;
// static const uint8_t EEPROM_WRSR = 0x01; // static const uint8_t EEPROM_WRSR = 0x01;
static const uint32_t EEPROM_MAGIC = 0xaffe0006; static const uint32_t EEPROM_MAGIC = 0xaffe0009;
static const uint16_t EEPROM_HEADER_ADDR = EEPROM_BASE_ADDR;
typedef union { typedef union {
struct __attribute__((__packed__)) s_eepromHeader { t_eepromHeader s;
uint32_t magic;
uint32_t writeCounter;
uint8_t activeBlock;
} s;
uint8_t b[sizeof(struct s_eepromHeader)]; uint8_t b[sizeof(struct s_eepromHeader)];
} t_eepromHeader; } t_eepromHeaderBlock;
static const uint16_t EEPROM_HEADER_ADDR = 0;
static t_eepromHeader eepromHeader;
static t_eepromHeaderBlock eepromHeader;
typedef union { typedef union {
@ -42,11 +41,13 @@ typedef union {
uint8_t b[sizeof(t_deviceStats)]; uint8_t b[sizeof(t_deviceStats)];
} t_deviceStatsBlock; } t_deviceStatsBlock;
static const uint16_t DEVICE_STATS_ADDR = 32; static const uint16_t DEVICE_STATS_ADDR = EEPROM_DEVICE_STATS_ADDR;
static t_deviceStatsBlock deviceStats; static t_deviceStatsBlock deviceStats;
static const uint8_t NUM_OF_BLOCKS = 2; static const uint16_t CONFIG_BLOCK_ADDR = EEPROM_CONFIG_BLOCK_ADDR;
static const uint16_t BLOCK_ADDR[] = { 64, 4128 }; static const uint16_t DEVICE_BLOCK_ADDR = EEPROM_DEVICE_BLOCK_BASE_ADDR;
typedef union { typedef union {
@ -58,7 +59,6 @@ typedef union {
uint8_t b[sizeof(struct s_spiMsg)]; uint8_t b[sizeof(struct s_spiMsg)];
} t_spiMsg; } t_spiMsg;
t_deviceStats* getGlobalDeviceStats() { t_deviceStats* getGlobalDeviceStats() {
return &(deviceStats.s); return &(deviceStats.s);
} }
@ -72,6 +72,11 @@ static uint16_t swap(uint16_t i) {
} }
// active waiting, use only during initialization!
static void eepromActiveDelay(uint8_t delay_ms) {
activeDelay(delay_ms);
}
void eepromWrite(uint16_t addr, uint8_t *buf, uint8_t len) { void eepromWrite(uint16_t addr, uint8_t *buf, uint8_t len) {
t_spiMsg msg = { t_spiMsg msg = {
.s.cmd = EEPROM_WRITE, .s.cmd = EEPROM_WRITE,
@ -114,8 +119,8 @@ static void eepromHourlyUpdateDeviceStats(void *handle) {
t_mbusCommStats *stats = mbusCommGetStats(); t_mbusCommStats *stats = mbusCommGetStats();
deviceStats.s.totalRequests = stats->requestCnt; deviceStats.s.totalRequests += stats->mbusRequestCnt;
deviceStats.s.totalFailures = stats->errorCnt; deviceStats.s.totalFailures += stats->mbusErrorCnt;
logMsg("eeHUDS, about to write updated device stats"); logMsg("eeHUDS, about to write updated device stats");
logMsg("eeHUDS, total powercycles so far: %d", deviceStats.s.totalPowercycles); logMsg("eeHUDS, total powercycles so far: %d", deviceStats.s.totalPowercycles);
@ -126,11 +131,42 @@ static void eepromHourlyUpdateDeviceStats(void *handle) {
eepromWrite(DEVICE_STATS_ADDR, deviceStats.b, sizeof(deviceStats)); eepromWrite(DEVICE_STATS_ADDR, deviceStats.b, sizeof(deviceStats));
} }
// active waiting, use only during initialization! void eepromReadConfigBlock(t_configBlock *destConfigBlock) {
static void eepromActiveDelay(uint8_t delay_ms) { // static_assert((sizeof(*destConfigBlock) % EEPROM_WRITE_BLOCK_SIZE == 0), "config block has illegal size, must be dividable by 32");
activeDelay(delay_ms);
for (uint8_t i = 0; i < (sizeof(*destConfigBlock) / EEPROM_WRITE_BLOCK_SIZE); i++) {
eepromRead(CONFIG_BLOCK_ADDR + (i * EEPROM_WRITE_BLOCK_SIZE), ((uint8_t*)destConfigBlock) + (i * EEPROM_WRITE_BLOCK_SIZE), EEPROM_WRITE_BLOCK_SIZE);
}
} }
void eepromWriteConfigBlock(t_configBlock *srcConfigBlock) {
for (uint8_t i = 0; i < (sizeof(*srcConfigBlock) / EEPROM_WRITE_BLOCK_SIZE); i++) {
eepromWrite(CONFIG_BLOCK_ADDR + (i * EEPROM_WRITE_BLOCK_SIZE), ((uint8_t*)srcConfigBlock) + (i * EEPROM_WRITE_BLOCK_SIZE), EEPROM_WRITE_BLOCK_SIZE);
eepromActiveDelay(EEPROM_AFTER_WRITE_DELAY);
}
}
void eepromReadDeviceBlock(uint8_t blockNum, t_deviceBlock *destDeviceBlock) {
static_assert((sizeof(*destDeviceBlock) % EEPROM_WRITE_BLOCK_SIZE == 0), "device block has illegal size, must be dividable by 32");
for (uint8_t i = 0; i < (sizeof(*destDeviceBlock) / EEPROM_WRITE_BLOCK_SIZE); i++) {
eepromRead(DEVICE_BLOCK_ADDR + (blockNum * sizeof(*destDeviceBlock)) + (i * EEPROM_WRITE_BLOCK_SIZE),
((uint8_t*)destDeviceBlock) + (i * EEPROM_WRITE_BLOCK_SIZE),
EEPROM_WRITE_BLOCK_SIZE);
}
}
void eepromWriteDeviceBlock(uint8_t blockNum, t_deviceBlock *srcDeviceBlock) {
for (uint8_t i = 0; i < (sizeof(*srcDeviceBlock) / EEPROM_WRITE_BLOCK_SIZE); i++) {
eepromWrite(DEVICE_BLOCK_ADDR + (blockNum * sizeof(*srcDeviceBlock)) + (i * EEPROM_WRITE_BLOCK_SIZE),
((uint8_t*)srcDeviceBlock) + (i * EEPROM_WRITE_BLOCK_SIZE),
EEPROM_WRITE_BLOCK_SIZE);
eepromActiveDelay(EEPROM_AFTER_WRITE_DELAY);
}
}
void eepromInit() { void eepromInit() {
__EEPROM_CS(HIGH); __EEPROM_CS(HIGH);
@ -147,26 +183,19 @@ void eepromInit() {
deviceStats.s.totalFailures = 0; deviceStats.s.totalFailures = 0;
logMsg("eeI, about to write device stats for the first time"); logMsg("eeI, about to write device stats for the first time");
eepromWrite(DEVICE_STATS_ADDR, deviceStats.b, sizeof(deviceStats)); eepromWrite(DEVICE_STATS_ADDR, deviceStats.b, sizeof(deviceStats));
eepromActiveDelay(7); eepromActiveDelay(EEPROM_AFTER_WRITE_DELAY);
uint8_t emptyBlock[32]; uint8_t emptyBlock[EEPROM_WRITE_BLOCK_SIZE];
memset(emptyBlock, 0, sizeof(emptyBlock)); memset(emptyBlock, 0, sizeof(emptyBlock));
for (uint8_t i = 0; i < NUM_OF_BLOCKS; i++) { eepromWrite(CONFIG_BLOCK_ADDR, emptyBlock, EEPROM_WRITE_BLOCK_SIZE);
for (uint8_t j = 0; j <= 127; j++) { eepromActiveDelay(EEPROM_AFTER_WRITE_DELAY);
uint16_t addr = BLOCK_ADDR[i] + sizeof(emptyBlock) * j; logMsg("eeI, config block initialized");
eepromWrite(addr, emptyBlock, sizeof(emptyBlock));
eepromActiveDelay(7);
}
}
logMsg("eeI, storage blocks initialized");
eepromHeader.s.magic = EEPROM_MAGIC; eepromHeader.s.magic = EEPROM_MAGIC;
eepromHeader.s.activeBlock = 0;
eepromHeader.s.writeCounter = 1; eepromHeader.s.writeCounter = 1;
logMsg("eeI, about to write header for the first time"); logMsg("eeI, about to write header for the first time");
eepromWrite(EEPROM_HEADER_ADDR, eepromHeader.b, sizeof(eepromHeader)); eepromWrite(EEPROM_HEADER_ADDR, eepromHeader.b, sizeof(eepromHeader));
eepromActiveDelay(7); eepromActiveDelay(EEPROM_AFTER_WRITE_DELAY);
logMsg("eeI, eeprom has been initialized"); logMsg("eeI, eeprom has been initialized");
} else { } else {
logMsg("eeI, eeprom is initialized"); logMsg("eeI, eeprom is initialized");
@ -179,13 +208,10 @@ void eepromInit() {
logMsg("eeI, total requests so far: %d", deviceStats.s.totalRequests); logMsg("eeI, total requests so far: %d", deviceStats.s.totalRequests);
logMsg("eeI, total failures so far: %d", deviceStats.s.totalFailures); logMsg("eeI, total failures so far: %d", deviceStats.s.totalFailures);
t_mbusCommStats stats = { .requestCnt = deviceStats.s.totalRequests, .errorCnt = deviceStats.s.totalFailures};
mbusCommSetStats(stats);
deviceStats.s.totalPowercycles += 1; deviceStats.s.totalPowercycles += 1;
logMsg("eeI, about to write device stats with updated power cycles counter"); logMsg("eeI, about to write device stats with updated power cycles counter");
eepromWrite(DEVICE_STATS_ADDR, deviceStats.b, sizeof(deviceStats)); eepromWrite(DEVICE_STATS_ADDR, deviceStats.b, sizeof(deviceStats));
eepromActiveDelay(7); eepromActiveDelay(EEPROM_AFTER_WRITE_DELAY);
schAdd(eepromHourlyUpdateDeviceStats, NULL, 0, 60 * 60 * 1000); schAdd(eepromHourlyUpdateDeviceStats, NULL, 0, 60 * 60 * 1000);
logMsg("eeI, hourly device stats update scheduled"); logMsg("eeI, hourly device stats update scheduled");

View File

@ -6,9 +6,10 @@
#include <frontend.h> #include <frontend.h>
#include <logger.h> #include <logger.h>
#include <show.h> #include <show.h>
#include <config.h>
static t_configBlock *config;
static volatile int32_t frontendAdcThreshold = 0; static volatile int32_t frontendAdcThreshold = 0;
@ -16,16 +17,15 @@ static volatile bool frontendEnabled = false;
void frontendInit() { void frontendInit() {
config = getConfig();
frontendAdcThreshold = config->frontendThreshold;
HAL_ADCEx_Calibration_Start(&frontendAdc); HAL_ADCEx_Calibration_Start(&frontendAdc);
logMsg("frontendInit, calibration done"); logMsg("frontendInit, calibration done");
HAL_ADC_Start_IT(&frontendAdc); HAL_ADC_Start_IT(&frontendAdc);
logMsg("frontendInit, adc started"); logMsg("frontendInit, adc started");
} }
void frontendSetThreshold(int32_t threshold) {
frontendAdcThreshold = threshold;
}
void frontendEnable() { void frontendEnable() {
frontendEnabled = true; frontendEnabled = true;
} }
@ -37,8 +37,6 @@ void frontendDisable() {
void frontendAdcCallback(ADC_HandleTypeDef* hadc) { void frontendAdcCallback(ADC_HandleTypeDef* hadc) {
static int32_t holdValue = 0; static int32_t holdValue = 0;
show(DEBUG_2, TOGGLE);
if (frontendEnabled) { if (frontendEnabled) {
int32_t currentValue = (int32_t) HAL_ADC_GetValue(hadc); int32_t currentValue = (int32_t) HAL_ADC_GetValue(hadc);

View File

@ -6,6 +6,7 @@
#include <ringbuffer.h> #include <ringbuffer.h>
#include <wizHelper.h> #include <wizHelper.h>
#include <socket.h> #include <socket.h>
#include <config.h>
#include <stdint.h> #include <stdint.h>
#include <stdlib.h> #include <stdlib.h>
@ -22,18 +23,21 @@
#endif //LOGGER_OUTPUT_BY_INTERRUPT #endif //LOGGER_OUTPUT_BY_INTERRUPT
#define LOGBUFFER_SIZE 2048 #define LOGBUFFER_SIZE 4096
#define MSGBUFFER_SIZE 256 #define MSGBUFFER_SIZE 256
static t_configBlock *config;
extern const uint8_t SYSLOG_SOCK; extern const uint8_t SYSLOG_SOCK;
uint8_t syslogAddr[] = { 172, 16, 11, 15 }; uint8_t syslogAddr[4];
uint8_t singleOctetTXBuffer; uint8_t singleOctetTXBuffer;
static ringbuffer_t logBuffer; static ringbuffer_t logBuffer;
void logInit() { void logInit() {
config = getConfig();
ringbufferInit(&logBuffer, LOGBUFFER_SIZE); ringbufferInit(&logBuffer, LOGBUFFER_SIZE);
} }
@ -69,16 +73,31 @@ int logExec() {
void syslog(char *msg) { void syslog(char *msg) {
static uint8_t state = 0; static uint8_t state = 0;
int8_t res8 = 0; int8_t res8 = 0;
int32_t res32 = 0;
if (isNetworkAvailable()) { if (isNetworkAvailable()) {
switch (state) { switch (state) {
case 0: case 0:
res8 = socket(SYSLOG_SOCK, Sn_MR_UDP, 514, SF_IO_NONBLOCK); res8 = socket(SYSLOG_SOCK, Sn_MR_UDP, 514, SF_IO_NONBLOCK);
if (res8 == SYSLOG_SOCK) { if (res8 != SYSLOG_SOCK) {
state = 1;
}
break; break;
}
state = 1;
// no break
case 1: case 1:
sendto(SYSLOG_SOCK, (uint8_t*)msg, strlen(msg), syslogAddr, 514); if (! wizDnsQuery(config->syslogServerName, syslogAddr)) {
disconnect(SYSLOG_SOCK);
state = 0;
break;
}
state = 2;
// no break
case 2:
res32 = sendto(SYSLOG_SOCK, (uint8_t*)msg, strlen(msg), syslogAddr, 514);
if (res32 != strlen(msg)) {
disconnect(SYSLOG_SOCK);
state = 0;
}
break; break;
} }
} }

View File

@ -20,6 +20,7 @@
#include <mqttComm.h> #include <mqttComm.h>
#include <cmdHandler.h> #include <cmdHandler.h>
#include <oled.h> #include <oled.h>
#include <config.h>
void my_setup_1() { void my_setup_1() {
@ -46,6 +47,9 @@ void my_setup_2() {
eepromInit(); eepromInit();
oledPrint(OLED_SCREEN0, "eeprom init"); oledPrint(OLED_SCREEN0, "eeprom init");
configInit();
oledPrint(OLED_SCREEN0, "config init");
wizInit(); wizInit();
oledPrint(OLED_SCREEN0, "network init"); oledPrint(OLED_SCREEN0, "network init");
@ -55,7 +59,6 @@ void my_setup_2() {
oledPrint(OLED_SCREEN0, "cmdhandler init"); oledPrint(OLED_SCREEN0, "cmdhandler init");
frontendInit(); frontendInit();
frontendSetThreshold(240);
oledPrint(OLED_SCREEN0, "frontend init"); oledPrint(OLED_SCREEN0, "frontend init");
mbusCommInit(); mbusCommInit();
@ -64,13 +67,15 @@ void my_setup_2() {
} }
void my_loop() { void my_loop() {
show(DEBUG_1, TOGGLE); // show(DEBUG_2, TOGGLE);
schExec(); schExec();
#ifndef LOGGER_OUTPUT_BY_INTERRUPT #ifndef LOGGER_OUTPUT_BY_INTERRUPT
logExec(); logExec();
#endif //LOGGER_OUTPUT_BY_INTERRUPT #endif //LOGGER_OUTPUT_BY_INTERRUPT
mbusCommExec();
} }
void SYSTICK_Callback() { void SYSTICK_Callback() {
@ -90,22 +95,13 @@ void HAL_ADC_ConvCpltCallback(ADC_HandleTypeDef* hadc) {
} }
void HAL_UART_TxCpltCallback(UART_HandleTypeDef *huart) { void HAL_UART_TxCpltCallback(UART_HandleTypeDef *huart) {
if (huart == &mbusUart) {
mbusCommTxCpltCallback(huart);
}
#ifdef LOGGER_OUTPUT_BY_INTERRUPT #ifdef LOGGER_OUTPUT_BY_INTERRUPT
else if (huart == &debugUart) { if (huart == &debugUart) {
debugTxCpltCallback(huart); debugTxCpltCallback(huart);
} }
#endif //LOGGER_OUTPUT_BY_INTERRUPT #endif //LOGGER_OUTPUT_BY_INTERRUPT
} }
void HAL_UART_RxCpltCallback(UART_HandleTypeDef *huart) {
if (huart == &mbusUart) {
mbusCommRxCpltCallback(huart);
}
}
void HAL_SPI_TxCpltCallback(SPI_HandleTypeDef *hspi) { void HAL_SPI_TxCpltCallback(SPI_HandleTypeDef *hspi) {
if (hspi == &eepromSpi) { if (hspi == &eepromSpi) {
eepromSpiTxCpltCallback(hspi); eepromSpiTxCpltCallback(hspi);

View File

@ -16,13 +16,22 @@
#include <mbusParserExt.h> #include <mbusParserExt.h>
#include <mqttComm.h> #include <mqttComm.h>
#include <oled.h> #include <oled.h>
#include <ringbuffer.h>
#include <config.h>
#include <mbus/mbus-protocol.h> #include <mbus/mbus-protocol.h>
static const char MBUS_TOPIC[] = "IoT/MBGW3/Measurement";
static t_configBlock *config;
static const uint8_t MBUS_QUERY_CMD = 0x5b; static const uint8_t MBUS_QUERY_CMD = 0x5b;
// Delay between end of last bit of sent request telegram
// and enabling the frontend for receiving the response.
// Standard says client must wait at least 11 bit times.
// 1 / 2400 * 11 = 4.5e-3ms
static const uint32_t DELAY_AFTER_SENDING = 4; // ms
typedef enum { typedef enum {
MBCR_SUCCESS = 0, MBCR_SUCCESS = 0,
MBCR_ERROR_TIMEOUT, MBCR_ERROR_TIMEOUT,
@ -44,7 +53,9 @@ typedef enum {
MBCS_IDLE, MBCS_IDLE,
MBCS_SEND, MBCS_SEND,
MBCS_SEND_CONTINUED, MBCS_SEND_CONTINUED,
MBCS_SENDING,
MBCS_SENDING_DONE, MBCS_SENDING_DONE,
MBCS_WAIT_AFTER_SENDING,
MBCS_ENABLE_FRONTEND, MBCS_ENABLE_FRONTEND,
MBCS_START1, MBCS_START1,
MBCS_LENGTH1, MBCS_LENGTH1,
@ -77,25 +88,33 @@ typedef struct {
uint8_t stop; uint8_t stop;
} t_longframe; } t_longframe;
typedef struct {
uint16_t size;
uint16_t readIdx;
uint16_t writeIdx;
uint8_t *buffer;
} linearBuffer_t;
typedef struct { typedef struct {
uint32_t requestId; uint32_t requestId;
e_mbusCommState state; e_mbusCommState state;
uint8_t retryCnt; uint8_t retryCnt;
uint8_t cmd; uint8_t cmd;
uint8_t addr; uint8_t addr;
uint8_t sendBuf[5]; linearBuffer_t sendBuffer;
linearBuffer_t receiveBuffer;
uint32_t startTime;
uint8_t receiveCnt; uint8_t receiveCnt;
uint8_t receivedOctet; bool waitForOctet;
bool receiving;
e_mbusCommResult result; e_mbusCommResult result;
t_longframe frame; t_longframe frame;
t_mbusDevice *device; t_mbusDevice *device;
} t_mbusCommHandle; } t_mbusCommHandle;
static t_mbusCommHandle mbusCommHandle = { .requestId = 0, .state = MBCS_IDLE, .retryCnt = 0, .cmd = 0, .addr = 0, .receiveCnt = 0, .receivedOctet = 0, .receiving = false }; static t_mbusCommHandle mbusCommHandle = { .requestId = 0, .state = MBCS_IDLE, .retryCnt = 0, .cmd = 0, .addr = 0, .startTime = 0, .receiveCnt = 0, .waitForOctet = false };
static t_mbusCommStats mbusCommStats = { .requestCnt = 0, .errorCnt = 0 }; static t_mbusCommStats mbusCommStats = { .mbusRequestCnt = 0, .mbusErrorCnt = 0, .uartOctetCnt = 0, .uartOverrunCnt = 0, .uartFramingErrCnt = 0, .uartParityErrCnt = 0, .uartNoiseErrCnt = 0 };
static bool mbusCommEnabled = true; static bool mbusCommEnabled = true;
@ -108,21 +127,21 @@ t_mbusCommStats *mbusCommGetStats() {
} }
static void printError(t_mbusCommHandle *localMbusCommHandle) { static void printError() {
float errorRatio = ((float) localMbusCommHandle->device->failures) / ((float) localMbusCommHandle->device->requests); float errorRatio = ((float) mbusCommHandle.device->failures) / ((float) mbusCommHandle.device->requests);
coloredMsg(LOG_YELLOW, true, "mbc pe [%d] Error ratio is %.2f", coloredMsg(LOG_YELLOW, true, "mbc pe [%d] Error ratio is %.2f",
localMbusCommHandle->requestId, mbusCommHandle.requestId,
errorRatio); errorRatio);
mqttPublishf(MBUS_TOPIC, "{\"Status\":\"Error\", \"RequestId\":\"%d\", \"Device\":\"%s\", \"Errors\":\"%d\", \"Requests\":\"%d\", \"ErrorRatio\":\"%.2f\"}", mqttPublishf(config->mbusDataTopic, "{\"Status\":\"Error\", \"RequestId\":\"%d\", \"Device\":\"%s\", \"Errors\":\"%d\", \"Requests\":\"%d\", \"ErrorRatio\":\"%.2f\"}",
localMbusCommHandle->requestId, localMbusCommHandle->device->deviceName, mbusCommHandle.requestId, mbusCommHandle.device->deviceName,
localMbusCommHandle->device->failures, localMbusCommHandle->device->requests, errorRatio); mbusCommHandle.device->failures, mbusCommHandle.device->requests, errorRatio);
oledPrintf(OLED_SCREEN0, "Err:%d/%d", localMbusCommHandle->device->failures, localMbusCommHandle->device->requests); oledPrintf(OLED_SCREEN0, "Err:%d/%d %.2f", mbusCommHandle.device->failures, mbusCommHandle.device->requests, errorRatio);
} }
static void parseAndPrintFrame(t_mbusCommHandle *localMbusCommHandle) { static void parseAndPrintFrame() {
t_longframe *frame = &(localMbusCommHandle->frame); t_longframe *frame = &(mbusCommHandle.frame);
mbus_frame reply; mbus_frame reply;
memset(&reply, 0, sizeof(reply)); memset(&reply, 0, sizeof(reply));
@ -147,30 +166,32 @@ static void parseAndPrintFrame(t_mbusCommHandle *localMbusCommHandle) {
int r = mbus_frame_data_parse(&reply, &frame_data); int r = mbus_frame_data_parse(&reply, &frame_data);
if (r == 0) { if (r == 0) {
mbus_data_variable *data_var = &(frame_data.data_var); mbus_data_variable *data_var = &(frame_data.data_var);
coloredMsg(LOG_YELLOW, false, "mbc papf [%d] sts: %02x", localMbusCommHandle->requestId, data_var->header.status); if (data_var->header.status) {
coloredMsg(LOG_RED, true, "mbc papf [%d] sts: %02x", mbusCommHandle.requestId, data_var->header.status);
}
if ((data_var->header.status & 0x01)) { if ((data_var->header.status & 0x01)) {
coloredMsg(LOG_RED, true, "mbc papf [%d] sts: Application Busy", localMbusCommHandle->requestId); coloredMsg(LOG_RED, true, "mbc papf [%d] sts: Application Busy", mbusCommHandle.requestId);
} }
if ((data_var->header.status & 0x02)) { if ((data_var->header.status & 0x02)) {
coloredMsg(LOG_RED, true, "mbc papf [%d] sts: Any Application Error", localMbusCommHandle->requestId); coloredMsg(LOG_RED, true, "mbc papf [%d] sts: Any Application Error", mbusCommHandle.requestId);
} }
if ((data_var->header.status & 0x04)) { if ((data_var->header.status & 0x04)) {
coloredMsg(LOG_RED, true, "mbc papf [%d] sts: Power Low", localMbusCommHandle->requestId); coloredMsg(LOG_RED, true, "mbc papf [%d] sts: Power Low", mbusCommHandle.requestId);
} }
if ((data_var->header.status & 0x08)) { if ((data_var->header.status & 0x08)) {
coloredMsg(LOG_RED, true, "mbc papf [%d] sts: Permanent Error", localMbusCommHandle->requestId); coloredMsg(LOG_RED, true, "mbc papf [%d] sts: Permanent Error", mbusCommHandle.requestId);
} }
if ((data_var->header.status & 0x10)) { if ((data_var->header.status & 0x10)) {
coloredMsg(LOG_RED, true, "mbc papf [%d] sts: Temporary Error", localMbusCommHandle->requestId); coloredMsg(LOG_RED, true, "mbc papf [%d] sts: Temporary Error", mbusCommHandle.requestId);
} }
if ((data_var->header.status & 0x20)) { if ((data_var->header.status & 0x20)) {
coloredMsg(LOG_RED, true, "mbc papf [%d] sts: Specific to manufacturer Error 1", localMbusCommHandle->requestId); coloredMsg(LOG_RED, true, "mbc papf [%d] sts: Specific to manufacturer Error 1", mbusCommHandle.requestId);
} }
if ((data_var->header.status & 0x40)) { if ((data_var->header.status & 0x40)) {
coloredMsg(LOG_RED, true, "mbc papf [%d] sts: Specific to manufacturer Error 2", localMbusCommHandle->requestId); coloredMsg(LOG_RED, true, "mbc papf [%d] sts: Specific to manufacturer Error 2", mbusCommHandle.requestId);
} }
if ((data_var->header.status & 0x80)) { if ((data_var->header.status & 0x80)) {
coloredMsg(LOG_RED, true, "mbc papf [%d] sts: Specific to manufacturer Error 3", localMbusCommHandle->requestId); coloredMsg(LOG_RED, true, "mbc papf [%d] sts: Specific to manufacturer Error 3", mbusCommHandle.requestId);
} }
mbus_data_record *record; mbus_data_record *record;
int i; int i;
@ -181,24 +202,24 @@ static void parseAndPrintFrame(t_mbusCommHandle *localMbusCommHandle) {
record; record;
record = record->next, i++) { record = record->next, i++) {
for (uint8_t j = 0; j < MBUSDEVICE_NUM_OF_CONSIDEREDFIELDS; j++) { for (uint8_t j = 0; j < MBUSDEVICE_NUM_OF_CONSIDEREDFIELDS; j++) {
if (localMbusCommHandle->device->consideredField[j] == i) { if (mbusCommHandle.device->consideredField[j] == i) {
parsedVIB_t parsedVIB = parseVIB(record->drh.vib); parsedVIB_t parsedVIB = parseVIB(record->drh.vib);
coloredMsg(LOG_YELLOW, false, "mbc papf [%d] parsed VIB N: %s, U: %s, E: %d", // coloredMsg(LOG_YELLOW, false, "mbc papf [%d] parsed VIB N: %s, U: %s, E: %d",
localMbusCommHandle->requestId, // mbusCommHandle.requestId,
parsedVIB.name, parsedVIB.unit, parsedVIB.exponent); // parsedVIB.name, parsedVIB.unit, parsedVIB.exponent);
if (parsedVIB.found) { if (parsedVIB.found) {
uint32_t value = strtol(mbus_data_record_value(record), NULL, 10); uint32_t value = strtol(mbus_data_record_value(record), NULL, 10);
float weightedValue = ((float) value) * powf(10.0, ((float) parsedVIB.exponent)); float weightedValue = ((float) value) * powf(10.0, ((float) parsedVIB.exponent));
coloredMsg(LOG_YELLOW, true, "mbc papf [%d] %s is %.1f %s (%d * 10^%d)", coloredMsg(LOG_YELLOW, true, "mbc papf [%d] %s is %.1f %s (%d * 10^%d)",
localMbusCommHandle->requestId, parsedVIB.name, weightedValue, parsedVIB.unit, mbusCommHandle.requestId, parsedVIB.name, weightedValue, parsedVIB.unit,
value, parsedVIB.exponent); value, parsedVIB.exponent);
keys[numOfConsideredFields] = parsedVIB.name; keys[numOfConsideredFields] = parsedVIB.name;
values[numOfConsideredFields] = weightedValue; values[numOfConsideredFields] = weightedValue;
numOfConsideredFields++; numOfConsideredFields++;
} else { } else {
coloredMsg(LOG_YELLOW, true, "mbc papf [%d] L:%d, VIF: 0x%02x U:%s V:%s", coloredMsg(LOG_YELLOW, true, "mbc papf [%d] L:%d, VIF: 0x%02x U:%s V:%s",
localMbusCommHandle->requestId, mbusCommHandle.requestId,
localMbusCommHandle->device->consideredField[j], mbusCommHandle.device->consideredField[j],
record->drh.vib.vif, record->drh.vib.vif,
mbus_data_record_unit(record), mbus_data_record_unit(record),
mbus_data_record_value(record)); mbus_data_record_value(record));
@ -207,296 +228,349 @@ static void parseAndPrintFrame(t_mbusCommHandle *localMbusCommHandle) {
} }
} }
} }
float errorRatio = ((float) localMbusCommHandle->device->failures) / ((float) localMbusCommHandle->device->requests); float errorRatio = ((float) mbusCommHandle.device->failures) / ((float) mbusCommHandle.device->requests);
coloredMsg(LOG_YELLOW, true, "mbc papf [%d] Error ratio is %.2f", coloredMsg(LOG_YELLOW, true, "mbc papf [%d] Error ratio is %.2f",
localMbusCommHandle->requestId, mbusCommHandle.requestId,
errorRatio); errorRatio);
if (numOfConsideredFields == 1) { if (numOfConsideredFields == 1) {
mqttPublishf(MBUS_TOPIC, "{\"Status\":\"Ok\", \"RequestId\":\"%d\", \"Device\":\"%s\", \"Errors\":\"%d\", \"Requests\":\"%d\", \"ErrorRatio\":\"%.2f\", " \ mqttPublishf(config->mbusDataTopic, "{\"Status\":\"Ok\", \"RequestId\":\"%d\", \"Device\":\"%s\", \"Errors\":\"%d\", \"Requests\":\"%d\", \"ErrorRatio\":\"%.2f\", " \
"\"Values\":{\"%s\":\"%.1f\"}}", "\"Values\":{\"%s\":\"%.1f\"}}",
localMbusCommHandle->requestId, localMbusCommHandle->device->deviceName, mbusCommHandle.requestId, mbusCommHandle.device->deviceName,
localMbusCommHandle->device->failures, localMbusCommHandle->device->requests, errorRatio, mbusCommHandle.device->failures, mbusCommHandle.device->requests, errorRatio,
keys[0], values[0]); keys[0], values[0]);
} else if (numOfConsideredFields == 2) { } else if (numOfConsideredFields == 2) {
mqttPublishf(MBUS_TOPIC, "{\"Status\":\"Ok\", \"RequestId\":\"%d\", \"Device\":\"%s\", \"Errors\":\"%d\", \"Requests\":\"%d\", \"ErrorRatio\":\"%.2f\", " \ mqttPublishf(config->mbusDataTopic, "{\"Status\":\"Ok\", \"RequestId\":\"%d\", \"Device\":\"%s\", \"Errors\":\"%d\", \"Requests\":\"%d\", \"ErrorRatio\":\"%.2f\", " \
"\"Values\":{\"%s\":\"%.1f\", \"%s\":\"%.1f\"}}", "\"Values\":{\"%s\":\"%.1f\", \"%s\":\"%.1f\"}}",
localMbusCommHandle->requestId, localMbusCommHandle->device->deviceName, mbusCommHandle.requestId, mbusCommHandle.device->deviceName,
localMbusCommHandle->device->failures, localMbusCommHandle->device->requests, errorRatio, mbusCommHandle.device->failures, mbusCommHandle.device->requests, errorRatio,
keys[0], values[0], keys[1], values[1]); keys[0], values[0], keys[1], values[1]);
} else if (numOfConsideredFields == 3) { } else if (numOfConsideredFields == 3) {
mqttPublishf(MBUS_TOPIC, "{\"Status\":\"Ok\", \"RequestId\":\"%d\", \"Device\":\"%s\", \"Errors\":\"%d\", \"Requests\":\"%d\", \"ErrorRatio\":\"%.2f\", " \ mqttPublishf(config->mbusDataTopic, "{\"Status\":\"Ok\", \"RequestId\":\"%d\", \"Device\":\"%s\", \"Errors\":\"%d\", \"Requests\":\"%d\", \"ErrorRatio\":\"%.2f\", " \
"\"Values\":{\"%s\":\"%.1f\", \"%s\":\"%.1f\", \"%s\":\"%.1f\"}}", "\"Values\":{\"%s\":\"%.1f\", \"%s\":\"%.1f\", \"%s\":\"%.1f\"}}",
localMbusCommHandle->requestId, localMbusCommHandle->device->deviceName, mbusCommHandle.requestId, mbusCommHandle.device->deviceName,
localMbusCommHandle->device->failures, localMbusCommHandle->device->requests, errorRatio, mbusCommHandle.device->failures, mbusCommHandle.device->requests, errorRatio,
keys[0], values[0], keys[1], values[1], keys[2], values[2]); keys[0], values[0], keys[1], values[1], keys[2], values[2]);
} else if (numOfConsideredFields == 4) { } else if (numOfConsideredFields == 4) {
mqttPublishf(MBUS_TOPIC, "{\"Status\":\"Ok\", \"RequestId\":\"%d\", \"Device\":\"%s\", \"Errors\":\"%d\", \"Requests\":\"%d\", \"ErrorRatio\":\"%.2f\", " \ mqttPublishf(config->mbusDataTopic, "{\"Status\":\"Ok\", \"RequestId\":\"%d\", \"Device\":\"%s\", \"Errors\":\"%d\", \"Requests\":\"%d\", \"ErrorRatio\":\"%.2f\", " \
"\"Values\":{\"%s\":\"%.1f\", \"%s\":\"%.1f\", \"%s\":\"%.1f\", \"%s\":\"%.1f\"}}", "\"Values\":{\"%s\":\"%.1f\", \"%s\":\"%.1f\", \"%s\":\"%.1f\", \"%s\":\"%.1f\"}}",
localMbusCommHandle->requestId, localMbusCommHandle->device->deviceName, mbusCommHandle.requestId, mbusCommHandle.device->deviceName,
localMbusCommHandle->device->failures, localMbusCommHandle->device->requests, errorRatio, mbusCommHandle.device->failures, mbusCommHandle.device->requests, errorRatio,
keys[0], values[0], keys[1], values[1], keys[2], values[2], keys[3], values[3]); keys[0], values[0], keys[1], values[1], keys[2], values[2], keys[3], values[3]);
} }
oledPrintf(OLED_SCREEN0, "Ok:%d/%d", localMbusCommHandle->device->failures, localMbusCommHandle->device->requests); oledPrintf(OLED_SCREEN0, "Ok:%d/%d %.2f", mbusCommHandle.device->failures, mbusCommHandle.device->requests, errorRatio);
mbus_data_record_free(data_var->record); mbus_data_record_free(data_var->record);
} else { } else {
coloredMsg(LOG_RED, true, "mbc papf [%d] err: unable to parse frame", localMbusCommHandle->requestId); coloredMsg(LOG_RED, true, "mbc papf [%d] err: unable to parse frame", mbusCommHandle.requestId);
} }
} }
static void handleRequestEngine(void *handle);
static void timeoutHandler(void *handle) { void mbusCommISR() {
t_mbusCommHandle *localMbusCommHandle = (t_mbusCommHandle*) handle; uint32_t isrflags = READ_REG(mbusUart.Instance->SR);
// coloredMsg(LOG_RED, true, "mbc th [%d] timeout", localMbusCommHandle->requestId); uint32_t cr1its = READ_REG(mbusUart.Instance->CR1);
localMbusCommHandle->state = MBCS_TIMEOUT;
localMbusCommHandle->receiving = false; // RXNEIE doesn't need to be considered since it is always on and more over the
handleRequestEngine(handle); // RXNE flag is cleared by reading the DR, which is done in any case
if (((isrflags & USART_SR_RXNE) != RESET) || ((isrflags & (USART_SR_ORE | USART_SR_FE | USART_SR_PE | USART_SR_NE)) != RESET)) {
// Error flags are only valid together with the RX flag.
// They will be cleared by reading SR (already done above) followed by reading DR (below).
bool errorFound = false;
if ((isrflags & USART_SR_ORE) != RESET) {
mbusCommStats.uartOverrunCnt += 1;
errorFound = true;
}
if ((isrflags & USART_SR_FE) != RESET) {
mbusCommStats.uartFramingErrCnt += 1;
errorFound = true;
}
if ((isrflags & USART_SR_PE) != RESET) {
mbusCommStats.uartParityErrCnt += 1;
errorFound = true;
}
if ((isrflags & USART_SR_NE) != RESET) {
mbusCommStats.uartNoiseErrCnt += 1;
errorFound = true;
}
mbusCommStats.uartOctetCnt += 1;
// it is required to read the DR in any case here, not only when the buffer has space
// otherwise the interrupt flag won't be reset, particularly important in case of ORE
uint8_t data = (uint8_t)(mbusUart.Instance->DR & (uint8_t)0x00FF);
if ((! errorFound) &&
(mbusCommHandle.receiveBuffer.writeIdx < mbusCommHandle.receiveBuffer.size)) {
mbusCommHandle.receiveBuffer.buffer[mbusCommHandle.receiveBuffer.writeIdx] = data;
mbusCommHandle.receiveBuffer.writeIdx += 1;
}
}
// TXEIE needs to be considered since TXE is cleared by writing the DR, which isn't done
// after the last octet sent
if (((isrflags & USART_SR_TXE) != RESET) && ((cr1its & USART_CR1_TXEIE) != RESET)) {
if (mbusCommHandle.sendBuffer.readIdx < mbusCommHandle.sendBuffer.writeIdx) {
mbusUart.Instance->DR = mbusCommHandle.sendBuffer.buffer[mbusCommHandle.sendBuffer.readIdx];
mbusCommHandle.sendBuffer.readIdx += 1;
if (mbusCommHandle.sendBuffer.readIdx == mbusCommHandle.sendBuffer.writeIdx) {
__HAL_UART_DISABLE_IT(&mbusUart, UART_IT_TXE);
__HAL_UART_ENABLE_IT(&mbusUart, UART_IT_TC);
}
}
}
// advance the state for the engine only when the last octet is shifted out completely
if (((isrflags & USART_SR_TC) != RESET) && ((cr1its & USART_CR1_TCIE) != RESET)) {
__HAL_UART_DISABLE_IT(&mbusUart, UART_IT_TC);
mbusCommHandle.state = MBCS_SENDING_DONE;
}
} }
static void receiveNext(t_mbusCommHandle *localMbusCommHandle) {
localMbusCommHandle->receiving = true;
HAL_UART_Receive_IT(&mbusUart, &(localMbusCommHandle->receivedOctet), 1);
}
static void handleRequestEngine(void *handle) {
t_mbusCommHandle *localMbusCommHandle = (t_mbusCommHandle*) handle;
void mbusCommExec() {
static uint8_t userdataIdx = 0; static uint8_t userdataIdx = 0;
static uint8_t calculatedChksum = 0; static uint8_t calculatedChksum = 0;
uint8_t receivedOctet = 0;
static uint32_t delayAfterSendStartTime = 0;
switch (localMbusCommHandle->state) { if ((mbusCommHandle.startTime != 0) && ((mbusCommHandle.startTime + 2500) < HAL_GetTick())) {
mbusCommHandle.state = MBCS_TIMEOUT;
} else if (mbusCommHandle.waitForOctet) {
if (mbusCommHandle.receiveBuffer.readIdx >= mbusCommHandle.receiveBuffer.writeIdx) {
return; // no data available, wait
}
receivedOctet = mbusCommHandle.receiveBuffer.buffer[mbusCommHandle.receiveBuffer.readIdx];
mbusCommHandle.receiveBuffer.readIdx += 1;
mbusCommHandle.waitForOctet = false;
}
switch (mbusCommHandle.state) {
case MBCS_IDLE: case MBCS_IDLE:
coloredMsg(LOG_YELLOW, false, "mbc hre [%d] state IDLE", localMbusCommHandle->requestId); // coloredMsg(LOG_YELLOW, false, "mbc hre [%d] state IDLE", mbusCommHandle.requestId);
break; break;
case MBCS_SEND: case MBCS_SEND:
// coloredMsg(LOG_YELLOW, false, "mbc hre [%d] state SEND", localMbusCommHandle->requestId); // coloredMsg(LOG_YELLOW, false, "mbc hre [%d] state SEND", mbusCommHandle.requestId);
localMbusCommHandle->sendBuf[0] = 0x10; mbusCommHandle.sendBuffer.buffer[0] = 0x10;
localMbusCommHandle->sendBuf[1] = localMbusCommHandle->cmd; mbusCommHandle.sendBuffer.buffer[1] = mbusCommHandle.cmd;
localMbusCommHandle->sendBuf[2] = localMbusCommHandle->addr; mbusCommHandle.sendBuffer.buffer[2] = mbusCommHandle.addr;
localMbusCommHandle->sendBuf[3] = localMbusCommHandle->cmd + localMbusCommHandle->addr; // checksum mbusCommHandle.sendBuffer.buffer[3] = mbusCommHandle.cmd + mbusCommHandle.addr; // checksum
localMbusCommHandle->sendBuf[4] = 0x16; mbusCommHandle.sendBuffer.buffer[4] = 0x16;
localMbusCommHandle->state = MBCS_SEND_CONTINUED; mbusCommHandle.sendBuffer.readIdx = 0;
mbusCommHandle.sendBuffer.writeIdx = 5;
mbusCommHandle.state = MBCS_SEND_CONTINUED;
// no break !! // no break !!
case MBCS_SEND_CONTINUED: case MBCS_SEND_CONTINUED:
// coloredMsg(LOG_YELLOW, false, "mbc hre [%d] state SEND_CONTINUED", localMbusCommHandle->requestId); // coloredMsg(LOG_YELLOW, false, "mbc hre [%d] state SEND_CONTINUED", mbusCommHandle.requestId);
show(LED_RED, OFF); show(LED_RED, OFF);
if (! loopActive) { if (! loopActive) {
coloredMsg(LOG_YELLOW, true, "mbc hre [%d] enabling loop, try %d", localMbusCommHandle->requestId, localMbusCommHandle->retryCnt); coloredMsg(LOG_YELLOW, true, "mbc hre [%d] enabling loop, try %d", mbusCommHandle.requestId, mbusCommHandle.retryCnt);
localMbusCommHandle->retryCnt++; mbusCommHandle.retryCnt++;
loopEnable(); loopEnable();
schAdd(handleRequestEngine, handle, 100, 0); // give 100ms to settled the loop
} else { } else {
localMbusCommHandle->retryCnt = 0; mbusCommHandle.retryCnt = 0;
HAL_UART_Transmit_IT(&mbusUart, localMbusCommHandle->sendBuf, 5); // enable transmitter interrupt
// transition from here to SENDING_DONE is initiate by mbusCommTxCpltCallback //coloredMsg(LOG_YELLOW, false, "mbc hre [%d] enable transmitter interrupt", mbusCommHandle.requestId);
// interrupt callback __HAL_UART_ENABLE_IT(&mbusUart, UART_IT_TXE);
localMbusCommHandle->state = MBCS_SENDING_DONE; mbusCommHandle.state = MBCS_SENDING;
} }
break; break;
case MBCS_SENDING:
// transition from here to MBCS_SENDING_DONE is done by TX ISR
break;
case MBCS_SENDING_DONE: case MBCS_SENDING_DONE:
// coloredMsg(LOG_YELLOW, false, "mbc hre [%d] state SENDING_DONE", localMbusCommHandle->requestId); //coloredMsg(LOG_YELLOW, false, "mbc hre [%d] state SENDING_DONE", mbusCommHandle.requestId);
localMbusCommHandle->state = MBCS_ENABLE_FRONTEND; delayAfterSendStartTime = HAL_GetTick();
schAdd(handleRequestEngine, handle, 3, 0); mbusCommHandle.state = MBCS_WAIT_AFTER_SENDING;
break;
case MBCS_WAIT_AFTER_SENDING:
// Avoids switching on the frontend while there is still noise from sending on the loop
// Make sure to wait not too long otherwise the beginning of the response is missed
if ((delayAfterSendStartTime + DELAY_AFTER_SENDING) < HAL_GetTick()) {
mbusCommHandle.state = MBCS_ENABLE_FRONTEND;
}
break; break;
case MBCS_ENABLE_FRONTEND: case MBCS_ENABLE_FRONTEND:
// coloredMsg(LOG_YELLOW, false, "mbc hre [%d] state ENABLE_FRONTEND", localMbusCommHandle->requestId); // coloredMsg(LOG_YELLOW, false, "mbc hre [%d] state ENABLE_FRONTEND", mbusCommHandle.requestId);
frontendEnable(); frontendEnable();
schAdd(timeoutHandler, handle, 2500, 0);
calculatedChksum = 0; calculatedChksum = 0;
userdataIdx = 0; userdataIdx = 0;
localMbusCommHandle->state = MBCS_START1; mbusCommHandle.receiveBuffer.readIdx = 0;
receiveNext(localMbusCommHandle); mbusCommHandle.receiveBuffer.writeIdx = 0;
mbusCommHandle.waitForOctet = true; // start receiver
mbusCommHandle.startTime = HAL_GetTick(); // start receiver timeout
mbusCommHandle.state = MBCS_START1;
break; break;
case MBCS_START1: case MBCS_START1:
if (localMbusCommHandle->receivedOctet == 0x68) { if (receivedOctet == 0x68) {
localMbusCommHandle->frame.start1 = localMbusCommHandle->receivedOctet; mbusCommHandle.frame.start1 = receivedOctet;
localMbusCommHandle->state = MBCS_LENGTH1; mbusCommHandle.waitForOctet = true;
receiveNext(localMbusCommHandle); mbusCommHandle.state = MBCS_LENGTH1;
} else { } else {
coloredMsg(LOG_RED, true, "mbc hre [%d] err: invalid start1 symbol %02x", localMbusCommHandle->requestId, localMbusCommHandle->receivedOctet); coloredMsg(LOG_RED, true, "mbc hre [%d] err: invalid start1 symbol %02x", mbusCommHandle.requestId, receivedOctet);
localMbusCommHandle->result = MBCR_ERROR_STATE_ENGINE__START1; mbusCommHandle.result = MBCR_ERROR_STATE_ENGINE__START1;
localMbusCommHandle->state = MBCS_ERROR; mbusCommHandle.state = MBCS_ERROR;
schAdd(handleRequestEngine, handle, 0, 0);
} }
break; break;
case MBCS_LENGTH1: case MBCS_LENGTH1:
if (localMbusCommHandle->receivedOctet <= 3) { if (receivedOctet <= 3) {
coloredMsg(LOG_RED, true, "mbc hre [%d] err: length to small %02x", localMbusCommHandle->requestId, localMbusCommHandle->receivedOctet); coloredMsg(LOG_RED, true, "mbc hre [%d] err: length to small %02x", mbusCommHandle.requestId, receivedOctet);
localMbusCommHandle->result = MBCR_ERROR_STATE_ENGINE__LENGTH1; mbusCommHandle.result = MBCR_ERROR_STATE_ENGINE__LENGTH1;
localMbusCommHandle->state = MBCS_ERROR; mbusCommHandle.state = MBCS_ERROR;
schAdd(handleRequestEngine, handle, 0, 0);
} else { } else {
localMbusCommHandle->frame.length1 = localMbusCommHandle->receivedOctet; mbusCommHandle.frame.length1 = receivedOctet;
localMbusCommHandle->frame.userdata = (uint8_t*) malloc(localMbusCommHandle->frame.length1 - 3); mbusCommHandle.frame.userdata = (uint8_t*) malloc(mbusCommHandle.frame.length1 - 3);
if (! localMbusCommHandle->frame.userdata) { if (! mbusCommHandle.frame.userdata) {
coloredMsg(LOG_RED, true, "mbc hre [%d] err: unable to allocate memory for userdata", localMbusCommHandle->requestId); coloredMsg(LOG_RED, true, "mbc hre [%d] err: unable to allocate memory for userdata", mbusCommHandle.requestId);
localMbusCommHandle->result = MBCR_ERROR_OUT_OF_MEMORY__USERDATA; mbusCommHandle.result = MBCR_ERROR_OUT_OF_MEMORY__USERDATA;
localMbusCommHandle->state = MBCS_ERROR; mbusCommHandle.state = MBCS_ERROR;
schAdd(handleRequestEngine, handle, 0, 0);
} else { } else {
localMbusCommHandle->state = MBCS_LENGTH2; mbusCommHandle.waitForOctet = true;
receiveNext(localMbusCommHandle); mbusCommHandle.state = MBCS_LENGTH2;
} }
} }
break; break;
case MBCS_LENGTH2: case MBCS_LENGTH2:
if (localMbusCommHandle->frame.length1 != localMbusCommHandle->receivedOctet) { if (mbusCommHandle.frame.length1 != receivedOctet) {
coloredMsg(LOG_RED, true, "mbc hre [%d] err: invalid length2 %02x vs. %02x", coloredMsg(LOG_RED, true, "mbc hre [%d] err: invalid length2 %02x vs. %02x",
localMbusCommHandle->requestId, localMbusCommHandle->frame.length1, localMbusCommHandle->receivedOctet); mbusCommHandle.requestId, mbusCommHandle.frame.length1, receivedOctet);
localMbusCommHandle->result = MBCR_ERROR_STATE_ENGINE__LENGTH2; mbusCommHandle.result = MBCR_ERROR_STATE_ENGINE__LENGTH2;
localMbusCommHandle->state = MBCS_ERROR; mbusCommHandle.state = MBCS_ERROR;
schAdd(handleRequestEngine, handle, 0, 0);
} else { } else {
localMbusCommHandle->frame.length2 = localMbusCommHandle->receivedOctet; mbusCommHandle.frame.length2 = receivedOctet;
localMbusCommHandle->state = MBCS_START2; mbusCommHandle.waitForOctet = true;
receiveNext(localMbusCommHandle); mbusCommHandle.state = MBCS_START2;
} }
break; break;
case MBCS_START2: case MBCS_START2:
if (localMbusCommHandle->receivedOctet == 0x68) { if (receivedOctet == 0x68) {
localMbusCommHandle->frame.start2 = localMbusCommHandle->receivedOctet; mbusCommHandle.frame.start2 = receivedOctet;
localMbusCommHandle->state = MBCS_C_FIELD; mbusCommHandle.waitForOctet = true;
receiveNext(localMbusCommHandle); mbusCommHandle.state = MBCS_C_FIELD;
} else { } else {
coloredMsg(LOG_RED, true, "mbc hre [%d] err: invalid start2 symbol %02x", coloredMsg(LOG_RED, true, "mbc hre [%d] err: invalid start2 symbol %02x",
localMbusCommHandle->requestId, localMbusCommHandle->receivedOctet); mbusCommHandle.requestId, receivedOctet);
localMbusCommHandle->result = MBCR_ERROR_STATE_ENGINE__START2; mbusCommHandle.result = MBCR_ERROR_STATE_ENGINE__START2;
localMbusCommHandle->state = MBCS_ERROR; mbusCommHandle.state = MBCS_ERROR;
schAdd(handleRequestEngine, handle, 0, 0);
} }
break; break;
case MBCS_C_FIELD: case MBCS_C_FIELD:
localMbusCommHandle->frame.c = localMbusCommHandle->receivedOctet; mbusCommHandle.frame.c = receivedOctet;
calculatedChksum += localMbusCommHandle->receivedOctet; calculatedChksum += receivedOctet;
localMbusCommHandle->state = MBCS_A_FIELD; mbusCommHandle.waitForOctet = true;
receiveNext(localMbusCommHandle); mbusCommHandle.state = MBCS_A_FIELD;
break; break;
case MBCS_A_FIELD: case MBCS_A_FIELD:
localMbusCommHandle->frame.a = localMbusCommHandle->receivedOctet; mbusCommHandle.frame.a = receivedOctet;
calculatedChksum += localMbusCommHandle->receivedOctet; calculatedChksum += receivedOctet;
localMbusCommHandle->state = MBCS_CI_FIELD; mbusCommHandle.waitForOctet = true;
receiveNext(localMbusCommHandle); mbusCommHandle.state = MBCS_CI_FIELD;
break; break;
case MBCS_CI_FIELD: case MBCS_CI_FIELD:
localMbusCommHandle->frame.ci = localMbusCommHandle->receivedOctet; mbusCommHandle.frame.ci = receivedOctet;
calculatedChksum += localMbusCommHandle->receivedOctet; calculatedChksum += receivedOctet;
localMbusCommHandle->state = MBCS_USERDATA; mbusCommHandle.waitForOctet = true;
receiveNext(localMbusCommHandle); mbusCommHandle.state = MBCS_USERDATA;
break; break;
case MBCS_USERDATA: case MBCS_USERDATA:
localMbusCommHandle->frame.userdata[userdataIdx] = localMbusCommHandle->receivedOctet; mbusCommHandle.frame.userdata[userdataIdx] = receivedOctet;
calculatedChksum += localMbusCommHandle->receivedOctet; calculatedChksum += receivedOctet;
userdataIdx++; userdataIdx++;
if (userdataIdx == (localMbusCommHandle->frame.length1 - 3)) { mbusCommHandle.waitForOctet = true;
localMbusCommHandle->state = MBCS_CHKSUM; if (userdataIdx == (mbusCommHandle.frame.length1 - 3)) {
mbusCommHandle.state = MBCS_CHKSUM;
} }
receiveNext(localMbusCommHandle);
break; break;
case MBCS_CHKSUM: case MBCS_CHKSUM:
if (localMbusCommHandle->receivedOctet != calculatedChksum) { if (receivedOctet != calculatedChksum) {
coloredMsg(LOG_RED, true, "mbc hre [%d] err: invalid checksum %02x vs %02x", coloredMsg(LOG_RED, true, "mbc hre [%d] err: invalid checksum %02x vs %02x",
localMbusCommHandle->requestId, calculatedChksum, localMbusCommHandle->receivedOctet); mbusCommHandle.requestId, calculatedChksum, receivedOctet);
localMbusCommHandle->result = MBCR_ERROR_STATE_ENGINE__INVALID_CHKSUM; mbusCommHandle.result = MBCR_ERROR_STATE_ENGINE__INVALID_CHKSUM;
localMbusCommHandle->state = MBCS_ERROR; mbusCommHandle.state = MBCS_ERROR;
schAdd(handleRequestEngine, handle, 0, 0);
} else { } else {
localMbusCommHandle->frame.chksum = localMbusCommHandle->receivedOctet; mbusCommHandle.frame.chksum = receivedOctet;
localMbusCommHandle->state = MBCS_STOP; mbusCommHandle.waitForOctet = true;
receiveNext(localMbusCommHandle); mbusCommHandle.state = MBCS_STOP;
} }
break; break;
case MBCS_STOP: case MBCS_STOP:
if (localMbusCommHandle->receivedOctet == 0x16) { if (receivedOctet == 0x16) {
localMbusCommHandle->frame.stop = localMbusCommHandle->receivedOctet; mbusCommHandle.frame.stop = receivedOctet;
localMbusCommHandle->state = MBCS_DONE; mbusCommHandle.state = MBCS_DONE;
schAdd(handleRequestEngine, handle, 0, 0);
} else { } else {
coloredMsg(LOG_RED, true, "mbc hre [%d] err: invalid stop symbol %02x", coloredMsg(LOG_RED, true, "mbc hre [%d] err: invalid stop symbol %02x",
localMbusCommHandle->requestId, localMbusCommHandle->receivedOctet); mbusCommHandle.requestId, receivedOctet);
localMbusCommHandle->result = MBCR_ERROR_STATE_ENGINE__STOP; mbusCommHandle.result = MBCR_ERROR_STATE_ENGINE__STOP;
localMbusCommHandle->state = MBCS_ERROR; mbusCommHandle.state = MBCS_ERROR;
schAdd(handleRequestEngine, handle, 0, 0);
} }
break; break;
case MBCS_DONE: case MBCS_DONE:
// coloredMsg(LOG_YELLOW, false, "mbc hre [%d] state DONE", localMbusCommHandle->requestId); // coloredMsg(LOG_YELLOW, false, "mbc hre [%d] state DONE", mbusCommHandle.requestId);
parseAndPrintFrame(localMbusCommHandle); parseAndPrintFrame();
if (localMbusCommHandle->frame.userdata != NULL) { if (mbusCommHandle.frame.userdata != NULL) {
free(localMbusCommHandle->frame.userdata); free(mbusCommHandle.frame.userdata);
localMbusCommHandle->frame.userdata = NULL; mbusCommHandle.frame.userdata = NULL;
} }
localMbusCommHandle->result = MBCR_SUCCESS; mbusCommHandle.result = MBCR_SUCCESS;
localMbusCommHandle->state = MBCS_DISABLE_FRONTEND; mbusCommHandle.state = MBCS_DISABLE_FRONTEND;
schDel(timeoutHandler, handle);
schAdd(handleRequestEngine, handle, 0, 0);
break; break;
case MBCS_ERROR: case MBCS_ERROR:
coloredMsg(LOG_RED, false, "mbc hre [%d] state ERROR", localMbusCommHandle->requestId); // coloredMsg(LOG_RED, false, "mbc hre [%d] state ERROR", mbusCommHandle.requestId);
coloredMsg(LOG_RED, true, "mbc hre [%d] error", mbusCommHandle.requestId);
show(LED_RED, ON); show(LED_RED, ON);
localMbusCommHandle->state = MBCS_ERROR_CONTINUED; // disable frontend immediately in case of error since no more data in relevant
// this avoids strange noise on RX line/led
frontendDisable();
mbusCommHandle.state = MBCS_ERROR_CONTINUED;
// no break // no break
case MBCS_ERROR_CONTINUED: case MBCS_ERROR_CONTINUED:
receiveNext(localMbusCommHandle); // every error will be collected by a timeout to receive all data still on the wire
// to avoid leaking old data in responses for new requests
break; break;
case MBCS_TIMEOUT: case MBCS_TIMEOUT:
coloredMsg(LOG_RED, false, "mbc hre [%d] state TIMEOUT", localMbusCommHandle->requestId); // coloredMsg(LOG_RED, false, "mbc hre [%d] state TIMEOUT", mbusCommHandle.requestId);
mbusCommStats.errorCnt += 1; coloredMsg(LOG_RED, true, "mbc hre [%d] timeout", mbusCommHandle.requestId);
localMbusCommHandle->device->failures += 1; mbusCommStats.mbusErrorCnt += 1;
printError(localMbusCommHandle); mbusCommHandle.device->failures += 1;
localMbusCommHandle->receiving = false; mbusCommHandle.startTime = 0; // disable timeout
if (localMbusCommHandle->frame.userdata != NULL) { mbusCommHandle.waitForOctet = false; // disable receiver
free(localMbusCommHandle->frame.userdata); printError();
localMbusCommHandle->frame.userdata = NULL; if (mbusCommHandle.frame.userdata != NULL) {
free(mbusCommHandle.frame.userdata);
mbusCommHandle.frame.userdata = NULL;
} }
HAL_UART_AbortReceive(&mbusUart);
uint8_t kitchenSink[16];
memset(kitchenSink, 0, 16);
HAL_StatusTypeDef r = HAL_UART_Receive(&mbusUart, kitchenSink, 16, 100);
coloredMsg(LOG_RED, false, "mbc hre [%d] abort, last receive result: %02x", localMbusCommHandle->requestId, r);
// no break // no break
case MBCS_DISABLE_FRONTEND: case MBCS_DISABLE_FRONTEND:
// coloredMsg(LOG_YELLOW, false, "mbc hre [%d] state DISABLE_FRONTEND", localMbusCommHandle->requestId); // coloredMsg(LOG_YELLOW, false, "mbc hre [%d] state DISABLE_FRONTEND", mbusCommHandle.requestId);
frontendDisable(); frontendDisable();
localMbusCommHandle->state = MBCS_IDLE; mbusCommHandle.startTime = 0; // disable timeout
mbusCommHandle.state = MBCS_IDLE;
break; break;
default: default:
localMbusCommHandle->state = MBCS_IDLE; mbusCommHandle.state = MBCS_IDLE;
break; break;
} }
} }
void mbusCommTxCpltCallback(UART_HandleTypeDef *huart) {
schAdd(handleRequestEngine, (void*) &mbusCommHandle, 0, 0);
}
void mbusCommRxCpltCallback(UART_HandleTypeDef *huart) {
if (mbusCommHandle.receiving) {
schAdd(handleRequestEngine, (void*) &mbusCommHandle, 0, 0);
mbusCommHandle.receiving = false;
}
}
void mbusCommEnable(bool enable) { void mbusCommEnable(bool enable) {
mbusCommEnabled = enable; mbusCommEnabled = enable;
} }
@ -514,19 +588,14 @@ static e_mbusCommRequestResult mbusCommRequest(t_mbusDevice *mbusDevice) {
mbusCommHandle.device = mbusDevice; mbusCommHandle.device = mbusDevice;
mbusDevice->requests += 1; mbusDevice->requests += 1;
coloredMsg(LOG_YELLOW, true, "mbc mcr [%d] new request %s R:%d F:%d GRC:%d GEC:%d", coloredMsg(LOG_YELLOW, true, "mbc mcr [%d] new request %s",
mbusCommHandle.requestId, mbusCommHandle.requestId,
mbusDevice->deviceName, mbusDevice->deviceName);
mbusDevice->requests,
mbusDevice->failures,
mbusCommStats.requestCnt,
mbusCommStats.errorCnt);
oledPrint(OLED_SCREEN0, mbusDevice->deviceName); oledPrint(OLED_SCREEN0, mbusDevice->deviceName);
schAdd(handleRequestEngine, (void*) &mbusCommHandle, 0, 0);
res = MBCRR_TRIGGERED; res = MBCRR_TRIGGERED;
mbusCommStats.requestCnt += 1; mbusCommStats.mbusRequestCnt += 1;
} }
} else { } else {
res = MBCRR_DISABLED; res = MBCRR_DISABLED;
@ -536,89 +605,120 @@ static e_mbusCommRequestResult mbusCommRequest(t_mbusDevice *mbusDevice) {
} }
static uint8_t numOfDevices = 8; #define PERIOD 10
static uint8_t numOfDevices = 0;
static t_mbusDevice *devices = NULL;
void mbusCommAddDevice(t_deviceBlock *deviceBlock) {
devices = (t_mbusDevice*) realloc((void*) devices, (numOfDevices + 1) * sizeof(t_mbusDevice));
strcpy(devices[numOfDevices].deviceName, deviceBlock->deviceName);
devices[numOfDevices].address = deviceBlock->address;
memcpy(devices[numOfDevices].consideredField, deviceBlock->consideredField, sizeof(deviceBlock->consideredField));
devices[numOfDevices].period = deviceBlock->period;
devices[numOfDevices].requests = 0;
devices[numOfDevices].failures = 0;
devices[numOfDevices].delay = 0;
devices[numOfDevices].waiting = false;
devices[numOfDevices].active = true;
coloredMsg(LOG_YELLOW, true, "mbc mbcad device added %d %s %d", numOfDevices, devices[numOfDevices].deviceName, devices[numOfDevices].address);
numOfDevices += 1;
}
/*
static t_mbusDevice devices[] = { static t_mbusDevice devices[] = {
{ {
.deviceName = "TotalPower", .deviceName = "Total",
.address = 80, .address = 80,
.consideredField = { 0, 17, -1, -1 }, .consideredField = { 0, 17, -1, -1 },
.requests = 0, .requests = 0,
.failures = 0, .failures = 0,
.period = 60, .period = PERIOD,
.delay = 0, .delay = 0,
.waiting = false .waiting = false,
.active = true
}, },
{ {
.deviceName = "ComputerPower", .deviceName = "Computer",
.address = 85, .address = 85,
.consideredField = { 0, 4, 2, 3 }, .consideredField = { 0, 4, 2, 3 },
.requests = 0, .requests = 0,
.failures = 0, .failures = 0,
.period = 60, .period = PERIOD,
.delay = 0, .delay = 0,
.waiting = false .waiting = false,
.active = true
}, },
{ {
.deviceName = "DryerPower", .deviceName = "Dryer",
.address = 81, .address = 81,
.consideredField = { 0, 4, 2, 3 }, .consideredField = { 0, 4, 2, 3 },
.requests = 0, .requests = 0,
.failures = 0, .failures = 0,
.period = 60, .period = PERIOD,
.delay = 0, .delay = 0,
.waiting = false .waiting = false,
.active = true
}, },
{ {
.deviceName = "LaundryPower", .deviceName = "Laundry",
.address = 82, .address = 82,
.consideredField = { 0, 4, 2, 3 }, .consideredField = { 0, 4, 2, 3 },
.requests = 0, .requests = 0,
.failures = 0, .failures = 0,
.period = 60, .period = PERIOD,
.delay = 0, .delay = 0,
.waiting = false .waiting = false,
.active = true
}, },
{ {
.deviceName = "DishwasherPower", .deviceName = "Dishwasher",
.address = 83, .address = 83,
.consideredField = { 0, 4, 2, 3 }, .consideredField = { 0, 4, 2, 3 },
.requests = 0, .requests = 0,
.failures = 0, .failures = 0,
.period = 60, .period = PERIOD,
.delay = 0, .delay = 0,
.waiting = false .waiting = false,
.active = true
}, },
{ {
.deviceName = "LightPower", .deviceName = "Light",
.address = 84, .address = 84,
.consideredField = { 0, 4, 2, 3 }, .consideredField = { 0, 4, 2, 3 },
.requests = 0, .requests = 0,
.failures = 0, .failures = 0,
.period = 15, .period = PERIOD,
.delay = 0, .delay = 0,
.waiting = false .waiting = false,
.active = true
}, },
{ {
.deviceName = "FreezerPower", .deviceName = "Freezer",
.address = 86, .address = 86,
.consideredField = { 0, 4, 2, 3 }, .consideredField = { 0, 4, 2, 3 },
.requests = 0, .requests = 0,
.failures = 0, .failures = 0,
.period = 60, .period = PERIOD,
.delay = 0, .delay = 0,
.waiting = false .waiting = false,
.active = true
}, },
{ {
.deviceName = "FridgePower", .deviceName = "Fridge",
.address = 87, .address = 87,
.consideredField = { 0, 4, 2, 3 }, .consideredField = { 0, 4, 2, 3 },
.requests = 0, .requests = 0,
.failures = 0, .failures = 0,
.period = 60, .period = PERIOD,
.delay = 0, .delay = 0,
.waiting = false .waiting = false,
.active = true
} }
}; };
*/
static void triggerMBusRequest(void *handle) { static void triggerMBusRequest(void *handle) {
@ -673,6 +773,7 @@ static void mbusCommScheduler(void *handle) {
state = 1; state = 1;
} }
for (uint8_t i = 0; i < numOfDevices; i++) { for (uint8_t i = 0; i < numOfDevices; i++) {
if (devices[i].active) {
devices[i].delay -= 1; devices[i].delay -= 1;
if (devices[i].delay <= 0) { if (devices[i].delay <= 0) {
devices[i].delay = devices[i].period; devices[i].delay = devices[i].period;
@ -680,11 +781,44 @@ static void mbusCommScheduler(void *handle) {
coloredMsg(LOG_YELLOW, false, "mbc mcs scheduled: %s", devices[i].deviceName); coloredMsg(LOG_YELLOW, false, "mbc mcs scheduled: %s", devices[i].deviceName);
} }
} }
}
// FIXME
// state = 3;
break;
case 3:
coloredMsg(LOG_YELLOW, false, "mbc mcs waiting for godot");
state = 4;
// no break
case 4:
break; break;
} }
} }
void mbusCommInit() { void mbusCommInit() {
config = getConfig();
coloredMsg(LOG_GREEN, true, "mbc mci initializing Meterbus communication"); coloredMsg(LOG_GREEN, true, "mbc mci initializing Meterbus communication");
// enable receive interrupts
// __HAL_UART_ENABLE_IT(&mbusUart, UART_IT_PE);
// __HAL_UART_ENABLE_IT(&mbusUart, UART_IT_ERR);
__HAL_UART_ENABLE_IT(&mbusUart, UART_IT_RXNE);
// init buffers
mbusCommHandle.receiveBuffer.size = 256;
mbusCommHandle.receiveBuffer.buffer = (uint8_t*) malloc(mbusCommHandle.receiveBuffer.size);
mbusCommHandle.receiveBuffer.readIdx = 0;
mbusCommHandle.receiveBuffer.writeIdx = 0;
mbusCommHandle.sendBuffer.size = 8;
mbusCommHandle.sendBuffer.buffer = (uint8_t*) malloc(mbusCommHandle.sendBuffer.size);
mbusCommHandle.sendBuffer.readIdx = 0;
mbusCommHandle.sendBuffer.writeIdx = 0;
// FIXME
schAdd(mbusCommScheduler, NULL, 0, 1000); schAdd(mbusCommScheduler, NULL, 0, 1000);
} }

View File

@ -9,6 +9,7 @@
#include <mbusComm.h> #include <mbusComm.h>
#include <oled.h> #include <oled.h>
#include <eeprom.h> #include <eeprom.h>
#include <config.h>
#include <stdint.h> #include <stdint.h>
#include <stdlib.h> #include <stdlib.h>
@ -19,17 +20,14 @@
extern const uint8_t MQTT_SOCK; extern const uint8_t MQTT_SOCK;
static t_configBlock *config;
client_t client; client_t client;
mqttClient_t mqttClient; mqttClient_t mqttClient;
uint8_t brokerAddress[] = { 172, 16, 2, 16 }; uint8_t brokerAddress[4];
uint16_t brokerPort = 1883; uint16_t brokerPort = 1883;
const static char WatchdogTopic[] = "IoT/Watchdog";
const static char StartupTopic[] = "IoT/MBGW3/Startup";
const static char StatusTopic[] = "IoT/MBGW3/Status";
static uint32_t watchdogCounter = 0; static uint32_t watchdogCounter = 0;
void watchdogHandler(void *handle) { void watchdogHandler(void *handle) {
@ -44,7 +42,7 @@ void watchdogHandler(void *handle) {
// typedef void (*callback_t)(char*, uint8_t*, uint16_t); // typedef void (*callback_t)(char*, uint8_t*, uint16_t);
static void mqttCallback(char *topic, uint8_t *payload, uint16_t payloadLength) { static void mqttCallback(char *topic, uint8_t *payload, uint16_t payloadLength) {
if (0 == strcmp(topic, WatchdogTopic)) { if (0 == strcmp(topic, config->watchdogTopic)) {
watchdogCounter++; watchdogCounter++;
} else { } else {
coloredMsg(LOG_GREEN, false, "mqcb: %s : %.*s", topic, payloadLength, payload); coloredMsg(LOG_GREEN, false, "mqcb: %s : %.*s", topic, payloadLength, payload);
@ -56,11 +54,12 @@ static void mqttStatusPublisher(void *handle) {
t_mbusCommStats *mbusCommStats = mbusCommGetStats(); t_mbusCommStats *mbusCommStats = mbusCommGetStats();
t_deviceStats* globalDeviceStats = getGlobalDeviceStats(); t_deviceStats* globalDeviceStats = getGlobalDeviceStats();
char buf[128]; char buf[256];
uint32_t uptime = HAL_GetTick() / 1000; uint32_t uptime = HAL_GetTick() / 1000;
snprintf(buf, sizeof(buf), "{\"uptime\":\"%ld\", \"runningHours\":\"%ld\", \"powerCycles\":\"%ld\", \"tasks\":\"%d\", \"requests\":\"%ld\", \"errors\":\"%ld\"}", snprintf(buf, sizeof(buf), "{\"uptime\":\"%ld\", \"runningHours\":\"%ld\", \"powerCycles\":\"%ld\", \"tasks\":\"%d\", \"requests\":\"%ld\", \"errors\":\"%ld\", \"octets\":\"%ld\", \"overrun\":\"%ld\", \"framing\":\"%ld\", \"parity\":\"%ld\", \"noise\":\"%ld\"}",
uptime, globalDeviceStats->totalRunningHours, globalDeviceStats->totalPowercycles, schTaskCnt(), mbusCommStats->requestCnt, mbusCommStats->errorCnt); uptime, globalDeviceStats->totalRunningHours, globalDeviceStats->totalPowercycles, schTaskCnt(), mbusCommStats->mbusRequestCnt, mbusCommStats->mbusErrorCnt,
bool res = publish(&mqttClient, StatusTopic, (const uint8_t*)buf, strlen(buf), false); mbusCommStats->uartOctetCnt, mbusCommStats->uartOverrunCnt, mbusCommStats->uartFramingErrCnt, mbusCommStats->uartParityErrCnt, mbusCommStats->uartNoiseErrCnt);
bool res = publish(&mqttClient, config->statusTopic, (const uint8_t*)buf, strlen(buf), false);
coloredMsg(LOG_GREEN, false, "mqch, publish returned %d", res); coloredMsg(LOG_GREEN, false, "mqch, publish returned %d", res);
oledSetActiveScreen(OLED_SCREEN1); oledSetActiveScreen(OLED_SCREEN1);
@ -69,11 +68,10 @@ static void mqttStatusPublisher(void *handle) {
oledPrintf(OLED_SCREEN1, "Addr:%d.%d.%d.%d", addr[0], addr[1], addr[2], addr[3]); oledPrintf(OLED_SCREEN1, "Addr:%d.%d.%d.%d", addr[0], addr[1], addr[2], addr[3]);
oledPrintf(OLED_SCREEN1, "Network available:%d", isNetworkAvailable()); oledPrintf(OLED_SCREEN1, "Network available:%d", isNetworkAvailable());
oledPrintf(OLED_SCREEN1, "Uptime:%ld", uptime); oledPrintf(OLED_SCREEN1, "Uptime:%ld", uptime);
oledPrintf(OLED_SCREEN1, "RunHours:%d", globalDeviceStats->totalRunningHours);
oledPrintf(OLED_SCREEN1, "PowerCycl:%d", globalDeviceStats->totalPowercycles); oledPrintf(OLED_SCREEN1, "PowerCycl:%d", globalDeviceStats->totalPowercycles);
oledPrintf(OLED_SCREEN1, "Req:%ld", mbusCommStats->requestCnt); oledPrintf(OLED_SCREEN1, "Req:%ld", mbusCommStats->mbusRequestCnt);
oledPrintf(OLED_SCREEN1, "Err:%ld", mbusCommStats->errorCnt); oledPrintf(OLED_SCREEN1, "Err:%ld", mbusCommStats->mbusErrorCnt);
oledPrintf(OLED_SCREEN1, "Uart:%d", mbusCommStats->uartOverrunCnt + mbusCommStats->uartFramingErrCnt + mbusCommStats->uartParityErrCnt + mbusCommStats->uartNoiseErrCnt);
} }
void mqttCommHandler(void *handle) { void mqttCommHandler(void *handle) {
@ -92,6 +90,11 @@ void mqttCommHandler(void *handle) {
break; break;
case 1: case 1:
coloredMsg(LOG_GREEN, false, "mqch, resolving broker name");
if (! wizDnsQuery(config->brokerName, brokerAddress)) {
coloredMsg(LOG_GREEN, false, "mqch, query for broker address failed, going to error state");
state = 255;
}
coloredMsg(LOG_GREEN, false, "mqch, connecting to broker "); coloredMsg(LOG_GREEN, false, "mqch, connecting to broker ");
bool res = mqttConnect(&mqttClient, brokerAddress, 1883, "mbv3gw-client", NULL, NULL, NULL, 0, false, NULL, false); bool res = mqttConnect(&mqttClient, brokerAddress, 1883, "mbv3gw-client", NULL, NULL, NULL, 0, false, NULL, false);
coloredMsg(LOG_GREEN, false, "mqch, mqttConnect returns %d", res); coloredMsg(LOG_GREEN, false, "mqch, mqttConnect returns %d", res);
@ -106,7 +109,7 @@ void mqttCommHandler(void *handle) {
case 2: case 2:
coloredMsg(LOG_GREEN, false, "mqch, publish start-up"); coloredMsg(LOG_GREEN, false, "mqch, publish start-up");
res = publish(&mqttClient, StartupTopic, (const uint8_t*)message, strlen((char*)message), false); res = publish(&mqttClient, config->startupTopic, (const uint8_t*)message, strlen((char*)message), false);
coloredMsg(LOG_GREEN, false, "mqch, publish returned %d", res); coloredMsg(LOG_GREEN, false, "mqch, publish returned %d", res);
schAdd(mqttStatusPublisher, NULL, 0, 60000); schAdd(mqttStatusPublisher, NULL, 0, 60000);
coloredMsg(LOG_GREEN, false, "mqch, status publisher scheduled"); coloredMsg(LOG_GREEN, false, "mqch, status publisher scheduled");
@ -115,7 +118,7 @@ void mqttCommHandler(void *handle) {
case 3: case 3:
coloredMsg(LOG_GREEN, false, "mqch, subscribe watchdog"); coloredMsg(LOG_GREEN, false, "mqch, subscribe watchdog");
res = subscribe(&mqttClient, WatchdogTopic, MQTTQOS0); res = subscribe(&mqttClient, config->watchdogTopic, MQTTQOS0);
coloredMsg(LOG_GREEN, false, "mqch, subscribe returned %d", res); coloredMsg(LOG_GREEN, false, "mqch, subscribe returned %d", res);
schAdd(watchdogHandler, NULL, 60000, 60000); schAdd(watchdogHandler, NULL, 60000, 60000);
coloredMsg(LOG_GREEN, false, "mqch, watchdogHandler scheduled"); coloredMsg(LOG_GREEN, false, "mqch, watchdogHandler scheduled");
@ -145,6 +148,7 @@ void mqttCommHandler(void *handle) {
} }
void mqttCommInit() { void mqttCommInit() {
config = getConfig();
schAdd(mqttCommHandler, NULL, 0, 100); schAdd(mqttCommHandler, NULL, 0, 100);
} }

View File

@ -8,3 +8,4 @@ const uint8_t DHCP_SOCK = 0;
const uint8_t MQTT_SOCK = 1; const uint8_t MQTT_SOCK = 1;
const uint8_t CMD_SOCK = 2; const uint8_t CMD_SOCK = 2;
const uint8_t SYSLOG_SOCK = 3; const uint8_t SYSLOG_SOCK = 3;
const uint8_t DNS_SOCK = 4;

View File

@ -0,0 +1,57 @@
#include <cmdHelper.h>
#include <logger.h>
#include <mbusComm.h>
#include <eeprom.h>
static bool globalStatsCmd(uint8_t argc, char **args) {
uint32_t uptime = HAL_GetTick() / 1000;
sendFormatString(\
"Current uptime: %ld\n\r" \
"\n\r",
uptime
);
t_deviceStats *deviceStats = getGlobalDeviceStats();
sendFormatString(\
"Global Device statistics\n\r" \
" Total running hours: %ld\n\r" \
" Total power cycles: %ld\n\r" \
" Total requests: %ld\n\r" \
" Total failures: %ld\n\r" \
"\n\r",
deviceStats->totalRunningHours, deviceStats->totalPowercycles,
deviceStats->totalRequests, deviceStats->totalFailures
);
t_mbusCommStats *mbusStats = mbusCommGetStats();
sendFormatString(\
"Global Meterbus/UART statistics\n\r" \
" Meterbus Requests: %ld\n\r" \
" Meterbus Errors: %ld\n\r" \
" UART Octets: %ld\n\r" \
" UART Overruns: %ld\n\r" \
" UART Framing Errs: %ld\n\r" \
" UART Parity Errs: %ld\n\r" \
" UART Noise Errs: %ld\n\r",
mbusStats->mbusRequestCnt, mbusStats->mbusErrorCnt,
mbusStats->uartOctetCnt, mbusStats->uartOverrunCnt, mbusStats->uartFramingErrCnt, mbusStats->uartParityErrCnt, mbusStats->uartNoiseErrCnt
);
return true;
}
const cmd_t COMMANDS[] = {
{ .name = "globalStats", .cmdFunc = globalStatsCmd,
.help = \
"globalStats .......................... Show the global statistics\n\r" \
" counters requestCnt and errorCnt\n\r"
},
{ .name = "END_OF_CMDS", .help = "",.cmdFunc = NULL }
};
const cmd_t *getRegularCommands() {
return COMMANDS;
}

View File

@ -19,6 +19,7 @@ void ringbufferFree(ringbuffer_t *handle) {
handle->bufferWriteIdx = 0; handle->bufferWriteIdx = 0;
} }
int ringbufferPut(ringbuffer_t *handle, uint8_t *data, uint32_t dataLen) { int ringbufferPut(ringbuffer_t *handle, uint8_t *data, uint32_t dataLen) {
uint32_t freeSpace = 0; uint32_t freeSpace = 0;
if (handle->bufferReadIdx == handle->bufferWriteIdx) { if (handle->bufferReadIdx == handle->bufferWriteIdx) {
@ -61,7 +62,7 @@ uint8_t *ringbufferGet(ringbuffer_t *handle, uint32_t dataLen) {
int ringbufferGetOne(ringbuffer_t *handle) { int ringbufferGetOne(ringbuffer_t *handle) {
int res = -1; int res = -1;
if (! ringbufferEmpty(handle)) { if (handle->bufferReadIdx != handle->bufferWriteIdx) {
uint8_t r = *(handle->buffer + handle->bufferReadIdx); uint8_t r = *(handle->buffer + handle->bufferReadIdx);
handle->bufferReadIdx += 1; handle->bufferReadIdx += 1;
if (handle->bufferReadIdx == handle->bufferSize) { if (handle->bufferReadIdx == handle->bufferSize) {

View File

@ -11,16 +11,23 @@
#include <dhcp.h> #include <dhcp.h>
#include <show.h> #include <show.h>
#include <oled.h> #include <oled.h>
#include <dns.h>
#include <config.h>
wiz_NetInfo netInfo = {
.mac = { 0x00, 0xA0, 0x57, 0x05, 0x3E, 0x0D },
.dhcp = NETINFO_DHCP static t_configBlock *config;
};
wiz_NetInfo netInfo;
#define DHCP_BUFFER_SIZE 2048 #define DHCP_BUFFER_SIZE 2048
static uint8_t dhcpBuffer[DHCP_BUFFER_SIZE]; static uint8_t dhcpBuffer[DHCP_BUFFER_SIZE];
#define DNS_BUFFER_SIZE MAX_DNS_BUF_SIZE
static uint8_t dnsBuffer[DNS_BUFFER_SIZE];
extern const uint8_t DHCP_SOCK; extern const uint8_t DHCP_SOCK;
extern const uint8_t DNS_SOCK;
static bool networkAvailable = false; static bool networkAvailable = false;
@ -109,7 +116,22 @@ static void wizDHCPHandler(void *handle) {
} }
} }
bool wizDnsQuery(char *name, uint8_t *ip) {
bool retCode = false;
coloredMsg(LOG_BLUE, false, "wizdq, querying for %s", name);
int8_t res = DNS_run(netInfo.dns, (uint8_t*) name, ip);
coloredMsg(LOG_BLUE, false, "wizdq, DNS_run returns %d", res);
retCode = (res == 1);
if (retCode) {
coloredMsg(LOG_BLUE, false, "wizdq, got address %d.%d.%d.%d", ip[0], ip[1], ip[2], ip[3]);
}
return retCode;
}
static void wizPhyLinkHandler(void *handle) { static void wizPhyLinkHandler(void *handle) {
// this handler is anyhow called with a 1s period, so we reuse it for the DNS timer
DNS_time_handler();
static uint8_t lastStablePhyLink = 255; static uint8_t lastStablePhyLink = 255;
static bool dhcpInitialized = false; static bool dhcpInitialized = false;
@ -153,7 +175,12 @@ static void wizPhyLinkHandler(void *handle) {
} }
} }
int wizInit() { int wizInit() {
config = getConfig();
netInfo.dhcp = NETINFO_DHCP;
memcpy(netInfo.mac, config->macAddress, 6);
coloredMsg(LOG_BLUE, false, "wizI, resetting Ethernet module"); coloredMsg(LOG_BLUE, false, "wizI, resetting Ethernet module");
wizReset(true); wizReset(true);
activeDelay(2); activeDelay(2);
@ -196,6 +223,7 @@ int wizInit() {
res = ctlwizchip(CW_GET_ID, (void*) buf); res = ctlwizchip(CW_GET_ID, (void*) buf);
coloredMsg(LOG_BLUE, false, "wizI, CW_GET_ID: %d %02x %02x %02x %02x %02x %02x", res, buf[0], buf[1], buf[2], buf[3], buf[4], buf[5]); coloredMsg(LOG_BLUE, false, "wizI, CW_GET_ID: %d %02x %02x %02x %02x %02x %02x", res, buf[0], buf[1], buf[2], buf[3], buf[4], buf[5]);
DNS_init(DNS_SOCK, dnsBuffer);
schAdd(wizPhyLinkHandler, NULL, 0, 1000); schAdd(wizPhyLinkHandler, NULL, 0, 1000);
coloredMsg(LOG_BLUE, false, "wizI, PhyLink handler scheduled"); coloredMsg(LOG_BLUE, false, "wizI, PhyLink handler scheduled");

View File

@ -1,6 +1,6 @@
CFLAGS=-I../cube/User/Inc -DTEST CFLAGS=-I../cube/User/Inc -DTEST
test: ringbuffer.o logger.o test.o test: ringbuffer.o test.o
gcc -o $@ -lcunit $^ gcc -o $@ -lcunit $^
ringbuffer.o: ../cube/User/Src/ringbuffer.c ringbuffer.o: ../cube/User/Src/ringbuffer.c

View File

@ -2,7 +2,7 @@
#include <stdio.h> #include <stdio.h>
#include <stdbool.h> #include <stdbool.h>
#include <ringbuffer.h> #include <ringbuffer.h>
#include <logger.h> //#include <logger.h>
// #define DEBUG // #define DEBUG
@ -10,6 +10,7 @@
ringbuffer_t rb; ringbuffer_t rb;
void printRingbuffer(ringbuffer_t *rb) { void printRingbuffer(ringbuffer_t *rb) {
printf("Ringbuffer:\n"); printf("Ringbuffer:\n");
printf(" Size: %u\n", rb->bufferSize); printf(" Size: %u\n", rb->bufferSize);
@ -817,8 +818,75 @@ void testRingbuffer99() {
} }
void testRingbuffer100() {
#ifdef DEBUG
printf("Initialize ringbuffer\n");
#endif
ringbufferInit(&rb, 16);
#ifdef DEBUG
printRingbuffer(&rb);
#endif
CU_ASSERT(rb.buffer != NULL);
CU_ASSERT(rb.bufferSize == 16);
CU_ASSERT(rb.bufferWriteIdx == 0);
CU_ASSERT(rb.bufferReadIdx == 0);
CU_ASSERT(rb.buffer[0] == 0);
CU_ASSERT(rb.buffer[1] == 0);
CU_ASSERT(rb.buffer[2] == 0);
CU_ASSERT(rb.buffer[3] == 0);
CU_ASSERT(rb.buffer[4] == 0);
CU_ASSERT(rb.buffer[5] == 0);
CU_ASSERT(rb.buffer[6] == 0);
CU_ASSERT(rb.buffer[7] == 0);
CU_ASSERT(rb.buffer[8] == 0);
CU_ASSERT(rb.buffer[9] == 0);
CU_ASSERT(rb.buffer[10] == 0);
CU_ASSERT(rb.buffer[11] == 0);
CU_ASSERT(rb.buffer[12] == 0);
CU_ASSERT(rb.buffer[13] == 0);
CU_ASSERT(rb.buffer[14] == 0);
CU_ASSERT(rb.buffer[15] == 0);
}
void testRingbuffer101() {
#ifdef DEBUG
printf("\nPut 1 chars in buffer\n");
#endif
int r = ringbufferPutOne(&rb, 'a');
#ifdef DEBUG
printf("r = %d\n", r);
printRingbuffer(&rb);
#endif
CU_ASSERT(r == 0);
CU_ASSERT(rb.buffer != NULL);
CU_ASSERT(rb.bufferSize == 16);
CU_ASSERT(rb.bufferWriteIdx == 1);
CU_ASSERT(rb.bufferReadIdx == 0);
CU_ASSERT(rb.buffer[0] == 'a');
CU_ASSERT(rb.buffer[1] == 0);
CU_ASSERT(rb.buffer[2] == 0);
CU_ASSERT(rb.buffer[3] == 0);
CU_ASSERT(rb.buffer[4] == 0);
CU_ASSERT(rb.buffer[5] == 0);
CU_ASSERT(rb.buffer[6] == 0);
CU_ASSERT(rb.buffer[7] == 0);
CU_ASSERT(rb.buffer[8] == 0);
CU_ASSERT(rb.buffer[9] == 0);
CU_ASSERT(rb.buffer[10] == 0);
CU_ASSERT(rb.buffer[11] == 0);
CU_ASSERT(rb.buffer[12] == 0);
CU_ASSERT(rb.buffer[13] == 0);
CU_ASSERT(rb.buffer[14] == 0);
CU_ASSERT(rb.buffer[15] == 0);
}
/*
int init_suite_logger(void) { int init_suite_logger(void) {
logInit(); logInit();
return 0; return 0;
@ -949,7 +1017,7 @@ void testLogger2() {
CU_ASSERT(strcmp(goldValueFullNotOk, buffer) != 0); CU_ASSERT(strcmp(goldValueFullNotOk, buffer) != 0);
CU_ASSERT(strcmp(goldValueFullOk, buffer) == 0); CU_ASSERT(strcmp(goldValueFullOk, buffer) == 0);
} }
*/
int main() { int main() {
@ -980,11 +1048,14 @@ int main() {
(NULL == CU_add_test(ringbufferSuite, "test 14 of ringbuffer", testRingbuffer15)) || (NULL == CU_add_test(ringbufferSuite, "test 14 of ringbuffer", testRingbuffer15)) ||
(NULL == CU_add_test(ringbufferSuite, "test 14 of ringbuffer", testRingbuffer16)) || (NULL == CU_add_test(ringbufferSuite, "test 14 of ringbuffer", testRingbuffer16)) ||
(NULL == CU_add_test(ringbufferSuite, "test 99 of ringbuffer, free", testRingbuffer99)) || (NULL == CU_add_test(ringbufferSuite, "test 99 of ringbuffer, free", testRingbuffer99)) ||
(NULL == CU_add_test(ringbufferSuite, "test 100 of ringbuffer, free", testRingbuffer100)) ||
(NULL == CU_add_test(ringbufferSuite, "test 101 of ringbuffer, free", testRingbuffer101)) ||
0 ) { 0 ) {
CU_cleanup_registry(); CU_cleanup_registry();
return CU_get_error(); return CU_get_error();
} }
/*
CU_pSuite loggerSuite = CU_add_suite("Suite_Logger", init_suite_logger, clean_suite_logger); CU_pSuite loggerSuite = CU_add_suite("Suite_Logger", init_suite_logger, clean_suite_logger);
if (NULL == loggerSuite) { if (NULL == loggerSuite) {
CU_cleanup_registry(); CU_cleanup_registry();
@ -999,7 +1070,7 @@ int main() {
CU_cleanup_registry(); CU_cleanup_registry();
return CU_get_error(); return CU_get_error();
} }
*/
CU_basic_set_mode(CU_BRM_VERBOSE); CU_basic_set_mode(CU_BRM_VERBOSE);
CU_basic_run_tests(); CU_basic_run_tests();

View File

@ -47,8 +47,11 @@ cat $MAIN_C_BAK | \
cp $IT_C $IT_C_BAK cp $IT_C $IT_C_BAK
echo "// $PROCESSED" > $IT_C echo "// $PROCESSED" > $IT_C
cat $IT_C_BAK | \ cat $IT_C_BAK | \
sed -e 's,\(/\* USER CODE BEGIN Includes \*/\),\1\n#include "main2.h"\n,' | \ sed -e 's,\(/\* USER CODE BEGIN Includes \*/\),\1\n#include "main2.h"\n,' \
sed -e 's,\(/\* USER CODE BEGIN SysTick_IRQn 1 \*/\),\1\n SYSTICK_Callback();\n,' >> $IT_C -e 's,\(/\* USER CODE BEGIN SysTick_IRQn 1 \*/\),\1\n SYSTICK_Callback();\n,' \
-e 's,\(HAL_UART_IRQHandler(&huart5);\),// \1,' \
-e 's,\(/\* USER CODE BEGIN UART5_IRQn 1 \*/\),\1\n mbusCommISR();\n,' \
>> $IT_C
# mkdir w5500 # mkdir w5500
# pushd ioLibrary_Driver # pushd ioLibrary_Driver
@ -81,6 +84,7 @@ cat $MAKEFILE_BAK | \
sed -e 's,\(C_SOURCES = \\\),\1\n'"$SRC_EXT"' \\,' | \ sed -e 's,\(C_SOURCES = \\\),\1\n'"$SRC_EXT"' \\,' | \
sed -e 's,\(C_INCLUDES = \\\),\1\n-IioLibrary_Driver/Ethernet \\,' | \ sed -e 's,\(C_INCLUDES = \\\),\1\n-IioLibrary_Driver/Ethernet \\,' | \
sed -e 's,\(C_INCLUDES = \\\),\1\n-IioLibrary_Driver/Internet/DHCP \\,' | \ sed -e 's,\(C_INCLUDES = \\\),\1\n-IioLibrary_Driver/Internet/DHCP \\,' | \
sed -e 's,\(C_INCLUDES = \\\),\1\n-IioLibrary_Driver/Internet/DNS \\,' | \
sed -e 's,\(C_INCLUDES = \\\),\1\n-IUser/Inc \\,' | \ sed -e 's,\(C_INCLUDES = \\\),\1\n-IUser/Inc \\,' | \
sed -e 's,\(C_INCLUDES = \\\),\1\n-Ilibmbus \\,' | \ sed -e 's,\(C_INCLUDES = \\\),\1\n-Ilibmbus \\,' | \
sed -e 's,\(C_INCLUDES = \\\),\1\n-Ipubsubc/src \\,' | \ sed -e 's,\(C_INCLUDES = \\\),\1\n-Ipubsubc/src \\,' | \