update
Browse files
app.py
CHANGED
@@ -14,7 +14,8 @@ import random
|
|
14 |
import cv2
|
15 |
from PIL import ImageDraw
|
16 |
|
17 |
-
|
|
|
18 |
logging.basicConfig(
|
19 |
level=logging.INFO,
|
20 |
format='%(asctime)s - %(name)s - %(levelname)s - %(message)s',
|
@@ -25,198 +26,94 @@ logging.basicConfig(
|
|
25 |
)
|
26 |
logger = logging.getLogger("bambu-analysis")
|
27 |
|
28 |
-
#
|
29 |
-
|
30 |
-
|
31 |
-
|
32 |
-
PASSWORD = "bblp"
|
33 |
DEFAULT_SERIAL = "0309CA471800852"
|
34 |
|
35 |
-
#
|
36 |
-
|
37 |
-
|
38 |
-
|
39 |
-
|
40 |
-
|
41 |
-
|
42 |
-
|
|
|
|
|
|
|
43 |
|
44 |
-
# Global variables
|
45 |
latest_data = {
|
46 |
"bed_temperature": "N/A",
|
47 |
"nozzle_temperature": "N/A",
|
48 |
"status": "N/A",
|
49 |
-
"update_time": "Waiting for data..."
|
50 |
}
|
51 |
|
52 |
-
# MQTT Client setup
|
53 |
client = None
|
54 |
-
response_topic = None
|
55 |
|
56 |
def create_client(host, port, username, password):
|
57 |
-
"""
|
58 |
-
global client
|
59 |
-
|
60 |
-
|
61 |
-
|
62 |
-
|
63 |
-
|
64 |
-
|
65 |
-
|
66 |
-
|
67 |
-
logger.info("Connecting to MQTT broker...")
|
68 |
-
client.connect(host, port, keepalive=5)
|
69 |
-
client.loop_start()
|
70 |
-
SIMULATION_MODE = False # 连接成功,禁用模拟模式
|
71 |
-
return True
|
72 |
-
except Exception as e:
|
73 |
-
logger.error(f"Failed to create MQTT client: {e}")
|
74 |
-
SIMULATION_MODE = True # 连接失败,启用模拟模式
|
75 |
-
return False
|
76 |
|
77 |
def on_connect(client, userdata, flags, rc):
|
78 |
-
"""MQTT连接回调"""
|
79 |
logger.info(f"Connected with result code {rc}")
|
80 |
-
if rc == 0:
|
81 |
-
logger.info("Successfully connected to MQTT broker")
|
82 |
-
else:
|
83 |
-
logger.error(f"Failed to connect to MQTT broker with code: {rc}")
|
84 |
-
global SIMULATION_MODE
|
85 |
-
SIMULATION_MODE = True # 连接失败,启用模拟模式
|
86 |
|
87 |
def on_message(client, userdata, message):
|
88 |
-
"""MQTT消息回调"""
|
89 |
global latest_data
|
90 |
logger.info("Received message")
|
91 |
try:
|
92 |
data = json.loads(message.payload)
|
93 |
-
logger.debug(f"Message content: {data}")
|
94 |
-
|
95 |
latest_data["bed_temperature"] = data.get("bed_temperature", "N/A")
|
96 |
latest_data["nozzle_temperature"] = data.get("nozzle_temperature", "N/A")
|
97 |
latest_data["status"] = data.get("status", "N/A")
|
98 |
-
latest_data["update_time"] = time.strftime("%Y-%m-%d %H:%M:%S")
|
99 |
except Exception as e:
|
100 |
logger.error(f"Error parsing MQTT message: {e}")
|
101 |
|
102 |
-
def update_simulated_data():
|
103 |
-
"""更新模拟数据"""
|
104 |
-
global simulated_data
|
105 |
-
# 随机波动温度,模拟真实情况
|
106 |
-
bed_temp = float(simulated_data["bed_temperature"])
|
107 |
-
nozzle_temp = float(simulated_data["nozzle_temperature"])
|
108 |
-
|
109 |
-
bed_temp += random.uniform(-1.0, 1.0)
|
110 |
-
nozzle_temp += random.uniform(-2.0, 2.0)
|
111 |
-
|
112 |
-
# 保持在合理范围内
|
113 |
-
bed_temp = max(55, min(65, bed_temp))
|
114 |
-
nozzle_temp = max(195, min(205, nozzle_temp))
|
115 |
-
|
116 |
-
simulated_data["bed_temperature"] = f"{bed_temp:.1f}"
|
117 |
-
simulated_data["nozzle_temperature"] = f"{nozzle_temp:.1f}"
|
118 |
-
simulated_data["update_time"] = time.strftime("%Y-%m-%d %H:%M:%S")
|
119 |
-
|
120 |
-
# 随机改变状态
|
121 |
-
if random.random() < 0.05: # 5%的概率改变状态
|
122 |
-
states = ["Printing", "Idle", "Heating", "Cooling"]
|
123 |
-
simulated_data["status"] = random.choice(states)
|
124 |
-
|
125 |
def get_data(serial=DEFAULT_SERIAL):
|
126 |
-
|
127 |
-
|
|
|
|
|
|
|
|
|
|
|
128 |
|
129 |
-
logger.info(f"
|
|
|
130 |
|
131 |
-
#
|
132 |
-
|
133 |
-
|
134 |
-
update_simulated_data()
|
135 |
-
return (
|
136 |
-
simulated_data["status"],
|
137 |
-
simulated_data["bed_temperature"],
|
138 |
-
simulated_data["nozzle_temperature"],
|
139 |
-
simulated_data["update_time"]
|
140 |
-
)
|
141 |
|
142 |
-
|
143 |
-
|
144 |
-
|
145 |
-
|
146 |
-
|
147 |
-
|
148 |
-
update_simulated_data()
|
149 |
-
return (
|
150 |
-
simulated_data["status"],
|
151 |
-
simulated_data["bed_temperature"],
|
152 |
-
simulated_data["nozzle_temperature"],
|
153 |
-
simulated_data["update_time"]
|
154 |
-
)
|
155 |
-
|
156 |
-
# 尝试获取真实数据
|
157 |
-
try:
|
158 |
-
request_topic = f"bambu_a1_mini/request/{serial}"
|
159 |
-
response_topic = f"bambu_a1_mini/response/{serial}"
|
160 |
-
|
161 |
-
logger.info(f"Subscribing to {response_topic}")
|
162 |
-
client.subscribe(response_topic)
|
163 |
-
|
164 |
-
# 发送请求获取数据
|
165 |
-
logger.info(f"Publishing request to {request_topic}")
|
166 |
-
client.publish(request_topic, json.dumps("HI"))
|
167 |
-
|
168 |
-
# 等待数据更新
|
169 |
-
timeout = 3
|
170 |
-
logger.info("Waiting for response...")
|
171 |
-
time.sleep(timeout)
|
172 |
-
|
173 |
-
# 检查是否收到响应
|
174 |
-
if latest_data["bed_temperature"] == "N/A":
|
175 |
-
# 没有收到响应,使用模拟数据
|
176 |
-
logger.warning("No response from printer, using simulation data")
|
177 |
-
update_simulated_data()
|
178 |
-
return (
|
179 |
-
simulated_data["status"],
|
180 |
-
simulated_data["bed_temperature"],
|
181 |
-
simulated_data["nozzle_temperature"],
|
182 |
-
simulated_data["update_time"]
|
183 |
-
)
|
184 |
|
185 |
-
|
186 |
-
|
187 |
-
|
188 |
-
|
189 |
-
|
190 |
-
|
191 |
-
latest_data["update_time"]
|
192 |
-
)
|
193 |
-
except Exception as e:
|
194 |
-
# 出错,使用模拟数据
|
195 |
-
logger.error(f"Error getting data: {e}")
|
196 |
-
update_simulated_data()
|
197 |
-
return (
|
198 |
-
simulated_data["status"],
|
199 |
-
simulated_data["bed_temperature"],
|
200 |
-
simulated_data["nozzle_temperature"],
|
201 |
-
simulated_data["update_time"]
|
202 |
-
)
|
203 |
|
204 |
def send_print_parameters(nozzle_temp, bed_temp, print_speed, fan_speed):
|
205 |
"""发送打印参数到打印机"""
|
206 |
-
global SIMULATION_MODE
|
207 |
serial = DEFAULT_SERIAL
|
208 |
logger.info(f"Sending parameters to {serial}: nozzle={nozzle_temp}, bed={bed_temp}, speed={print_speed}, fan={fan_speed}")
|
209 |
-
|
210 |
-
# 如果在模拟模式下,更新模拟数据
|
211 |
-
if SIMULATION_MODE:
|
212 |
-
logger.info("Using simulation mode for parameter setting")
|
213 |
-
simulated_data["nozzle_temperature"] = str(nozzle_temp)
|
214 |
-
simulated_data["bed_temperature"] = str(bed_temp)
|
215 |
-
simulated_data["status"] = "Adjusting"
|
216 |
-
simulated_data["update_time"] = time.strftime("%Y-%m-%d %H:%M:%S")
|
217 |
-
return "Parameters set in simulation mode"
|
218 |
-
|
219 |
-
# 尝试通过MQTT发送参数
|
220 |
try:
|
221 |
params = {
|
222 |
'nozzle_temp': nozzle_temp,
|
@@ -227,7 +124,7 @@ def send_print_parameters(nozzle_temp, bed_temp, print_speed, fan_speed):
|
|
227 |
|
228 |
request_topic = f"bambu_a1_mini/request/{serial}"
|
229 |
|
230 |
-
if client
|
231 |
client.publish(request_topic, json.dumps({
|
232 |
'command': 'set_parameters',
|
233 |
'parameters': params
|
@@ -235,14 +132,8 @@ def send_print_parameters(nozzle_temp, bed_temp, print_speed, fan_speed):
|
|
235 |
logger.info("Parameters sent successfully")
|
236 |
return "Parameters sent successfully"
|
237 |
else:
|
238 |
-
|
239 |
-
|
240 |
-
SIMULATION_MODE = True
|
241 |
-
simulated_data["nozzle_temperature"] = str(nozzle_temp)
|
242 |
-
simulated_data["bed_temperature"] = str(bed_temp)
|
243 |
-
simulated_data["status"] = "Adjusting"
|
244 |
-
simulated_data["update_time"] = time.strftime("%Y-%m-%d %H:%M:%S")
|
245 |
-
return "Parameters set in simulation mode"
|
246 |
except Exception as e:
|
247 |
logger.error(f"Error sending parameters: {e}")
|
248 |
return f"Error sending parameters: {e}"
|
@@ -272,64 +163,32 @@ def capture_image():
|
|
272 |
"""捕获当前打印图像"""
|
273 |
logger.info("Capturing print image")
|
274 |
try:
|
275 |
-
#
|
276 |
-
|
277 |
-
|
278 |
-
|
279 |
-
|
280 |
-
image = np.ones((height, width, 3), dtype=np.uint8) * 240 # 浅灰色背景
|
281 |
-
|
282 |
-
# 添加一些随机的打印图案
|
283 |
-
for i in range(50):
|
284 |
-
x1, y1 = random.randint(0, width-100), random.randint(0, height-100)
|
285 |
-
x2, y2 = x1 + random.randint(50, 100), y1 + random.randint(50, 100)
|
286 |
-
color = (random.randint(50, 150), random.randint(50, 150), random.randint(50, 150))
|
287 |
-
thickness = random.randint(1, 5)
|
288 |
-
cv_image = np.array(image)
|
289 |
-
cv_image = cv2.rectangle(cv_image, (x1, y1), (x2, y2), color, thickness)
|
290 |
-
image = Image.fromarray(cv_image)
|
291 |
-
|
292 |
-
# 添加一些文本
|
293 |
-
draw = ImageDraw.Draw(image)
|
294 |
-
draw.text((10, 10), f"Simulated Print - {time.strftime('%H:%M:%S')}", fill=(0, 0, 0))
|
295 |
-
|
296 |
-
return image
|
297 |
except Exception as e:
|
298 |
logger.error(f"Error capturing image: {e}")
|
299 |
-
|
300 |
-
return Image.new('RGB', (300, 300), color=(200, 200, 200))
|
301 |
|
302 |
def health_check():
|
303 |
"""健康检查端点"""
|
304 |
status = {
|
305 |
"app": "running",
|
306 |
"time": time.strftime("%Y-%m-%d %H:%M:%S"),
|
307 |
-
"mqtt_connected": not
|
308 |
-
"
|
309 |
-
"latest_update": latest_data["update_time"] if not SIMULATION_MODE else simulated_data["update_time"]
|
310 |
}
|
311 |
logger.info(f"Health check: {status}")
|
312 |
return status
|
313 |
|
314 |
-
# 尝试初始化MQTT连接
|
315 |
-
try:
|
316 |
-
logger.info("Attempting to connect to MQTT broker")
|
317 |
-
mqtt_connected = create_client(HOST, PORT, USERNAME, PASSWORD)
|
318 |
-
if not mqtt_connected:
|
319 |
-
logger.warning("MQTT connection failed, starting in simulation mode")
|
320 |
-
SIMULATION_MODE = True
|
321 |
-
except Exception as e:
|
322 |
-
logger.error(f"Error initializing MQTT: {e}")
|
323 |
-
logger.warning("Starting in simulation mode")
|
324 |
-
SIMULATION_MODE = True
|
325 |
-
|
326 |
# 创建主界面
|
327 |
with gr.Blocks(title="Bambu A1 Mini Print Control") as demo:
|
328 |
gr.Markdown("# Bambu A1 Mini Print Control")
|
329 |
|
330 |
with gr.Row():
|
331 |
refresh_btn = gr.Button("Refresh Status")
|
332 |
-
simulation_status = gr.Markdown("**Mode: Simulation**" if SIMULATION_MODE else "**Mode: Connected to Printer**")
|
333 |
|
334 |
with gr.Row():
|
335 |
current_status = gr.Textbox(label="Printer Status", value="N/A", interactive=False)
|
@@ -351,15 +210,10 @@ with gr.Blocks(title="Bambu A1 Mini Print Control") as demo:
|
|
351 |
|
352 |
send_params_btn = gr.Button("Send Print Parameters")
|
353 |
|
354 |
-
#
|
355 |
-
def refresh_callback():
|
356 |
-
status, bed_temp, nozzle_temp, update_time = get_data()
|
357 |
-
mode_text = "**Mode: Simulation**" if SIMULATION_MODE else "**Mode: Connected to Printer**"
|
358 |
-
return [status, bed_temp, nozzle_temp, update_time, mode_text]
|
359 |
-
|
360 |
refresh_btn.click(
|
361 |
-
fn=
|
362 |
-
outputs=[current_status, current_bed_temp, current_nozzle_temp, last_update
|
363 |
)
|
364 |
|
365 |
capture_btn.click(
|
@@ -433,6 +287,13 @@ with gr.Blocks(title="Bambu A1 Mini Print Control") as demo:
|
|
433 |
if __name__ == "__main__":
|
434 |
logger.info("Starting Bambu A1 Mini Print Control application")
|
435 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
436 |
# 启动应用
|
437 |
demo.queue().launch(
|
438 |
show_error=True,
|
|
|
14 |
import cv2
|
15 |
from PIL import ImageDraw
|
16 |
|
17 |
+
|
18 |
+
# 设置日志记录
|
19 |
logging.basicConfig(
|
20 |
level=logging.INFO,
|
21 |
format='%(asctime)s - %(name)s - %(levelname)s - %(message)s',
|
|
|
26 |
)
|
27 |
logger = logging.getLogger("bambu-analysis")
|
28 |
|
29 |
+
HOST = "mqtt.bambulab.com" # 默认值
|
30 |
+
PORT = 8883 # 默认值
|
31 |
+
USERNAME = "bblp" # 默认值
|
32 |
+
PASSWORD = "bblp" # 默认值
|
|
|
33 |
DEFAULT_SERIAL = "0309CA471800852"
|
34 |
|
35 |
+
# 尝试从环境变量获取
|
36 |
+
if os.environ.get("host"):
|
37 |
+
HOST = os.environ.get("host")
|
38 |
+
if os.environ.get("port"):
|
39 |
+
PORT = int(os.environ.get("port"))
|
40 |
+
if os.environ.get("username"):
|
41 |
+
USERNAME = os.environ.get("username")
|
42 |
+
if os.environ.get("password"):
|
43 |
+
PASSWORD = os.environ.get("password")
|
44 |
+
|
45 |
+
logger.info(f"MQTT Configuration: HOST={HOST}, PORT={PORT}, USERNAME={USERNAME}")
|
46 |
|
|
|
47 |
latest_data = {
|
48 |
"bed_temperature": "N/A",
|
49 |
"nozzle_temperature": "N/A",
|
50 |
"status": "N/A",
|
51 |
+
"update_time": "Waiting for data...",
|
52 |
}
|
53 |
|
|
|
54 |
client = None
|
55 |
+
response_topic = None # Will be set dynamically
|
56 |
|
57 |
def create_client(host, port, username, password):
|
58 |
+
"""完全使用同事的创建客户端函数"""
|
59 |
+
global client
|
60 |
+
client = mqtt.Client()
|
61 |
+
client.username_pw_set(username, password)
|
62 |
+
client.tls_set(tls_version=mqtt.ssl.PROTOCOL_TLS)
|
63 |
+
client.on_connect = on_connect
|
64 |
+
client.on_message = on_message
|
65 |
+
client.connect(host, port)
|
66 |
+
client.loop_start()
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
67 |
|
68 |
def on_connect(client, userdata, flags, rc):
|
|
|
69 |
logger.info(f"Connected with result code {rc}")
|
|
|
|
|
|
|
|
|
|
|
|
|
70 |
|
71 |
def on_message(client, userdata, message):
|
|
|
72 |
global latest_data
|
73 |
logger.info("Received message")
|
74 |
try:
|
75 |
data = json.loads(message.payload)
|
|
|
|
|
76 |
latest_data["bed_temperature"] = data.get("bed_temperature", "N/A")
|
77 |
latest_data["nozzle_temperature"] = data.get("nozzle_temperature", "N/A")
|
78 |
latest_data["status"] = data.get("status", "N/A")
|
79 |
+
latest_data["update_time"] = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())
|
80 |
except Exception as e:
|
81 |
logger.error(f"Error parsing MQTT message: {e}")
|
82 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
83 |
def get_data(serial=DEFAULT_SERIAL):
|
84 |
+
global client, response_topic
|
85 |
+
|
86 |
+
if client is None:
|
87 |
+
create_client(HOST, PORT, USERNAME, PASSWORD)
|
88 |
+
|
89 |
+
request_topic = f"bambu_a1_mini/request/{serial}"
|
90 |
+
response_topic = f"bambu_a1_mini/response/{serial}"
|
91 |
|
92 |
+
logger.info(f"Subscribing to {response_topic}")
|
93 |
+
client.subscribe(response_topic)
|
94 |
|
95 |
+
# 发送请求获取数据
|
96 |
+
logger.info(f"Publishing request to {request_topic}")
|
97 |
+
client.publish(request_topic, json.dumps("HI"))
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
98 |
|
99 |
+
global latest_data
|
100 |
+
latest_data["bed_temperature"] = "N/A"
|
101 |
+
timeout = 10
|
102 |
+
while latest_data["bed_temperature"] == "N/A" and timeout > 0:
|
103 |
+
time.sleep(1)
|
104 |
+
timeout -= 1
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
105 |
|
106 |
+
return (
|
107 |
+
latest_data["status"],
|
108 |
+
latest_data["bed_temperature"],
|
109 |
+
latest_data["nozzle_temperature"],
|
110 |
+
latest_data["update_time"]
|
111 |
+
)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
112 |
|
113 |
def send_print_parameters(nozzle_temp, bed_temp, print_speed, fan_speed):
|
114 |
"""发送打印参数到打印机"""
|
|
|
115 |
serial = DEFAULT_SERIAL
|
116 |
logger.info(f"Sending parameters to {serial}: nozzle={nozzle_temp}, bed={bed_temp}, speed={print_speed}, fan={fan_speed}")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
117 |
try:
|
118 |
params = {
|
119 |
'nozzle_temp': nozzle_temp,
|
|
|
124 |
|
125 |
request_topic = f"bambu_a1_mini/request/{serial}"
|
126 |
|
127 |
+
if client:
|
128 |
client.publish(request_topic, json.dumps({
|
129 |
'command': 'set_parameters',
|
130 |
'parameters': params
|
|
|
132 |
logger.info("Parameters sent successfully")
|
133 |
return "Parameters sent successfully"
|
134 |
else:
|
135 |
+
logger.warning("MQTT not connected, parameters not sent")
|
136 |
+
return "MQTT not connected, parameters not sent"
|
|
|
|
|
|
|
|
|
|
|
|
|
137 |
except Exception as e:
|
138 |
logger.error(f"Error sending parameters: {e}")
|
139 |
return f"Error sending parameters: {e}"
|
|
|
163 |
"""捕获当前打印图像"""
|
164 |
logger.info("Capturing print image")
|
165 |
try:
|
166 |
+
# 这里应该是实际的相机捕获代码
|
167 |
+
# 目前返回一个占位图像
|
168 |
+
logger.warning("Using placeholder image (camera not implemented)")
|
169 |
+
placeholder = Image.new('RGB', (300, 300), color=(200, 200, 200))
|
170 |
+
return placeholder
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
171 |
except Exception as e:
|
172 |
logger.error(f"Error capturing image: {e}")
|
173 |
+
return None
|
|
|
174 |
|
175 |
def health_check():
|
176 |
"""健康检查端点"""
|
177 |
status = {
|
178 |
"app": "running",
|
179 |
"time": time.strftime("%Y-%m-%d %H:%M:%S"),
|
180 |
+
"mqtt_connected": client is not None,
|
181 |
+
"latest_update": latest_data["update_time"]
|
|
|
182 |
}
|
183 |
logger.info(f"Health check: {status}")
|
184 |
return status
|
185 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
186 |
# 创建主界面
|
187 |
with gr.Blocks(title="Bambu A1 Mini Print Control") as demo:
|
188 |
gr.Markdown("# Bambu A1 Mini Print Control")
|
189 |
|
190 |
with gr.Row():
|
191 |
refresh_btn = gr.Button("Refresh Status")
|
|
|
192 |
|
193 |
with gr.Row():
|
194 |
current_status = gr.Textbox(label="Printer Status", value="N/A", interactive=False)
|
|
|
210 |
|
211 |
send_params_btn = gr.Button("Send Print Parameters")
|
212 |
|
213 |
+
# 连接按钮
|
|
|
|
|
|
|
|
|
|
|
214 |
refresh_btn.click(
|
215 |
+
fn=get_data,
|
216 |
+
outputs=[current_status, current_bed_temp, current_nozzle_temp, last_update]
|
217 |
)
|
218 |
|
219 |
capture_btn.click(
|
|
|
287 |
if __name__ == "__main__":
|
288 |
logger.info("Starting Bambu A1 Mini Print Control application")
|
289 |
|
290 |
+
# 尝试初始化MQTT连接
|
291 |
+
try:
|
292 |
+
logger.info("Initializing MQTT client")
|
293 |
+
create_client(HOST, PORT, USERNAME, PASSWORD)
|
294 |
+
except Exception as e:
|
295 |
+
logger.error(f"Failed to initialize MQTT: {e}")
|
296 |
+
|
297 |
# 启动应用
|
298 |
demo.queue().launch(
|
299 |
show_error=True,
|