Sfoglia il codice sorgente

Тестовые скипты, события, тесты.

TelenkovDmitry 8 mesi fa
parent
commit
4acfa19759

+ 58 - 406
fw/modules/log/log.c

@@ -14,17 +14,22 @@
 #undef DBG
 #define DBG if(1)
 
-static bool archive_state = true;
+static bool archive_state = false;
 static bool log_state = true;
 
+static bool log_init_f = false;
+static bool archive_init_f = false;
+
 struct ringfs fs_log;
 struct ringfs fs_archive;
 
 SemaphoreHandle_t log_mutex;
+xQueueHandle log_queue;
 
 uint16_t log_entries_capacity;
 uint16_t archive_entries_capacity;
 
+void archive_task(void *params);
 void log_task(void *params);
 
 
@@ -108,10 +113,6 @@ void log_init(bool format)
 		ringfs_format(&fs_archive);
 	}
 	DBG printf("FAT2 true\r\n");
-	
-    // ---------------------------------------------------------------------- //
-    
-    //fLogInit = true;
 
 	log_mutex = xSemaphoreCreateMutex();
 
@@ -119,7 +120,15 @@ void log_init(bool format)
     
     archive_entries_capacity = ringfs_capacity(&fs_archive);
     
-	xTaskCreate(log_task, "log_task", 2*configMINIMAL_STACK_SIZE, NULL, tskIDLE_PRIORITY, NULL);
+	xTaskCreate(archive_task, "archive_task", 2*configMINIMAL_STACK_SIZE, NULL, tskIDLE_PRIORITY, NULL);
+        
+    log_queue = xQueueCreate(10, sizeof(log_entry_t));
+    
+    xTaskCreate(log_task, "log_task", 2*configMINIMAL_STACK_SIZE, NULL, tskIDLE_PRIORITY, NULL);
+    
+    log_init_f = true;
+    
+    archive_init_f = true;
 }
 
 //
@@ -174,7 +183,8 @@ int log_append(void *entry, entry_type_t entry_type)
     if (ret == pdFALSE)
         return ret;
   
-    entry_ptr->timestamp = rtc_get_ms();
+    if (entry_ptr->timestamp == 0)
+        entry_ptr->timestamp = rtc_get_ms();
     
     if (entry_type == LOG_ENTRY) 
     {
@@ -198,13 +208,15 @@ int log_append(void *entry, entry_type_t entry_type)
 //
 uint16_t log_capacity(void)
 {
-    return ringfs_count_estimate(&fs_log);
+    //return ringfs_count_estimate(&fs_log);
+    return ringfs_count_exact(&fs_log);
 }
 
 //
 uint16_t log_arch_capacity(void)
 {
-    return ringfs_count_estimate(&fs_archive);
+    //return ringfs_count_estimate(&fs_archive);
+    return ringfs_count_exact(&fs_archive);
 }
 
 // -------------------------------------------------------------------------- //
@@ -278,7 +290,7 @@ void log_format(uint8_t val)
     }
 }
 
-// Добавить n архивных записей
+// Добавить n записей журнала
 int log_add_random_entry(uint8_t val, uint32_t cnt_entry)
 {
     int ret;
@@ -319,6 +331,27 @@ int log_add_random_entry(uint8_t val, uint32_t cnt_entry)
     return ret;
 }
 
+//
+int log_add_entry(log_event_type_t type, log_event_state_t state, 
+                  uint8_t channel_number, float value)
+{
+    log_entry_t entry;
+    
+    if (!log_init_f)
+        return -1;
+    
+    entry.timestamp = rtc_get_ms();
+    entry.code_type = (uint8_t)type;
+    entry.code_state = (uint8_t)state;
+    entry.channel_number = channel_number;
+    entry.value = value;
+    
+    xQueueSend(log_queue, &entry, 0);
+    
+    return 0;
+}
+
+
 //
 void test_fetch(void)
 {
@@ -341,18 +374,19 @@ void log_log_state(bool state)
 }
 
 
-void log_task(void *params)
+void archive_task(void *params)
 {
     int ret = 0;
     archive_entry_t entry = {0};
     
     for (;;)
     {
-        if (!archive_state) {
+        if ((!archive_state) || (!archive_init_f)) {
             vTaskDelay(1000);
             continue;
         }
         
+        entry.timestamp = 0;
         entry.input_value = (uint8_t)input_state_bit;
         
         DBG printf("Append archive entry...");
@@ -370,401 +404,19 @@ void log_task(void *params)
     }
 }
 
-
-
-
-
-
-
-
-#if 0
-
-char logFileBuf[FILE_BUF_MAX_LEN];
-
-char name_login[50];
-
-extern const char* logsStrShortRu[];
-
-bool flUpdateLog = false;
-static bool fLogInit = false;  // Флаг инициализации журнала
-
-#define LOG_TIME	1000*60*10
-
-static int op_sector_erase(struct ringfs_flash_partition *flash, int address) {
-	(void)flash;
-	int ret;
-	ret = spi_flash_erase_sector(address, 0);
-	return ret;
-}
-
-static ssize_t op_program(struct ringfs_flash_partition *flash, int address, const void *data, size_t size) {
-	(void)flash;
-	int ret;
-	ret = spi_flash_write(address, data, size, 0);
-	return ret;
-}
-
-static ssize_t op_read(struct ringfs_flash_partition *flash, int address, void *data, size_t size) {
-	(void)flash;
-	int ret;
-	ret = spi_flash_read(address, data, size, 0);
-	return ret;
-}
-
-static struct ringfs_flash_partition ringfs_flash = {
-	.sector_offset = LOG_FLASH_SECTOR_OFFSET,
-
-	.sector_erase = op_sector_erase,
-	.program = op_program,
-	.read = op_read,
-};
-
-static struct ringfs fs;
-
-static struct ringfs_flash_partition ringfs_flash2 = {
-	.sector_offset = ALARM_LOG_FLASH_SECTOR_OFFSET,
-
-	.sector_erase = op_sector_erase,
-	.program = op_program,
-	.read = op_read,
-};
-
-static struct ringfs fs2;
-
-static SemaphoreHandle_t log_mutex;
-
-
-/**
-  * @brief  Отключает журнал для безопасной перезагрузки
-  */
-bool LOG_Disable(void)
+//
+void log_task(void *params)
 {
-    if (fLogInit) {
-        /* Ожидаем завершения работы с журнал */
-        if ( xSemaphoreTake(log_mutex, 10000) == pdTRUE ) {
-            //fLogInit = false;
-            //xSemaphoreGive(logMutex);
-            return true;
-        }
-        else {
-           return false;
+    int ret;
+    log_entry_t entry;
+      
+    for (;;)
+    {
+        if (xQueueReceive(log_queue, &entry, portMAX_DELAY) == pdTRUE)
+        {
+            DBG printf("Try append LOG entry... ");
+            ret = log_append((void*)&entry, LOG_ENTRY);
+            DBG printf("Result: %i\r\n", ret);
         }
     }
-    else {
-        return true;
-    }
-}
-
-void log_task(void* params)
-{
-	for(;;){
-		flUpdateLog = true;
-		vTaskDelay(LOG_TIME);
-		/*vTaskDelay(50);
-		log_event_data(LOG_SYSTEM_BOOT, "Администратор");
-		log_add(")215.7;215.7;220.5;000;50.1;2.30;25.0;00000001;");*/
-	}
-}
-
-void log_init(bool format) {
-	DBG printf(">>> Event log\n");
-
-	if (!spi_flash_desc.present)
-		return;
-	ringfs_flash.sector_size = spi_flash_desc.sector_size;
-	ringfs_flash.sector_count = SECTOR_COUNT;
-
-	ringfs_init(&fs, &ringfs_flash, LOG_ENTRY_VERSION, sizeof(log_entry_t));
-	if (format || ringfs_scan(&fs) != 0){
-		DBG printf("FAT1 false\r\n");
-		ringfs_format(&fs);
-	}
-	DBG printf("FAT1 true\r\n");
-	ringfs_flash2.sector_size = spi_flash_desc.sector_size;
-	ringfs_flash2.sector_count = SECTOR_COUNT;
-
-	ringfs_init(&fs2, &ringfs_flash2, LOG_ENTRY_VERSION, sizeof(log_entry_t));
-	if (format || ringfs_scan(&fs2) != 0){
-		DBG printf("FAT2 false\r\n");
-		ringfs_format(&fs2);
-	}
-	DBG printf("FAT2 true\r\n");
-	fLogInit = true;
-
-	log_mutex = xSemaphoreCreateMutex();
-
-	xTaskCreate(log_task, ( char * ) "log_task", configMINIMAL_STACK_SIZE * 2, NULL, tskIDLE_PRIORITY, NULL);
-}
-
-
-int capacity_flash = 0;
-int count_flash = 0;
-int log_test(void) {
-	int ret;
-	log_entry_t entry;
-
-	log_init(false);
-	capacity_flash = ringfs_capacity(&fs);
-	count_flash = ringfs_count_exact(&fs);
-	DBG printf("\tCapacity:   %d\n", capacity_flash);
-	DBG printf("\tCount:      %d\n", count_flash);
-
-	DBG printf("\tAppending   ");
-//	ret = log_event(LOG_SYSTEM_DEFCONFIG, 0, 0);
-	DBG printf("%s\n", ret == 0 ? "ok" : "error");
-	if (ret == 0)
-		return -1;
-
-//	ret = log_event(LOG_SYSTEM_DEFCONFIG, 0, 512);
-	entry.timestamp = 0;
-	entry.type = 0;
-	DBG printf("\tFetching    ");
-	if (log_fetch(&entry, portMAX_DELAY) == 0){
-		DBG printf("ok, time=%d, type=%d\n", entry.timestamp, entry.type);
-		log_fetch(&entry, portMAX_DELAY);
-		entry.timestamp = 0;
-			entry.type = 0;
-		log_fetch(&entry, portMAX_DELAY);
-		entry.timestamp = 0;
-					entry.type = 0;
-				log_fetch(&entry, portMAX_DELAY);
-				entry.timestamp = 0;
-							entry.type = 0;
-						log_fetch(&entry, portMAX_DELAY);
-		return 0;
-	}
-	else {
-		DBG printf("fail\n");
-		return -1;
-	}
-
-	DBG printf("\tDiscarding  ");
-	if (log_discard(&entry,portMAX_DELAY) == 0)
-		DBG printf("ok\n");
-	else {
-		DBG printf("fail\n");
-		return -1;
-	}
-
-	return 0;
 }
-
-int log_append(log_entry_t *entry) {
-	int ret;
-	TM_RTC_t data;
-	ret = xSemaphoreTake( log_mutex, portMAX_DELAY );
-	if (ret == pdFALSE)
-		return ret;
-	if (!entry->timestamp){
-		TM_RTC_GetDateTime(&data, TM_RTC_Format_BIN);
-		entry->timestamp = data.unix;
-	}
-	if(entry->type == LOG_VALUE)
-		ringfs_append(&fs, entry);
-	else
-		ringfs_append(&fs2, entry);
-	xSemaphoreGive(log_mutex);
-	return ret;
-}
-
-int log_fetch(log_entry_t *entry, uint32_t timeout) {
-	int ret;
-	ret = xSemaphoreTake( log_mutex, (TickType_t)timeout );
-	if (ret == pdFALSE)
-		return ret;
-	if(entry->type == LOG_VALUE)
-		ret = ringfs_fetch(&fs, entry);
-	else
-		ret = ringfs_fetch(&fs2, entry);
-	xSemaphoreGive(log_mutex);
-	return ret;
-}
-
-int log_rewind(log_entry_t *entry, uint32_t timeout) {
-	int ret;
-	ret = xSemaphoreTake( log_mutex, (TickType_t)timeout );
-	if (ret == pdFALSE)
-		return ret;
-	if(entry->type == LOG_VALUE)
-		ret = ringfs_rewind(&fs);
-	else
-		ret = ringfs_rewind(&fs2);
-	xSemaphoreGive(log_mutex);
-	return ret;
-}
-
-int log_discard(log_entry_t *entry, uint32_t timeout) {
-	int ret;
-	ret = xSemaphoreTake( log_mutex, (TickType_t)timeout );
-	if (ret == pdFALSE)
-		return ret;
-	if(entry->type == LOG_VALUE)
-		ret = ringfs_discard(&fs);
-	else
-		ret = ringfs_discard(&fs2);
-	xSemaphoreGive(log_mutex);
-	return ret;
-}
-
-void log_event_data(log_type_t type, char *data)
-{
-	log_entry_t entry_data;
-
-	entry_data.timestamp = 0;
-	entry_data.type = type;
-	strncpy(entry_data.data, data, 49);
-	if (fLogInit)
-		log_append(&entry_data);
-}
-
-void log_add(char *log_data)
-{
-	char buf_value[50];
-	uint8_t i, len;
-
-
-	memset(buf_value, 0, 50);
-	len = strlen(log_data);
-	if (len != UPS_DATA_STRING_SIZE) {
-		//len = UPS_DATA_STRING_SIZE;
-		return;
-	}
-
-	strncpy(buf_value, log_data, len);
-
-	DBG printf("UPS log data: %s\r\n", log_data);
-	buf_value[0] = '\"';
-
-	for(i = 0; i < len; i++)
-	{
-		if(buf_value[i] == ' ')
-			buf_value[i] = ';';
-	}
-	buf_value[len - 1] = ';';
-
-	if(fLogInit){
-		if(fs.write.slot>67)
-		{
-			log_entry_t entry_data;
-			entry_data.timestamp = 0;
-			log_event_data(LOG_VALUE, buf_value);
-		}
-		else
-		log_event_data(LOG_VALUE, buf_value);
-	}
-
-}
-
-/**
-  * @brief  Возвращает true если журнал проинициализирован
-  */
-bool LOG_IsInit()
-{
-  return fLogInit;
-}
-
-/**
-  * @brief  Возвращает общее количество страниц
-  */
-uint32_t LOG_GetPageCount(void)
-{
-  return (((ringfs_count_estimate(&fs)) / 10) + 1);
-}
-
-uint32_t LOG_GetTotalSTRCount(void)
-{
-	return ringfs_count_estimate(&fs);
-}
-
-void LOG_GetPage_tabs(char *str, uint32_t page)
-{
-	TM_RTC_t rtc_data;
-	log_entry_t entry;
-	char buf[20];
-	uint8_t i;
-	int start =LOG_GetTotalSTRCount();//(fs.write.sector*fs.slots_per_sector + fs.write.slot);
-
-	memset(buf, 0, 20);
-	for(i=0; i < 10; i++){
-		fs.cursor_position =  start - 10*(page-1) - 1 - i;
-		if(fs.cursor_position < 0)
-			break;
-		else{
-			fs.cursor.sector = (fs.read.sector + fs.cursor_position/fs.slots_per_sector)%fs.flash->sector_count;
-			fs.cursor.slot = fs.cursor_position%fs.slots_per_sector;
-		}
-		entry.type = LOG_VALUE;
-		log_fetch(&entry, portMAX_DELAY);
-		entry.data[49] = 0;
-		strncat(str, entry.data, strlen(entry.data));
-		TM_RTC_GetDateTimeFromUnix(&rtc_data, entry.timestamp);
-		sprintf(buf, "%02i.%02i.%02i %02i:%02i:%02i",  rtc_data.date, rtc_data.month,
-		rtc_data.year, rtc_data.hours, rtc_data.minutes, rtc_data.seconds);
-		strcat(str, buf);
-		strcat(str, "\",");
-		strcat(str, "\r\n");
-	}
-}
-
-void LOG_GetPage(char *str, uint32_t page)
-{
-	TM_RTC_t rtc_data;
-	log_entry_t entry;
-	char buf[20];
-	uint8_t i;
-	int start =LOG_GetTotalSTRCount();//(fs.write.sector*fs.slots_per_sector + fs.write.slot);
-
-	memset(buf, 0, 20);
-	for(i=0; i < 10; i++){
-		fs.cursor_position =  start - 10*(page-1) - 1 - i;
-		if(fs.cursor_position < 0)
-			break;
-		else{
-			fs.cursor.sector = (fs.read.sector + fs.cursor_position/fs.slots_per_sector)%fs.flash->sector_count;
-			fs.cursor.slot = fs.cursor_position%fs.slots_per_sector;
-		}
-		entry.type = LOG_VALUE;
-		log_fetch(&entry, portMAX_DELAY);
-		entry.data[49] = 0;
-		strncat(str, entry.data, strlen(entry.data));
-		TM_RTC_GetDateTimeFromUnix(&rtc_data, entry.timestamp);
-		sprintf(buf, "%02i.%02i.%02i %02i:%02i:%02i",  rtc_data.date, rtc_data.month,
-		rtc_data.year, rtc_data.hours, rtc_data.minutes, rtc_data.seconds);
-		strcat(str, buf);
-		strcat(str, "\",");
-	}
-}
-
-uint32_t LOG_GetData(int ptr, char *str, uint32_t size, bool start)
-{
-	TM_RTC_t rtc_data;
-	log_entry_t entry;
-	char buf[20];
-	uint8_t i;
-	entry.type = LOG_VALUE;
-	if(start)
-		log_rewind(&entry, portMAX_DELAY);
-
-	fs.cursor_position =  ptr/STRING_SIZE;
-	fs.cursor.sector = (fs.read.sector + fs.cursor_position/fs.slots_per_sector)%fs.flash->sector_count;
-	fs.cursor.slot = fs.cursor_position%fs.slots_per_sector;
-
-	for(i = 0; i < size/STRING_SIZE; i++)
-	{
-		entry.type = LOG_VALUE;
-		log_fetch(&entry, portMAX_DELAY);
-		entry.data[49] = 0;
-		strncat(str, &entry.data[1], (strlen(entry.data) - 1));
-		TM_RTC_GetDateTimeFromUnix(&rtc_data, entry.timestamp);
-		sprintf(buf, "%02i.%02i.%02i %02i:%02i:%02i",  rtc_data.date, rtc_data.month,
-		rtc_data.year, rtc_data.hours, rtc_data.minutes, rtc_data.seconds);
-		strcat(str, buf);
-		strcat(str, "\n");
-	}
-	return strlen(str);
-
-}
-
-
-
-#endif

+ 26 - 84
fw/modules/log/log.h

@@ -14,11 +14,11 @@ extern "C" {
 
 #define LOG_FLASH_SECTOR_OFFSET         4
 
-#define LOG_FLASH_SECTOR_COUNT          51 //252
+#define LOG_FLASH_SECTOR_COUNT          51
 
 #define ARCHIVE_FLASH_SECTOR_OFFSET     260
 
-#define ARCHIVE_FLASH_SECTOR_COUNT      38 //252
+#define ARCHIVE_FLASH_SECTOR_COUNT      38
 
 #define SECTOR_COUNT (spi_flash_desc.sector_count/2 - LOG_FLASH_SECTOR_OFFSET)
 
@@ -29,32 +29,27 @@ extern "C" {
 //
 typedef enum 
 {
-    LOG_SYSTEM_BOOT = 0,			// device booted
-    LOG_SYSTEM_DEFCONFIG,	// default config applied
-    LOG_UPDATE_SOFT,
-    LOG_TURN_ON,		//
-    LOG_PSW_CHANGE,		//
-    LOG_SETTING_SAVE,		//
-    LOG_LOGIN_TELNET,		//
-    LOG_LOGIN_SSH,
-    LOG_LOGIN,		//
-    LOG_TEST_UPS,		//
-    LOG_SHUTDOWN_UPS,
-    LOG_ALARM_VAC_LOW_OUTPUT,
-    LOG_ALARM_VAC_HIGH_OUTPUT,
-    LOG_ALARM_HIGH_TEMP,
-    LOG_ALARM_LOW_TEMP,
-    LOG_ALARM_LINE,
-    LOG_ALARM_LOW_BAT,
-    LOG_ALARM_POWER,
-    LOG_ALARM_UPS,
-    LOG_ALARM_AKB,
-    LOG_ALARM_CHANGE_AKB,
-    LOG_PHASE_FAIL,
-    LOG_EPO_FAIL,
-    LOG_VALUE,
+    LOG_SYSTEM_BOOT = 1,    // включение питания/перезагрузка
+    LOG_CLOCK_CHANGE,       // перевод времени
+    LOG_UPDATE_FW,          // обновление FW
+    LOG_SYSTEM_ERR,         // самодиагностика/системная ошибка
+    LOG_CHANGE_CONFIG,      // изменение конфигурации
+    LOG_OUPUTS,             // диагностика выходов
+    LOG_SETPOINT,           // срабатывание уставок
+    LOG_SAVE_MODE,          // переход в безопасный режим
+    LOG_CLEAR,              // очистка журнала/архива
+    
     LOG_NONE,
-} log_type_t;
+
+} log_event_type_t;
+
+
+typedef enum
+{
+    LOG_EVENT_STATE_ERR = 0,
+    LOG_EVENT_STATE_OK,
+    
+} log_event_state_t;
 
 
 typedef enum
@@ -131,6 +126,10 @@ void log_format(uint8_t val);
 //
 int log_add_random_entry(uint8_t val, uint32_t cnt_entry);
 
+//
+int log_add_entry(log_event_type_t type, log_event_state_t state, 
+                  uint8_t channel_number, float value);
+
 //
 void test_fetch(void);
 
@@ -155,61 +154,4 @@ extern uint16_t archive_entries_capacity;
 #endif
 
 
-
-
-#if 0
-
-#include "main.h"
-#include "common_config.h"
-
-#define FILE_BUF_MAX_LEN            10*STRING_SIZE_HISTORY // Размер временного буфера для отправки/копирования Лог файла
-#define FILE_BUF_MAX_LEN_LOG        10*STRING_SIZE // Размер временного буфера для отправки/копирования Лог файла
-#define STRING_SIZE                 64
-#define STRING_SIZE_HISTORY		  	100
-#define UPS_DATA_STRING_SIZE        47
-
-extern char logFileBuf[FILE_BUF_MAX_LEN];
-
-extern char name_login[50];
-
-
-#define LOG_ENTRY_VERSION 1
-
-extern void log_init(bool format);
-extern int log_test(void);
-extern int log_append(log_entry_t *entry);
-extern int log_fetch(log_entry_t *entry, uint32_t timeout);
-extern int log_rewind(log_entry_t *entry, uint32_t timeout);
-extern int log_discard(log_entry_t *entry, uint32_t timeout);
-
-void log_add(char *log_data);
-void log_event_data(log_type_t type, char *data);
-
-/**
-  * @brief  Возвращает true если журнал проинициализирован
-  */
-bool LOG_IsInit();
-
-/**
-  * @brief  Отключает журнал для безопасной перезагрузки
-  */
-bool LOG_Disable(void);
-
-/**
-  * @brief  Возвращает общее количество страниц
-  */
-uint32_t LOG_GetPageCount(void);
-uint32_t LOG_GetTotalSTRCount(void);
-void LOG_GetPage(char *str, uint32_t page);
-void LOG_GetPage_tabs(char *str, uint32_t page);
-uint32_t LOG_GetData(int ptr, char *str, uint32_t size, bool start);
-
-uint32_t History_GetPageCount(void);
-uint32_t History_GetTotalSTRCount(void);
-void History_GetPage(char *str, uint32_t page);
-uint32_t History_GetData(int ptr, char *str, uint32_t size, bool start);
-void History_GetPage_tabs(char *str, uint32_t page);
-
-#endif
-
 #endif /* __LOG_H */

+ 2 - 10
fw/modules/log/log_api.c

@@ -75,16 +75,8 @@ int log_get_log_entry(uint32_t index, struct ringfs *fs, void *entry)
 	}
     
     log_fetch(entry, LOG_ENTRY, portMAX_DELAY);
-
-#if 0    
-    uint64_t timestamp;
-    uint8_t code_type;  // код типа события
-    uint8_t code_state; // код состояния
-    uint8_t channel_number; // номер канала
-    float value;        // значение
-    uint8_t crc;
-#endif    
-#if 1    
+   
+#if 0
 /*
     printf("[log entry] timestamp = % " PRId64 ", code_type = %u, code_state = %u, \
            channel_number = %u, value = %f, crc = %u\r\n", ent->timestamp, \

+ 8 - 1
fw/modules/modbus/modbus.c

@@ -103,6 +103,8 @@ void modbus_task(void *params)
 //
 void modbus_params(void *params)
 {
+    bool ret = false;
+    
     for (;;)
     {
         if (mb_action != MB_NO_ACTION)
@@ -158,7 +160,12 @@ void modbus_params(void *params)
                   
                 case MB_SAVE_SETTINGS :
                     
-                    settings_save(&settings);
+                    ret = settings_save(&settings);
+                  
+                    if (settings_is_changed(&settings)) {
+                        log_add_entry(LOG_CHANGE_CONFIG, (log_event_state_t)ret, 0, 0);
+                    }
+                    
 
                 break;
                 

+ 19 - 4
fw/modules/modbus/modbus_params.c

@@ -462,8 +462,8 @@ void get_log_entries_number(uint8_t* buf, uint8_t size)
     static uint16_t capacity;
     
     capacity = swap_uint16(log_capacity());
-    
-    buf = (uint8_t*)&capacity;
+    memcpy(buf, &capacity, 2);
+    //buf = (uint8_t*)&capacity;
 }
 
 //
@@ -472,8 +472,8 @@ void get_archive_entries_number(uint8_t* buf, uint8_t size)
     static uint16_t capacity;
       
     capacity = swap_uint16(log_arch_capacity());
-    
-    buf = (uint8_t*)&capacity;
+    memcpy(buf, &capacity, 2);
+    //buf = (uint8_t*)&capacity;
 }
 
 //
@@ -567,7 +567,22 @@ mb_delay_action_t mb_control(void)
 //
 mb_delay_action_t mb_set_rtc(void)
 {
+    float delta;
+    uint64_t now = rtc_get_ms();
+
+    if (now >= value_64)
+        delta = (float)(now - value_64);
+    else
+        delta = (float)(value_64 - now);
+    
+    
     rtc_set_in_ms((uint32_t)(value_64/1000));
+    
+    // -------------------------------------------------------------------------- //
+    // EVENT. Перевод времени.
+    log_add_entry(LOG_CLOCK_CHANGE, LOG_EVENT_STATE_OK, 0, delta);
+    
+    
     return MB_NO_ACTION;
 }
 

+ 39 - 12
fw/modules/settings/settings_api.c

@@ -113,8 +113,8 @@ void settings_set_all_default(void)
 {
     settings_set_modbus_def(&settings.com_settings.mb_port);
     
-    memset(settings.com_settings.model, 0, MODEL_LEN);
-    memcpy(settings.com_settings.model, MODEL_STR, strlen(MODEL_STR));
+    //memset(settings.com_settings.model, 0, MODEL_LEN);
+    //memcpy(settings.com_settings.model, MODEL_STR, strlen(MODEL_STR));
         
     settings.settings_version = SETTINGS_VERSION;
     settings.critical_section_crc = settings_get_crit_sec_crc(&settings);
@@ -412,18 +412,23 @@ void settings_do_def(settings_t *settings)
 // -------------------------------------------------------------------------- //
 
 // Запись структуры настроек во flash
-void settings_save(settings_t *settings)
+bool settings_save(settings_t *settings)
 {
+    bool ret = false;
+    
     xSemaphoreTake(flash_mutex, portMAX_DELAY);
     
     settings->critical_section_crc = settings_get_crit_sec_crc(settings);
     
-    settings_write_to_flash((uint8_t*)settings, sizeof(settings_t));
+    ret = settings_write_to_flash((uint8_t*)settings, sizeof(settings_t));
+    
     xSemaphoreGive(flash_mutex);
+    
+    return ret;
 }
 
 //
-void settings_write_to_flash(uint8_t *data, uint32_t size)
+bool settings_write_to_flash(uint8_t *data, uint32_t size)
 {
     uint32_t baseAddress = SETTINGS_SECTOR;
     uint32_t checkCrc = 0;
@@ -431,8 +436,7 @@ void settings_write_to_flash(uint8_t *data, uint32_t size)
     flash_status_type status;
     uint8_t *ptr = data;
     
-    for (uint8_t i = 0; i < 3; i++)
-    {	
+
         flash_unlock();
     
         settings_erase_flash_sector();
@@ -440,7 +444,7 @@ void settings_write_to_flash(uint8_t *data, uint32_t size)
         for (uint32_t i = 0; i < size; i++)
             if ((status = flash_byte_program(baseAddress++, *data++)) != FLASH_OPERATE_DONE) {
                 DBG printf("FLASH_ProgramByte error: status = %d\r\n", status);
-                break;
+                return false;
             }
     
         if ((status = flash_word_program((uint32_t)CRC_ADDRESS, crc)) != FLASH_OPERATE_DONE) {
@@ -455,9 +459,11 @@ void settings_write_to_flash(uint8_t *data, uint32_t size)
         checkCrc = settings_get_crc((settings_t*)ptr);
     
         /* Проверяем  CRC того что было записано */
-        if (checkCrc == crc)
-            break;
-    }
+        if ((checkCrc != crc) || (status != FLASH_OPERATE_DONE)) {
+            return false;
+        }
+        
+        return true;
 }
 
 // Очистка сектора настроек
@@ -470,6 +476,27 @@ void settings_erase_flash_sector(void)
     }
 }
 
+//
+bool settings_is_changed(settings_t *new_settings)
+{
+    uint32_t baseAddress = SETTINGS_SECTOR;
+    uint32_t settings_size = sizeof(settings_t);
+    uint8_t old_data;
+    uint8_t new_data;
+    uint8_t *ptr = (uint8_t*)new_settings;
+    
+    for (uint32_t i = 0; i < settings_size; i++)
+    {
+        old_data = (*(uint32_t*)baseAddress++);
+        new_data = *ptr++;
+        if (old_data != new_data)
+            return false;
+    }
+    
+    return true;
+}
+
+
 // -------------------------------------------------------------------------- //
 
 void settings_print(void)
@@ -519,7 +546,7 @@ void settings_print(void)
         default : break;
     }
 
-    printf("Модель: %s\r\n", settings.com_settings.model);
+    //printf("Модель: %s\r\n", settings.com_settings.model);
     
   
 }

+ 6 - 3
fw/modules/settings/settings_api.h

@@ -74,7 +74,7 @@ typedef struct
 typedef struct
 {
     uint16_t    mb_port;    // Настройки порта для modbus
-    char model[MODEL_LEN];  // Модель
+    //char model[MODEL_LEN];  // Модель
 } com_settings_t;
 
 
@@ -172,14 +172,17 @@ void settings_do_def(settings_t *settings);
 // -------------------------------------------------------------------------- //
 
 // Запись структуры настроек во flash
-void settings_save(settings_t *settings);
+bool settings_save(settings_t *settings);
 
 //
-void settings_write_to_flash(uint8_t *data, uint32_t size);
+bool settings_write_to_flash(uint8_t *data, uint32_t size);
 
 // Очистка сектора настроек
 void settings_erase_flash_sector(void);
 
+//
+bool settings_is_changed(settings_t *new_settings);
+
 //
 void settings_print(void);
 

+ 2 - 1
fw/modules/terminal/terminal_sbs.cpp

@@ -111,7 +111,8 @@ int SbsTerminal::execute(int argc, const char * const *argv)
     }
     //
     if (strcmp(argv[0], "lstate") == 0) {
-        log_log_state(atoi(argv[1]));
+        if (argc > 1)
+            log_log_state(atoi(argv[1]));
         return 0;
     }
     //

+ 23 - 2
fw/user/main.cpp

@@ -40,6 +40,7 @@ extern "C" {
 #include <stdio.h>
 #include <stdbool.h>
 #include <string.h>
+#include <stdlib.h>
 
 
 void init_task(void *argument);
@@ -136,7 +137,7 @@ void init_task(void *argument)
     // Настройки параметров порта Modbus
     settings_set_modbus_params(settings.com_settings.mb_port);
     
-#if 0    
+#if 1    
     settings_set_all_default();
     settings_save(&settings);
 #endif      
@@ -248,12 +249,32 @@ void init_task(void *argument)
     
     log_init(false);
     
-    // Тесты USB
+// -------------------------------------------------------------------------- //
+// EVENT. Обновление FW.
+    
+    uint16_t update_status = bpr_data_read(BACKUP_UPDATE_STATUS);
+    
+    if (update_status == IAP_UPDATE_OK)
+        log_add_entry(LOG_UPDATE_FW, LOG_EVENT_STATE_OK, 0, atof(FW_VERSION));
+    else if (update_status == IAP_UPDATE_ERROR)
+        log_add_entry(LOG_UPDATE_FW, LOG_EVENT_STATE_ERR, 0, atof(FW_VERSION));
+        
+    bpr_data_write(BACKUP_UPDATE_STATUS, IAP_UPDATE_NO);
+
+// -------------------------------------------------------------------------- //
+// EVENT. Включение питания/перезагрузка.    
+    log_add_entry(LOG_SYSTEM_BOOT, (log_event_state_t)0, 0, 0);
+
+// -------------------------------------------------------------------------- //    
+// Тесты USB
+
     //usb_eth_init();
      
       
     //vTaskDelete(NULL);
             
+    settings_is_changed(&settings);
+    
     for (;;)
     {
         mux_led_proc();

+ 1 - 1
iap/modules/settings/settings_api.h

@@ -31,7 +31,7 @@ typedef struct
 typedef struct
 {
     uint16_t    mb_port;    // Настройки порта для modbus
-    char model[MODEL_LEN];  // Модель
+    //char model[MODEL_LEN];  // Модель
       
 } com_settings_t;
 

BIN
output/cortex_crc.exe


+ 0 - 1
output/crc.bat

@@ -1 +0,0 @@
-start "crc" cortex_crc.exe fw.bin 0x08021000 0x080С0FFF

BIN
output/fw.bin


File diff suppressed because it is too large
+ 423 - 397
project/ewarm/iap/iap.dep


File diff suppressed because it is too large
+ 997 - 1016
project/ewarm/module_universal_io.dep


+ 7 - 6
shared/board/common_config.h

@@ -14,8 +14,8 @@
 /**
   * @brief  Версия прошивки
   */
-#define FW_VERSION                      "1.00.01"
-   
+#define FW_VERSION                      "1.01"
+
 /**
   * @brief  Адрес сектора настроек
   */ 	
@@ -74,10 +74,11 @@
 // -------------------------------------------------------------------------- //
 
 // Флаги, статусы
-
+    
+#define IAP_UPDATE_NO                   0   // обновления не было
 #define IAP_UPDATE_OK                   1
-#define IAP_UPDATE_ERROR                0
-
-
+#define IAP_UPDATE_ERROR                2
 
+      
+      
 #endif /* #ifndef COMMON_CONFIG_H */

+ 0 - 4
shared/freemodbus/functions/mbfuncfile.c

@@ -50,10 +50,6 @@
 #if  MB_FUNC_READ_FILE_RECORD_ENABLED > 0
 eMBException eMBFuncReadFileRecord( UCHAR * pucFrame, USHORT * usLen )
 {
-    //*usLen += 1;
-    
-    //printf("usLen: %u\r\n", *usLen);
-  
     return eMBFuncReadFileRecordCB(pucFrame, usLen);
 }
 #endif

+ 0 - 1
shared/rtc/rtc.c

@@ -397,7 +397,6 @@ uint32_t rtc_foo(void)
 void rtc_set_in_ms(uint64_t ms)
 {
     TM_RTC_SetDataTimeUnix(ms);
-    
 }
 
 //

BIN
tools/__pycache__/log_reader.cpython-310.pyc


BIN
tools/__pycache__/modbus.cpython-310.pyc


BIN
tools/__pycache__/sys_params.cpython-310.pyc


+ 4 - 3
tools/digital_io.py

@@ -20,10 +20,10 @@ class IO_Digital(IO_Module):
 def main():
     colorama.init(autoreset=True)
     dev = IO_Digital('COM24', 115200, 15)
-    dev.MB_DEBUG = True
+    dev.modbus.MB_DEBUG = False
 
     '''Системные переменные и параметры'''
-    dev.sys.get_system_vars()
+    # dev.sys.get_system_vars()
 
     ''' Установить текущее время с учетом часового пояса'''
     # dev.sys.set_rtc()     
@@ -34,7 +34,8 @@ def main():
     # dev.log.get_random_entries()
     # dev.log.set_archive_period(10)
     # dev.log.get_all_archive()
-
+    dev.log.get_all_log()
+    
     '''Сохранение настроек'''
     # dev.sys.save_sattings()
 

BIN
tools/fw.bin


+ 40 - 3
tools/log_reader.py

@@ -3,14 +3,39 @@ from mb_registers import reg_table
 from colorama import Fore
 from random import randint
 from time import sleep
+import time
 import colorama
 import struct
+from datetime import datetime, timedelta, timezone
 
 ARCHIVE_ENTRY = 0x06
 LOG_ENTRY = 0x07
 
 
-class LogReader():
+
+class LogParser:
+
+    events = {1: 'Включение питания/перезагрузка',
+              2: 'Перевод времени',
+              3: 'Обновление ПО'}
+
+    utc_offset = 10800
+
+    def __init__(self) -> None:
+        t = datetime.now(timezone.utc).astimezone()
+        self.utc_offset = t.utcoffset() // timedelta(seconds=1)
+        
+
+    @staticmethod
+    def print_entry(entry: tuple, index: int):
+        timestamp = time.ctime(entry[0]/1000 - LogParser.utc_offset)
+        ans = f"[LOG] {index}: {LogParser.events[entry[1]]}, {timestamp}, state: {entry[2]}, channel: {entry[3]}, value: {entry[4]}"
+        print(Fore.CYAN + ans)
+
+
+
+
+class LogReader:
     def __init__(self, modbus: Modbus):
         self.modbus = modbus
         self.log_capacity = 0
@@ -57,6 +82,14 @@ class DigitalLogReader(LogReader):
         entry = struct.unpack('<QBB', data[5:15])
         print(Fore.CYAN + str(entry))
 
+    def get_log_entry(self, index):
+        data = self.modbus.read_file_record(LOG_ENTRY, index, 1)
+        return struct.unpack('<QBBBfB', data[5:21])
+
+    def print_log_entry(self, index):
+        data = self.modbus.read_file_record(LOG_ENTRY, index, 1)
+        LogParser.print_entry(struct.unpack('<QBBBfB', data[5:21]), index)
+
     def get_random_log_entry(self):
         data = self.modbus.read_file_record(LOG_ENTRY, randint(1, self.log_entries_number), 1)
         entry = struct.unpack('<QBBBfB', data[5:21])
@@ -73,11 +106,15 @@ class DigitalLogReader(LogReader):
 
     def get_all_archive(self):
         self.get_log_info()
+        
         for i in range(1, self.archive_entries_number + 1):
             print(self.get_archive_entry(i))
-            sleep(0.1)
-
 
+    def get_all_log(self):
+        self.get_log_info()
+        for i in range(1, self.log_entries_number + 1):
+            self.print_log_entry(i)
+            sleep(0.01)
 
 
 class AnalogInputLogReader(LogReader):

+ 2 - 2
tools/modbus.py

@@ -41,7 +41,7 @@ class ChecksumError(IOError):
 class MBError(IOError):
     pass
 
-class ModbusMixin():
+class ModbusMixin:
     def print_hex(self, text: str, data: bytes):
         print(text, *tuple(map(lambda x: '0x{:02X}'.format(x), (i for i in data))))
 
@@ -50,7 +50,7 @@ class Modbus(ModbusMixin):
 
     # MB_CRC_TABLE: Sequence[int] = DEFAULT_MB_CRC_TABLE
     REF_TYPE = 6
-    MB_TIMEOUT: float = 0.05
+    MB_TIMEOUT: float = 0.5 # 0.05
     MB_CRC_TABLE: Sequence[int] = DEFAULT_MB_CRC_TABLE
     MB_DEBUG: bool = False
     MB_TRIES: int = 3

+ 0 - 1
tools/sys_params.py

@@ -62,7 +62,6 @@ class IO_SysParams:
         # Локальное время модуля
         t = time.ctime(self.get_rtc()/1000 - self.utc_offset)
         print("Local time : ", Fore.LIGHTMAGENTA_EX + t)
-        
 
     def set_system_vars(self, password: int):
         """Установка системных настроек"""

Some files were not shown because too many files changed in this diff