-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathb64Encoding.py
More file actions
114 lines (92 loc) · 3.76 KB
/
Copy pathb64Encoding.py
File metadata and controls
114 lines (92 loc) · 3.76 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
#!/usr/bin/env python3
"""
Simple Base64 Encoding and MQTT Publishing
Continuously monitors stills folder for newest img.png, encodes it, and publishes via MQTT
"""
import paho.mqtt.client as mqtt
import base64
import json
import time
from datetime import datetime
import os
import glob
# MQTT Configuration
MQTT_BROKER = "localhost" # Local MQTT broker
MQTT_PORT = 1883
BASE_TOPIC = "encoded_data"
def encode_image_to_base64(image_path: str) -> str:
"""Encode image to base64 string"""
with open(image_path, "rb") as image_file:
encoded_bytes = base64.b64encode(image_file.read())
return encoded_bytes.decode("utf-8")
def get_newest_image():
"""Get the newest img.png file from the stills folder"""
pattern = "stills/img.png"
if os.path.exists(pattern):
return pattern
return None
def publish_image(client, image_path):
"""Encode and publish a single image"""
try:
# Encode the image
encoded_str = encode_image_to_base64(image_path)
print(f"✅ Encoded image: {len(encoded_str)} characters")
# Prepare data
data = {
"file_name": os.path.basename(image_path),
"file_size_bytes": os.path.getsize(image_path),
"encoded_data": encoded_str,
"timestamp": datetime.now().isoformat(),
"encoding": "base64"
}
# Publish to MQTT
topic = f"{BASE_TOPIC}/image/{os.path.basename(image_path)}"
message = json.dumps(data)
result = client.publish(topic, message)
if result.rc == mqtt.MQTT_ERR_SUCCESS:
print(f"📤 Published encoded image to: {topic}")
print(f" File: {os.path.basename(image_path)} ({data['file_size_bytes']} bytes)")
print(f" Encoded size: {len(encoded_str)} characters")
else:
print(f"❌ Failed to publish to {topic}")
except Exception as e:
print(f"❌ Error processing image {image_path}: {e}")
def main():
print("🚀 Starting Continuous Base64 Encoding and Publishing...")
print("📁 Monitoring stills folder for img.png...")
# Connect to MQTT broker
client = mqtt.Client()
try:
client.connect(MQTT_BROKER, MQTT_PORT, 60)
print(f"✅ Connected to MQTT broker at {MQTT_BROKER}:{MQTT_PORT}")
except Exception as e:
print(f"❌ Failed to connect to MQTT broker: {e}")
return
last_modified_time = 0
try:
while True:
image_path = get_newest_image()
if image_path and os.path.exists(image_path):
current_modified_time = os.path.getmtime(image_path)
# Check if the file has been modified since last check
if current_modified_time > last_modified_time:
print(f"\n🔄 New image detected: {image_path}")
print(f"📅 Modified: {datetime.fromtimestamp(current_modified_time)}")
publish_image(client, image_path)
last_modified_time = current_modified_time
print("⏳ Waiting for next image update...")
else:
print(".", end="", flush=True) # Show activity
else:
print("⏳ Waiting for img.png to appear in stills folder...")
time.sleep(1) # Check every second
except KeyboardInterrupt:
print("\n\n🛑 Stopping continuous monitoring...")
except Exception as e:
print(f"\n❌ Error in main loop: {e}")
finally:
# Disconnect
client.disconnect()
print("👋 Disconnected from MQTT broker. Done!")
if __name__ == "__main__":
main()