Bläddra i källkod

Project worked

TelenkovDmitry 7 år sedan
förälder
incheckning
294cfd3caa

+ 1 - 1
config/common_config.h

@@ -105,7 +105,7 @@
   * @brief  SNMP протокол
   */
 #if defined HARDWARE_BT6702
-//#define SNMP_ENABLE
+#define SNMP_ENABLE
 #endif
 
 /**

+ 1 - 1
modules/MegaTec/megatec.h

@@ -46,7 +46,7 @@ typedef struct{
 	bool Flag_Present;
 }UPS_value_t;
 
-UPS_value_t UPS;
+extern UPS_value_t UPS;
 
 extern uint16_t TimeParam;
 extern uint16_t TimeParam2;

+ 469 - 467
modules/log/log.c

@@ -1,467 +1,469 @@
-#include "log.h"
-#include "rtc.h"
-#include "ringfs.h"
-#include "spi_flash.h"
-
-#include "FreeRTOS.h"
-#include "task.h"
-#include "semphr.h"
-
-#include <string.h>
-
-const char* logsStrShortRu[] =
-{
-	"Перезагрузка контроллера",
-    "Сброс настроек",
-    "Обновление ПО",
-    "Смена пароля",
-    "Сохранение настроек",
-    "Авторизация",
-    "Тест ИБП",
-    "Откл. нагрузки ИБП",
-    "Авария дискр. входа 1",
-    "Состояние выхода 1",
-    "Состояние выхода 2",
-    "Авария температуры",
-    "Авария вх. напряжения",
-    "Низкий заряд АКБ",
-    "Авария нагрузки",
-    "Авария связи с ИБП",
-    "Авария отключения АКБ",
-};
-
-bool flUpdateLog = false;
-static bool fLogInit = false;  // Флаг инициализации журнала
-
-#define LOG_TIME	1000*60*10
-
-#define LOG_FLASH_SECTOR_OFFSET	4
-
-#define ALARM_LOG_FLASH_SECTOR_OFFSET	258
-
-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)
-{
-    if (fLogInit) {
-        /* Ожидаем завершения работы с журнал */
-        if ( xSemaphoreTake(log_mutex, 10000) == pdTRUE ) {
-            //fLogInit = false;
-            //xSemaphoreGive(logMutex);
-            return true;
-        }
-        else {
-           return false;
-        }
-    }
-    else {
-        return true;
-    }
-}
-
-void log_task(void)
-{
-	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 = spi_flash_desc.sector_count/2 - LOG_FLASH_SECTOR_OFFSET;
-
-	ringfs_init(&fs, &ringfs_flash, LOG_ENTRY_VERSION, sizeof(log_entry_t));
-	if (format || ringfs_scan(&fs) != 0)
-		ringfs_format(&fs);
-
-	ringfs_flash2.sector_size = spi_flash_desc.sector_size;
-	ringfs_flash2.sector_count = spi_flash_desc.sector_count/2 - LOG_FLASH_SECTOR_OFFSET;
-
-	ringfs_init(&fs2, &ringfs_flash2, LOG_ENTRY_VERSION, sizeof(log_entry_t));
-	if (format || ringfs_scan(&fs2) != 0)
-		ringfs_format(&fs2);
-
-	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);
-
-	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);
-
-	strncpy(buf_value, log_data, len);
-	buf_value[0] = '\"';
-
-	for(i = 0; i < len; i++)
-	{
-		if(buf_value[i] == ' ')
-			buf_value[i] = ';';
-	}
-	buf_value[len - 1] = ';';
-
-	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(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);
-
-}
-
-/**
-  * @brief  Возвращает общее количество страниц
-  */
-uint32_t History_GetPageCount(void)
-{
-  return (((ringfs_count_estimate(&fs2)) / 10) + 1);
-}
-
-uint32_t History_GetTotalSTRCount(void)
-{
-	return ringfs_count_estimate(&fs2);
-}
-
-void History_GetPage(char *str, uint32_t page)
-{
-	TM_RTC_t rtc_data;
-	log_entry_t entry;
-	char buf[20];
-	uint8_t i;
-	int start =History_GetTotalSTRCount();//(fs.write.sector*fs.slots_per_sector + fs.write.slot);
-
-	memset(buf, 0, 20);
-	for(i=0; i < 10; i++){
-		fs2.cursor_position =  start - 10*(page-1) - 1 - i;
-		if(fs2.cursor_position < 0)
-			break;
-		else{
-			fs2.cursor.sector = (fs2.read.sector + fs2.cursor_position/fs.slots_per_sector)%fs2.flash->sector_count;
-			fs2.cursor.slot = fs2.cursor_position%fs2.slots_per_sector;
-		}
-		entry.type = LOG_LOGIN;
-		log_fetch(&entry, portMAX_DELAY);
-		strcat(str, "\"");
-		strncat(str, logsStrShortRu[entry.type], (strlen(logsStrShortRu[entry.type]) ));
-		strcat(str, ";");
-		entry.data[49] = 0;
-		strncat(str, entry.data, (strlen(entry.data) ));
-		strcat(str, ";");
-		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 History_GetData(int ptr, char *str, uint32_t size, bool start)
-{
-	TM_RTC_t rtc_data;
-	log_entry_t entry;
-	char buf[20];
-	char temp_str[FILE_BUF_MAX_LEN];
-	uint8_t i;
-	uint16_t len;
-	entry.type = LOG_LOGIN;
-	if(start)
-		log_rewind(&entry, portMAX_DELAY);
-
-	fs2.cursor_position =  ptr/STRING_SIZE_HISTORY;
-	fs2.cursor.sector = (fs2.read.sector + fs2.cursor_position/fs2.slots_per_sector)%fs2.flash->sector_count;
-	fs2.cursor.slot = fs2.cursor_position%fs2.slots_per_sector;
-
-	for(i = 0; i < size/STRING_SIZE_HISTORY; i++)
-	{
-		memset(temp_str, 0, 100);
-		log_fetch(&entry, portMAX_DELAY);
-		strncat(temp_str, logsStrShortRu[entry.type], (strlen(logsStrShortRu[entry.type])));
-		strcat(temp_str, ";");
-		entry.data[49] = 0;
-		strncat(temp_str, entry.data, (strlen(entry.data)));
-		strcat(temp_str, ";");
-		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(temp_str, buf);
-
-		len = strlen(temp_str);
-
-		  if (len <= STRING_SIZE_HISTORY - 1)
-		  {
-		    memset(&temp_str[len], ' ', STRING_SIZE_HISTORY - len - 1);
-		    strcat(temp_str, "\n");
-		  }
-		  else
-		  {
-		    temp_str[STRING_SIZE - 1] = 0xa;
-		  }
-		  strncat(str, temp_str, STRING_SIZE_HISTORY);
-
-	}
-	return strlen(str);
-
-}
+#include "log.h"
+#include "rtc.h"
+#include "ringfs.h"
+#include "spi_flash.h"
+
+#include "FreeRTOS.h"
+#include "task.h"
+#include "semphr.h"
+
+#include <string.h>
+
+char logFileBuf[FILE_BUF_MAX_LEN];
+
+const char* logsStrShortRu[] =
+{
+	"Перезагрузка контроллера",
+    "Сброс настроек",
+    "Обновление ПО",
+    "Смена пароля",
+    "Сохранение настроек",
+    "Авторизация",
+    "Тест ИБП",
+    "Откл. нагрузки ИБП",
+    "Авария дискр. входа 1",
+    "Состояние выхода 1",
+    "Состояние выхода 2",
+    "Авария температуры",
+    "Авария вх. напряжения",
+    "Низкий заряд АКБ",
+    "Авария нагрузки",
+    "Авария связи с ИБП",
+    "Авария отключения АКБ",
+};
+
+bool flUpdateLog = false;
+static bool fLogInit = false;  // Флаг инициализации журнала
+
+#define LOG_TIME	1000*60*10
+
+#define LOG_FLASH_SECTOR_OFFSET	4
+
+#define ALARM_LOG_FLASH_SECTOR_OFFSET	258
+
+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)
+{
+    if (fLogInit) {
+        /* Ожидаем завершения работы с журнал */
+        if ( xSemaphoreTake(log_mutex, 10000) == pdTRUE ) {
+            //fLogInit = false;
+            //xSemaphoreGive(logMutex);
+            return true;
+        }
+        else {
+           return false;
+        }
+    }
+    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 = spi_flash_desc.sector_count/2 - LOG_FLASH_SECTOR_OFFSET;
+
+	ringfs_init(&fs, &ringfs_flash, LOG_ENTRY_VERSION, sizeof(log_entry_t));
+	if (format || ringfs_scan(&fs) != 0)
+		ringfs_format(&fs);
+
+	ringfs_flash2.sector_size = spi_flash_desc.sector_size;
+	ringfs_flash2.sector_count = spi_flash_desc.sector_count/2 - LOG_FLASH_SECTOR_OFFSET;
+
+	ringfs_init(&fs2, &ringfs_flash2, LOG_ENTRY_VERSION, sizeof(log_entry_t));
+	if (format || ringfs_scan(&fs2) != 0)
+		ringfs_format(&fs2);
+
+	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);
+
+	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);
+
+	strncpy(buf_value, log_data, len);
+	buf_value[0] = '\"';
+
+	for(i = 0; i < len; i++)
+	{
+		if(buf_value[i] == ' ')
+			buf_value[i] = ';';
+	}
+	buf_value[len - 1] = ';';
+
+	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(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);
+
+}
+
+/**
+  * @brief  Возвращает общее количество страниц
+  */
+uint32_t History_GetPageCount(void)
+{
+  return (((ringfs_count_estimate(&fs2)) / 10) + 1);
+}
+
+uint32_t History_GetTotalSTRCount(void)
+{
+	return ringfs_count_estimate(&fs2);
+}
+
+void History_GetPage(char *str, uint32_t page)
+{
+	TM_RTC_t rtc_data;
+	log_entry_t entry;
+	char buf[20];
+	uint8_t i;
+	int start =History_GetTotalSTRCount();//(fs.write.sector*fs.slots_per_sector + fs.write.slot);
+
+	memset(buf, 0, 20);
+	for(i=0; i < 10; i++){
+		fs2.cursor_position =  start - 10*(page-1) - 1 - i;
+		if(fs2.cursor_position < 0)
+			break;
+		else{
+			fs2.cursor.sector = (fs2.read.sector + fs2.cursor_position/fs.slots_per_sector)%fs2.flash->sector_count;
+			fs2.cursor.slot = fs2.cursor_position%fs2.slots_per_sector;
+		}
+		entry.type = LOG_LOGIN;
+		log_fetch(&entry, portMAX_DELAY);
+		strcat(str, "\"");
+		strncat(str, logsStrShortRu[entry.type], (strlen(logsStrShortRu[entry.type]) ));
+		strcat(str, ";");
+		entry.data[49] = 0;
+		strncat(str, entry.data, (strlen(entry.data) ));
+		strcat(str, ";");
+		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 History_GetData(int ptr, char *str, uint32_t size, bool start)
+{
+	TM_RTC_t rtc_data;
+	log_entry_t entry;
+	char buf[20];
+	char temp_str[FILE_BUF_MAX_LEN];
+	uint8_t i;
+	uint16_t len;
+	entry.type = LOG_LOGIN;
+	if(start)
+		log_rewind(&entry, portMAX_DELAY);
+
+	fs2.cursor_position =  ptr/STRING_SIZE_HISTORY;
+	fs2.cursor.sector = (fs2.read.sector + fs2.cursor_position/fs2.slots_per_sector)%fs2.flash->sector_count;
+	fs2.cursor.slot = fs2.cursor_position%fs2.slots_per_sector;
+
+	for(i = 0; i < size/STRING_SIZE_HISTORY; i++)
+	{
+		memset(temp_str, 0, 100);
+		log_fetch(&entry, portMAX_DELAY);
+		strncat(temp_str, logsStrShortRu[entry.type], (strlen(logsStrShortRu[entry.type])));
+		strcat(temp_str, ";");
+		entry.data[49] = 0;
+		strncat(temp_str, entry.data, (strlen(entry.data)));
+		strcat(temp_str, ";");
+		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(temp_str, buf);
+
+		len = strlen(temp_str);
+
+		  if (len <= STRING_SIZE_HISTORY - 1)
+		  {
+		    memset(&temp_str[len], ' ', STRING_SIZE_HISTORY - len - 1);
+		    strcat(temp_str, "\n");
+		  }
+		  else
+		  {
+		    temp_str[STRING_SIZE - 1] = 0xa;
+		  }
+		  strncat(str, temp_str, STRING_SIZE_HISTORY);
+
+	}
+	return strlen(str);
+
+}

+ 77 - 77
modules/log/log.h

@@ -1,77 +1,77 @@
-#ifndef LOG_H
-#define LOG_H
-
-#include "main.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
-
-char logFileBuf[FILE_BUF_MAX_LEN];
-
-typedef enum {
-	LOG_SYSTEM_BOOT = 0x00,			// device booted
-	LOG_SYSTEM_DEFCONFIG,	// default config applied
-	LOG_UPDATE_SOFT,		//
-	LOG_PSW_CHANGE,		//
-	LOG_SETTING_SAVE,		//
-	LOG_LOGIN,		//
-	LOG_TEST_UPS,		//
-	LOG_SHUTDOWN_UPS,
-	LOG_ALARM_DIO,
-	LOG_DO0_STATE,
-	LOG_DO1_STATE,
-	LOG_ALARM_TEMP,
-	LOG_ALARM_LINE,
-	LOG_ALARM_LOW_BAT,
-	LOG_ALARM_POWER,
-	LOG_ALARM_UPS,
-	LOG_ALARM_AKB,
-	LOG_VALUE,
-	LOG_NONE,
-} __packed log_type_t;
-
-typedef struct {
-	uint32_t timestamp;
-	log_type_t type:8;
-	char data[50];
-} __packed log_entry_t;
-
-#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);
-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);
-
-
-#endif /* LOG_H */
+#ifndef LOG_H
+#define LOG_H
+
+#include "main.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
+
+extern char logFileBuf[FILE_BUF_MAX_LEN];
+
+typedef __packed enum {
+	LOG_SYSTEM_BOOT = 0x00,			// device booted
+	LOG_SYSTEM_DEFCONFIG,	// default config applied
+	LOG_UPDATE_SOFT,		//
+	LOG_PSW_CHANGE,		//
+	LOG_SETTING_SAVE,		//
+	LOG_LOGIN,		//
+	LOG_TEST_UPS,		//
+	LOG_SHUTDOWN_UPS,
+	LOG_ALARM_DIO,
+	LOG_DO0_STATE,
+	LOG_DO1_STATE,
+	LOG_ALARM_TEMP,
+	LOG_ALARM_LINE,
+	LOG_ALARM_LOW_BAT,
+	LOG_ALARM_POWER,
+	LOG_ALARM_UPS,
+	LOG_ALARM_AKB,
+	LOG_VALUE,
+	LOG_NONE,
+} log_type_t;
+
+typedef __packed struct {
+	uint32_t timestamp;
+	log_type_t type:8;
+	char data[50];
+} log_entry_t;
+
+#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);
+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);
+
+
+#endif /* LOG_H */

+ 195 - 183
modules/log/ringfs.h

@@ -1,183 +1,195 @@
-/*
- * Copyright © 2014 Kosma Moczek <kosma@cloudyourcar.com>
- * This program is free software. It comes without any warranty, to the extent
- * permitted by applicable law. You can redistribute it and/or modify it under
- * the terms of the Do What The Fuck You Want To Public License, Version 2, as
- * published by Sam Hocevar. See the COPYING file for more details.
- */
-
-#ifndef RINGFS_H
-#define RINGFS_H
-
-/**
- * @defgroup ringfs_api RingFS API
- * @{
- */
-
-#include <stdint.h>
-#include <unistd.h>
-#include "tinystdio.h"
-
-/**
- * Flash memory+parition descriptor.
- */
-struct ringfs_flash_partition
-{
-    int sector_size;            /**< Sector size, in bytes. */
-    int sector_offset;          /**< Partition offset, in sectors. */
-    int sector_count;           /**< Partition size, in sectors. */
-
-    /**
-     * Erase a sector.
-     * @param address Any address inside the sector.
-     * @returns Zero on success, -1 on failure.
-     */
-    int (*sector_erase)(struct ringfs_flash_partition *flash, int address);
-    /**
-     * Program flash memory bits by toggling them from 1 to 0.
-     * @param address Start address, in bytes.
-     * @param data Data to program.
-     * @param size Size of data.
-     * @returns size on success, -1 on failure.
-     */
-    ssize_t (*program)(struct ringfs_flash_partition *flash, int address, const void *data, size_t size);
-    /**
-     * Read flash memory.
-     * @param address Start address, in bytes.
-     * @param data Buffer to store read data.
-     * @param size Size of data.
-     * @returns size on success, -1 on failure.
-     */
-    ssize_t (*read)(struct ringfs_flash_partition *flash, int address, void *data, size_t size);
-};
-
-/** @private */
-struct ringfs_loc {
-    int sector;
-    int slot;
-};
-
-/**
- * RingFS instance. Should be initialized with ringfs_init() befure use.
- * Structure fields should not be accessed directly.
- * */
-struct ringfs {
-    /* Constant values, set once at ringfs_init(). */
-    struct ringfs_flash_partition *flash;
-    uint32_t version;
-    int object_size;
-    /* Cached values. */
-    int slots_per_sector;
-
-    /* Read/write pointers. Modified as needed. */
-    struct ringfs_loc read;
-    struct ringfs_loc write;
-    struct ringfs_loc cursor;
-
-    int cursor_position;
-};
-
-/**
- * Initialize a RingFS instance. Must be called before the instance can be used
- * with the other ringfs_* functions.
- *
- * @param fs RingFS instance to be initialized.
- * @param flash Flash memory interface. Must be implemented externally.
- * @param version Object version. Should be incremented whenever the object's
- *                semantics or size change in a backwards-incompatible way.
- * @param object_size Size of one stored object, in bytes.
- * @returns Zero on success, -1 on failure.
- */
-int ringfs_init(struct ringfs *fs, struct ringfs_flash_partition *flash, uint32_t version, int object_size);
-
-/**
- * Format the flash memory.
- *
- * @param fs Initialized RingFS instance.
- * @returns Zero on success, -1 on failure.
- */
-int ringfs_format(struct ringfs *fs);
-
-/**
- * Scan the flash memory for a valid filesystem.
- *
- * @param fs Initialized RingFS instance.
- * @returns Zero on success, -1 on failure.
- */
-int ringfs_scan(struct ringfs *fs);
-
-/**
- * Calculate maximum RingFS capacity.
- *
- * @param fs Initialized RingFS instance.
- * @returns Maximum capacity on success, -1 on failure.
- */
-int ringfs_capacity(struct ringfs *fs);
-
-/**
- * Calculate approximate object count.
- * Runs in O(1).
- *
- * @param fs Initialized RingFS instance.
- * @returns Estimated object count on success, -1 on failure.
- */
-int ringfs_count_estimate(struct ringfs *fs);
-
-/**
- * Calculate exact object count.
- * Runs in O(n).
- *
- * @param fs Initialized RingFS instance.
- * @returns Exact object count on success, -1 on failure.
- */
-int ringfs_count_exact(struct ringfs *fs);
-
-/**
- * Get current cursor position.
- *
- * @param fs Initialized RingFS instance.
- * @returns Current cursor position, -1 on failure.
- */
-int ringfs_cursor_position(struct ringfs *fs);
-
-/**
- * Append an object at the end of the ring. Deletes oldest objects as needed.
- *
- * @param fs Initialized RingFS instance.
- * @param object Object to be stored.
- * @returns Zero on success, -1 on failure.
- */
-int ringfs_append(struct ringfs *fs, const void *object);
-
-/**
- * Fetch next object from the ring, oldest-first. Advances read cursor.
- *
- * @param fs Initialized RingFS instance.
- * @param object Buffer to store retrieved object.
- * @returns Zero on success, -1 on failure.
- */
-int ringfs_fetch(struct ringfs *fs, void *object);
-
-/**
- * Discard all fetched objects up to the read cursor.
- *
- * @param fs Initialized RingFS instance.
- * @returns Zero on success, -1 on failure.
- */
-int ringfs_discard(struct ringfs *fs);
-
-/**
- * Rewind the read cursor back to the oldest object.
- *
- * @param fs Initialized RingFS instance.
- * @returns Zero on success, -1 on failure.
- */
-int ringfs_rewind(struct ringfs *fs);
-
-/**
- * @}
- */
-
-#endif
-
-/* vim: set ts=4 sw=4 et: */
+/*
+ * Copyright © 2014 Kosma Moczek <kosma@cloudyourcar.com>
+ * This program is free software. It comes without any warranty, to the extent
+ * permitted by applicable law. You can redistribute it and/or modify it under
+ * the terms of the Do What The Fuck You Want To Public License, Version 2, as
+ * published by Sam Hocevar. See the COPYING file for more details.
+ */
+
+#ifndef RINGFS_H
+#define RINGFS_H
+
+/**
+ * @defgroup ringfs_api RingFS API
+ * @{
+ */
+
+#include <stdint.h>
+#if defined ( __GNUC__ )
+#include <unistd.h>
+#endif
+#ifdef PRINTF_STDLIB
+#include <stdio.h>
+#endif
+#ifdef PRINTF_CUSTOM
+#include "tinystdio.h"
+#endif
+
+#if defined ( __ICCARM__ )
+typedef int ssize_t;
+#include <stdlib.h>
+#endif  
+   
+/**
+ * Flash memory+parition descriptor.
+ */
+struct ringfs_flash_partition
+{
+    int sector_size;            /**< Sector size, in bytes. */
+    int sector_offset;          /**< Partition offset, in sectors. */
+    int sector_count;           /**< Partition size, in sectors. */
+
+    /**
+     * Erase a sector.
+     * @param address Any address inside the sector.
+     * @returns Zero on success, -1 on failure.
+     */
+    int (*sector_erase)(struct ringfs_flash_partition *flash, int address);
+    /**
+     * Program flash memory bits by toggling them from 1 to 0.
+     * @param address Start address, in bytes.
+     * @param data Data to program.
+     * @param size Size of data.
+     * @returns size on success, -1 on failure.
+     */
+    ssize_t (*program)(struct ringfs_flash_partition *flash, int address, const void *data, size_t size);
+    /**
+     * Read flash memory.
+     * @param address Start address, in bytes.
+     * @param data Buffer to store read data.
+     * @param size Size of data.
+     * @returns size on success, -1 on failure.
+     */
+    ssize_t (*read)(struct ringfs_flash_partition *flash, int address, void *data, size_t size);
+};
+
+/** @private */
+struct ringfs_loc {
+    int sector;
+    int slot;
+};
+
+/**
+ * RingFS instance. Should be initialized with ringfs_init() befure use.
+ * Structure fields should not be accessed directly.
+ * */
+struct ringfs {
+    /* Constant values, set once at ringfs_init(). */
+    struct ringfs_flash_partition *flash;
+    uint32_t version;
+    int object_size;
+    /* Cached values. */
+    int slots_per_sector;
+
+    /* Read/write pointers. Modified as needed. */
+    struct ringfs_loc read;
+    struct ringfs_loc write;
+    struct ringfs_loc cursor;
+
+    int cursor_position;
+};
+
+/**
+ * Initialize a RingFS instance. Must be called before the instance can be used
+ * with the other ringfs_* functions.
+ *
+ * @param fs RingFS instance to be initialized.
+ * @param flash Flash memory interface. Must be implemented externally.
+ * @param version Object version. Should be incremented whenever the object's
+ *                semantics or size change in a backwards-incompatible way.
+ * @param object_size Size of one stored object, in bytes.
+ * @returns Zero on success, -1 on failure.
+ */
+int ringfs_init(struct ringfs *fs, struct ringfs_flash_partition *flash, uint32_t version, int object_size);
+
+/**
+ * Format the flash memory.
+ *
+ * @param fs Initialized RingFS instance.
+ * @returns Zero on success, -1 on failure.
+ */
+int ringfs_format(struct ringfs *fs);
+
+/**
+ * Scan the flash memory for a valid filesystem.
+ *
+ * @param fs Initialized RingFS instance.
+ * @returns Zero on success, -1 on failure.
+ */
+int ringfs_scan(struct ringfs *fs);
+
+/**
+ * Calculate maximum RingFS capacity.
+ *
+ * @param fs Initialized RingFS instance.
+ * @returns Maximum capacity on success, -1 on failure.
+ */
+int ringfs_capacity(struct ringfs *fs);
+
+/**
+ * Calculate approximate object count.
+ * Runs in O(1).
+ *
+ * @param fs Initialized RingFS instance.
+ * @returns Estimated object count on success, -1 on failure.
+ */
+int ringfs_count_estimate(struct ringfs *fs);
+
+/**
+ * Calculate exact object count.
+ * Runs in O(n).
+ *
+ * @param fs Initialized RingFS instance.
+ * @returns Exact object count on success, -1 on failure.
+ */
+int ringfs_count_exact(struct ringfs *fs);
+
+/**
+ * Get current cursor position.
+ *
+ * @param fs Initialized RingFS instance.
+ * @returns Current cursor position, -1 on failure.
+ */
+int ringfs_cursor_position(struct ringfs *fs);
+
+/**
+ * Append an object at the end of the ring. Deletes oldest objects as needed.
+ *
+ * @param fs Initialized RingFS instance.
+ * @param object Object to be stored.
+ * @returns Zero on success, -1 on failure.
+ */
+int ringfs_append(struct ringfs *fs, const void *object);
+
+/**
+ * Fetch next object from the ring, oldest-first. Advances read cursor.
+ *
+ * @param fs Initialized RingFS instance.
+ * @param object Buffer to store retrieved object.
+ * @returns Zero on success, -1 on failure.
+ */
+int ringfs_fetch(struct ringfs *fs, void *object);
+
+/**
+ * Discard all fetched objects up to the read cursor.
+ *
+ * @param fs Initialized RingFS instance.
+ * @returns Zero on success, -1 on failure.
+ */
+int ringfs_discard(struct ringfs *fs);
+
+/**
+ * Rewind the read cursor back to the oldest object.
+ *
+ * @param fs Initialized RingFS instance.
+ * @returns Zero on success, -1 on failure.
+ */
+int ringfs_rewind(struct ringfs *fs);
+
+/**
+ * @}
+ */
+
+#endif
+
+/* vim: set ts=4 sw=4 et: */

+ 3 - 1
peripheral_modules/inc/spi_flash.h

@@ -17,7 +17,9 @@
 #define SPI_FLASH_BLOCK_SIZE                16//4
 #define SPI_FLASH_BLOCK_NUMBER		        32
 
-typedef uint32_t ssize_t;
+#if defined ( __ICCARM__ )
+typedef int ssize_t;
+#endif
 
 typedef struct {
 	bool present;

+ 6 - 6
peripheral_modules/src/spi_flash.c

@@ -169,6 +169,7 @@ ssize_t spi_flash_read(int addr, void *buf, size_t len, uint32_t timeout) {
 #define TIMEOUT 10000
 
 uint16_t spi_flash_pp(int addr, const void *buf, size_t len, uint32_t timeout) {
+    uint8_t* foo = (uint8_t *)buf;
 //	ret = tn_mutex_lock(&spi_mutex, timeout);
 //	if (ret != TERR_NO_ERR)
 //		return ret;
@@ -260,9 +261,6 @@ bool spi_flash_init(void) {
 		tmp[2] == 0x44 && tmp[3] == 0x50))
 		return 0;
 
-	return 1;
-
-/*
 	// get parameter headers count
 	spi_flash_read_sfdp(0x06, tmp, 1);
 
@@ -278,7 +276,7 @@ bool spi_flash_init(void) {
 
 	// get flash density (size in bits)
 	if (spi_flash_read_sfdp(ptable + 4, &bitsize, 4) < 0 || !bitsize)
-		return;
+		return 0;
 
 	// find smallest available sector
 	for (i = 0; i < 4; i++) {
@@ -292,10 +290,12 @@ bool spi_flash_init(void) {
 		}
 	}
 	if (!spi_flash_desc.sector_size)
-		return;
+		return 0;
 
 	spi_flash_desc.present = true;
-*/
+    
+    return 1;
+
 }
 
 uint8_t txbuf1[] = "This film came out on DVD yesterday and I rushed to buy it. \

+ 23 - 0
projects/iar/bt-670x.ewp

@@ -189,6 +189,7 @@
           <state>STM32F407xx</state>
           <state>HARDWARE_BT6702</state>
           <state>OS_FREERTOS</state>
+          <state>PRINTF_STDLIB</state>
         </option>
         <option>
           <name>CCPreprocFile</name>
@@ -333,6 +334,7 @@
           <state>$PROJ_DIR$\..\..\modules\monitor</state>
           <state>$PROJ_DIR$\..\..\modules\jumper</state>
           <state>$PROJ_DIR$\..\..\modules\STM32F4x7_ETH_Driver</state>
+          <state>$PROJ_DIR$\..\..\modules\log</state>
           <state>$PROJ_DIR$\..\..\thirdparty\FreeRTOS\include</state>
           <state>$PROJ_DIR$\..\..\thirdparty\FreeRTOS\portable\IAR\ARM_CM4F</state>
           <state>$PROJ_DIR$\..\..\thirdparty\lwip\src\include</state>
@@ -1960,6 +1962,9 @@
     </group>
     <group>
       <name>common</name>
+      <file>
+        <name>$PROJ_DIR$\..\..\modules\common\hal.c</name>
+      </file>
       <file>
         <name>$PROJ_DIR$\..\..\modules\common\ring_buf.c</name>
       </file>
@@ -1996,9 +2001,18 @@
     </group>
     <group>
       <name>http_server</name>
+      <file>
+        <name>$PROJ_DIR$\..\..\modules\HTTP_Server\fsdata.c</name>
+        <excluded>
+          <configuration>Debug</configuration>
+        </excluded>
+      </file>
       <file>
         <name>$PROJ_DIR$\..\..\modules\HTTP_Server\http_server.c</name>
       </file>
+      <file>
+        <name>$PROJ_DIR$\..\..\modules\HTTP_Server\trap_params.c</name>
+      </file>
       <file>
         <name>$PROJ_DIR$\..\..\modules\HTTP_Server\web_params_api.c</name>
       </file>
@@ -2015,6 +2029,15 @@
         <name>$PROJ_DIR$\..\..\modules\leds\led.c</name>
       </file>
     </group>
+    <group>
+      <name>log</name>
+      <file>
+        <name>$PROJ_DIR$\..\..\modules\log\log.c</name>
+      </file>
+      <file>
+        <name>$PROJ_DIR$\..\..\modules\log\ringfs.c</name>
+      </file>
+    </group>
     <group>
       <name>megatec</name>
       <file>

+ 1 - 4
user/init_task.c

@@ -76,7 +76,7 @@ void InitTask(void *params)
  // xTaskCreate(vTaskWdt, "WDT", configMINIMAL_STACK_SIZE, NULL, tskIDLE_PRIORITY, NULL);
 // -----------------------------------------------------------------------------    
   //InitUSART();
-  ups_megatec_init();
+ //ups_megatec_init();
 // -----------------------------------------------------------------------------    
  // RCC_AHB1PeriphClockCmd(RCC_AHB1Periph_CRC, ENABLE);
   //SETTINGS_SetDefaultDebug();
@@ -126,9 +126,6 @@ void InitTask(void *params)
   //UDP_netsetting_init();
 // -----------------------------------------------------------------------------
 #ifdef UPS_ENABLE
- /* UPS_Init();
-  xTaskCreate(UPS_TaskParsing, "UPS_Parsing", 2*configMINIMAL_STACK_SIZE, NULL, tskIDLE_PRIORITY, NULL);
-  xTaskCreate(UPS_TaskState, "UPS_State", configMINIMAL_STACK_SIZE, NULL, tskIDLE_PRIORITY, NULL);*/
   xTaskCreate(UPS_Monitor, "UPS_Monitor", configMINIMAL_STACK_SIZE, NULL, tskIDLE_PRIORITY, NULL);
 #endif
 // -----------------------------------------------------------------------------    

+ 3 - 3
user/main.c

@@ -12,15 +12,15 @@
 #include "spi_flash.h"
 
 /* Размещение стека FreeRTOS в CCRAM */
-#if defined ( __ICCARM__ ) // IAR Compiler 
+#if defined ( __ICCARM__ ) 
 #pragma location = ".sram"
 uint8_t ucHeap[ configTOTAL_HEAP_SIZE ];
 #else
 uint8_t ucHeap[ configTOTAL_HEAP_SIZE ] __attribute__ ((section (".mb1text")));
-#endif
-
 /* Секция размещения СRC прошивки */
 uint32_t crc __attribute__ ((section (".crc"))) = 0xAABBCCDD;
+#endif
+
 
 void vApplicationTickHook(void) {
 }

+ 4 - 2
user/main.h

@@ -33,7 +33,9 @@
 
 #include <stdlib.h>
 #include <stdint.h>
+#if defined ( __GNUC__ )
 #include <unistd.h>
+#endif
 #include <stdbool.h>
 #include <string.h>
 
@@ -49,12 +51,12 @@
 
 #define tn_task_sleep(x) vTaskDelay(x)
 
-
+#if defined ( __GNUC__ )
 #ifdef __packed
 #undef __packed
 #endif
 #define __packed		__attribute__(( packed ))
-
+#endif
    
 //#define DEBUG