From 98766aaabcb1fa74123247a52e72a453b6da59f8 Mon Sep 17 00:00:00 2001
From: guowenxue <guowenxue@gmail.com>
Date: Sat, 22 Nov 2025 20:44:51 +0800
Subject: [PATCH] Update TSL2561 to sample for 5 times

---
 project/lightd/lightd.c      |    4 +-
 project/lightd/hal/tsl2561.c |   61 ++++++++++++++++++++++++++++++
 2 files changed, 62 insertions(+), 3 deletions(-)

diff --git a/project/lightd/hal/tsl2561.c b/project/lightd/hal/tsl2561.c
index a004e41..96a166a 100644
--- a/project/lightd/hal/tsl2561.c
+++ b/project/lightd/hal/tsl2561.c
@@ -142,7 +142,7 @@
     return 0;
 }
 
-int tsl2561_get_lux(float *lux)
+int tsl2561_sample_lux(float *lux)
 {
     int                 i, fd;
     int                 rv = 0;
@@ -223,3 +223,62 @@
     close(fd);
     return rv;
 }
+
+/**
+ * @brief 采样TSL2561光照强度数据
+ * @param lux 输出参数,存储计算后的光照强度值
+ * @return int 0成功,-1失败
+ */
+#define SAMPLE_COUNT 5
+int tsl2561_get_lux(float *lux)
+{
+    float       samples[SAMPLE_COUNT];
+    float       current_lux, temp;
+    int         valid_samples = 0;
+    int         i,j;
+
+    if (!lux) {
+        log_error("Invalid input argument\n");
+        return -1;
+    }
+
+    /* 采样N次数据 */
+    for (i=0; i<SAMPLE_COUNT; i++)
+    {
+        if (tsl2561_sample_lux(&current_lux) == 0) {
+            samples[valid_samples++] = current_lux;
+        }
+
+        if (i < SAMPLE_COUNT-1) {
+            msleep(100);
+        }
+    }
+
+    if (valid_samples == 0)
+    {
+        log_error("All TSL2561 samples failed\n");
+        return -2;
+    }
+
+    /* 只有一个有效采样,直接使用 */
+    if (valid_samples == 1)
+    {
+        *lux = samples[0];
+        return 0;
+    }
+
+    /* 对采样值进行排序 */
+    for (i=0; i<valid_samples-1; i++) {
+        for (j = i + 1; j < valid_samples; j++) {
+            if (samples[i] > samples[j]) {
+                temp = samples[i];
+                samples[i] = samples[j];
+                samples[j] = temp;
+            }
+        }
+    }
+
+    /* 取中位数 */
+    *lux = samples[valid_samples / 2];
+    return 0;
+}
diff --git a/project/lightd/lightd.c b/project/lightd/lightd.c
index f4f9af7..4af1957 100644
--- a/project/lightd/lightd.c
+++ b/project/lightd/lightd.c
@@ -142,8 +142,8 @@
     log_info("Auto light control thread start\n");
     while( ! g_signal.stop )
     {
-        /* TSL2561 update lux in every 5 minutes  */
-        if(check_timeout(&last_time, 300))
+        /* TSL2561 update lux in every 10 minutes  */
+        if(check_timeout(&last_time, 600))
         {
             /* The TSL2561 sensor is not present, do not turn on the light */
             if( !hwinfo->tsl2561 )

--
Gitblit v1.9.1