-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathhttp.go
More file actions
172 lines (145 loc) · 4.25 KB
/
http.go
File metadata and controls
172 lines (145 loc) · 4.25 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
package main
import (
"fmt"
"io"
"log"
"math"
"net/http"
"os"
"path/filepath"
"strconv"
"sync"
"time"
)
var (
lastReadingMu sync.Mutex
lastReading = math.NaN()
)
func handleOCR(w http.ResponseWriter, r *http.Request) {
if r.Method != http.MethodPost {
http.Error(w, "POST only", http.StatusMethodNotAllowed)
return
}
query := r.URL.Query()
var batLevel, batVoltage int
if v := query.Get("bat_level"); v != "" {
if level, err := strconv.Atoi(v); err == nil && level >= 0 && level <= 100 {
batLevel = level
metricBatteryLevel.Set(float64(level))
}
}
if v := query.Get("bat_voltage"); v != "" {
if voltage, err := strconv.Atoi(v); err == nil && voltage > 0 {
batVoltage = voltage
metricBatteryVoltage.Set(float64(voltage))
}
}
imageData, err := io.ReadAll(io.LimitReader(r.Body, 10<<20))
if err != nil {
http.Error(w, "failed to read body: "+err.Error(), http.StatusBadRequest)
return
}
defer r.Body.Close()
log.Printf("OCR request: image_bytes=%d bat_level=%d bat_voltage=%d", len(imageData), batLevel, batVoltage)
if len(imageData) == 0 {
http.Error(w, "empty body", http.StatusBadRequest)
return
}
// Respond immediately so the ESP32 can go back to sleep.
w.WriteHeader(http.StatusAccepted)
// Process OCR in the background.
go processOCR(imageData, batLevel, batVoltage)
}
func processOCR(imageData []byte, batLevel, batVoltage int) {
var cropped, masked bool
ocrData := imageData
if cropRect != nil {
data, err := cropImage(imageData, cropRect)
if err != nil {
log.Printf("crop error: %v, using original image", err)
} else {
ocrData = data
cropped = true
}
}
if len(ocrMasks) > 0 {
data, err := maskImage(ocrData, ocrMasks)
if err != nil {
log.Printf("mask error: %v, using unmasked image", err)
} else {
ocrData = data
masked = true
}
}
// Store images to disk before OCR so we have them even if OCR fails.
imagePath := storeImages(imageData, ocrData, cropped, masked)
tmpDir, err := os.MkdirTemp("", "ocr-")
if err != nil {
log.Printf("failed to create temp dir: %v", err)
metricOCRErrors.Inc()
return
}
defer os.RemoveAll(tmpDir)
tmpFile := filepath.Join(tmpDir, "image.jpg")
if err := os.WriteFile(tmpFile, ocrData, 0644); err != nil {
log.Printf("failed to write temp file: %v", err)
metricOCRErrors.Inc()
return
}
start := time.Now()
ocrOut, err := runOCR(tmpFile)
elapsed := time.Since(start)
metricOCRDuration.Observe(elapsed.Seconds())
if err != nil {
metricOCRErrors.Inc()
log.Printf("ocr error: %v", err)
return
}
reading := extractReading(ocrOut.Texts, ocrMatchRe, ocrFixRules, ocrMergeTexts)
// Append reading to CSV unconditionally so discarded values are still on disk.
storeReading(imagePath, reading)
if reading == "" {
log.Printf("OCR completed in %s: no reading found, texts=%v", elapsed, ocrOut.Texts)
return
}
val, err := strconv.ParseFloat(reading, 64)
if err != nil {
log.Printf("OCR completed in %s: invalid reading %q, texts=%v", elapsed, reading, ocrOut.Texts)
return
}
divided := val / meterDivisor
if ocrIncrOnly || ocrMaxIncr > 0 {
lastReadingMu.Lock()
prev := lastReading
if reason := checkReadingFilter(divided, prev, ocrIncrOnly, ocrMaxIncr); reason != "" {
lastReadingMu.Unlock()
log.Printf("%s", reason)
return
}
lastReading = divided
lastReadingMu.Unlock()
}
metricMeterReading.Set(val)
if mqttBroker != "" {
publishReading(divided, batLevel, batVoltage)
}
log.Printf("OCR completed in %s: reading=%s (%.3f m³) texts=%v", elapsed, reading, divided, ocrOut.Texts)
}
// checkReadingFilter returns a non-empty reason string if the reading should
// be discarded, or "" if it should be accepted. prev may be NaN for the first reading.
func checkReadingFilter(divided, prev float64, incrOnly bool, maxIncr float64) string {
if math.IsNaN(prev) {
return ""
}
if incrOnly && divided < prev {
return fmt.Sprintf("OCR incr-only: discarding reading %.3f < previous %.3f", divided, prev)
}
if maxIncr > 0 && divided-prev > maxIncr {
return fmt.Sprintf("OCR max-incr: discarding reading %.3f, increase %.3f > max %.3f (previous %.3f)", divided, divided-prev, maxIncr, prev)
}
return ""
}
func handleHealth(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(http.StatusOK)
w.Write([]byte("ok"))
}