SYSTEMSTATE DUMPs: An example of how to take and upload them [ID 125568.1]

Applies to:

Enterprise Manager for Oracle Database - Version: 8.1.7.4 and later [Release: and later ]
Oracle Server - Enterprise Edition - Version: 6.0.0.0 and later [Release: 6.0 and later]
Oracle Database Configuration Assistant - Version: 8.1.7 and later [Release: 8.1.7 and later]
Information in this document applies to any platform.

Purpose

To provide step by step instructions for taking system state dumps to assist database hanging/locking issues and to further provide instructions for
delivering the output for examination

Scope and Application

scope

SYSTEMSTATE DUMPs: An example of how to take and upload them

1) Get the process/procedure/query/command/database hung

2) Start SQLPLUS and connect as SYSDBA or SYSOPER

Prior to 11g

ALTER SESSION SET EVENTS 'IMMEDIATE TRACE NAME SYSTEMSTATE LEVEL 266';

11g and later

ALTER SESSION SET EVENTS 'IMMEDIATE TRACE NAME SYSTEMSTATE LEVEL 258';


If you cannot connect to the database to take the dump the following note may assist you in taking the dump

Note:121779.1 Taking Systemstate dumps when you cannot connect to Oracle

3) Exit SQLPLUS

4) Wait 5 minutes

5) Repeat steps 2-4 ... 2 more times

6) At this point you can do what is necessary to unhang the process

7) Locate the trace files (3) in the user_dump_dest

The user_dump_dest is defined in your parameter file or can be viewed by SHOW PARAMETER USER_DUMP_DEST

8) Upload the 3 trace files via My Oracle Support

NOTE :

If REAL APPLICATION CLUSTER (RAC) is being used ... it is strongly suggested that systemstates be done from each node ... after which ... they should be renamed to clearly indicate which node the dump originated from if it is not already clear by the file name

EXAMPLE:

sqlplus / as sysdba

SQL*Plus: Release 11.2.0.2.0 Production on Tue Oct 12 18:21:40 2010

Copyright (c) 1982, 2010, Oracle. All rights reserved.


Connected to:
Oracle Database 11g Enterprise Edition Release 11.2.0.2.0 - Production
With the Partitioning, OLAP, Data Mining and Real Application Testing options

SQL> ALTER SESSION SET EVENTS 'IMMEDIATE TRACE NAME SYSTEMSTATE LEVEL 266';

Session altered.

SQL> show parameter user_dump_dest

NAME TYPE VALUE
------------------------------------ ----------- ------------------------------
user_dump_dest string /ora/ora_11.2.0.2/diag/rdbms/ora11202/ora11202/trace

SQL> exit
Disconnected from Oracle Database 11g Enterprise Edition Release 11.2.0.2.0 - Production
With the Partitioning, OLAP, Data Mining and Real Application Testing options

> cd /ora/ora_11.2.0.2/diag/rdbms/ora11202/ora11202/trace

> ls -alt

-rw-r----- 1 oracle oinstall 1461273 Oct 12 18:19 ora11202_ora_3915.trc
-rw-r----- 1 oracle oinstall 202940 Oct 12 18:19 ora11202_ora_3915.trm
drwxr-x--- 3 oracle oinstall 20480 Oct 12 18:19 .
-rw-r----- 1 oracle oinstall 194243 Oct 12 18:19 alert_ora11202.log
drwxr-xr-x 2 oracle oinstall 4096 Oct 11 16:06 cdmp_20101011160628
drwxr-x--- 15 oracle oinstall 4096 Sep 14 15:45 ..

> more ora11202_ora_3915.trc

Trace file /ora/ora_11.2.0.2/diag/rdbms/ora11202/ora11202/trace/ora11202_ora_391
5.trc
Oracle Database 11g Enterprise Edition Release 11.2.0.2.0 - Production
With the Partitioning, OLAP, Data Mining and Real Application Testing options
ORACLE_HOME = /ora/ora_11.2.0.2/11202
System name: Linux
Node name: filnx10
Release: 2.6.9-42.0.3.EL
Version: #1 Mon Sep 25 17:14:19 EDT 2006
Machine: i686
Instance name: ora11202
Redo thread mounted by this instance: 1
Oracle process number: 20
Unix process pid: 3915, image: oracle@filnx10 (TNS V1-V3)


*** 2010-10-12 18:19:39.705
*** SESSION ID:(1.7) 2010-10-12 18:19:39.705
*** CLIENT ID:() 2010-10-12 18:19:39.705
*** SERVICE NAME:(SYS$USERS) 2010-10-12 18:19:39.705
*** MODULE NAME:(sqlplus@filnx10 (TNS V1-V3)) 2010-10-12 18:19:39.705
*** ACTION NAME:() 2010-10-12 18:19:39.705
*** ACTION NAME:() 2010-10-12 18:19:39.705

===================================================
SYSTEM STATE (level=10, with short stacks)
------------
System global information:
processes: base 0x3f3bac6c, size 150, cleanup 0x3f3caa8c
allocation: free sessions 0x3e87927c, free calls (nil)
control alloc errors: 0 (process), 0 (session), 0 (call)
PMON latch cleanup depth: 0
seconds since PMON's last scan for dead processes: 49
system statistics:
0 OS CPU Qt wait time
40 logons cumulative
20 logons current
5281 opened cursors cumulative
29 opened cursors current
13 user commits
0 user rollbacks
114 user calls
31001 recursive calls
904 recursive cpu usage
10 pinned cursors current
....

来自 “ ITPUB博客 ” ,链接:http://blog.itpub.net/22308399/viewspace-750809/,如需转载,请注明出处,否则将追究法律责任。

转载于:http://blog.itpub.net/22308399/viewspace-750809/

修改下面代码,使模型只在下面的roi区域使用模型识别ROI (x: 76,y: 120,w: 169, h: 104)。 并且在执行WAIT_FOR_LABEL1 = 3 # 等待标签1状态时最后发送stop。 等待uart收到十六进制的0x02再次运行下面的各个逻辑状态NORMAL = 0 # 正常检测模式 OBJECT_DETECTED = 1 # 物体检测处理中 SPECIAL_HANDLING = 2 # 特殊处理模式(标签08) WAIT_FOR_LABEL1 = 3 # 等待标签1状态。 import logging from maix import camera, display, image, nn, app, uart, time import requests import json import os import threading from datetime import datetime # 日志配置 logging.basicConfig( level=logging.INFO, format='%(asctime)s [%(levelname)s] %(message)s', handlers=[ logging.FileHandler("/root/operation.log"), logging.StreamHandler() ] ) logger = logging.getLogger("MAIX_PRO") # 状态定义 class SystemState: NORMAL = 0 # 正常检测模式 OBJECT_DETECTED = 1 # 物体检测处理中 SPECIAL_HANDLING = 2 # 特殊处理模式(标签08) WAIT_FOR_LABEL1 = 3 # 等待标签1状态 UPLOADING = 4 # 新增:上传处理中状态 # OCR模型加载 try: ocr = nn.PP_OCR(model="/root/models/pp_ocr.mud") logger.info("OCR model loaded") except Exception as e: logger.critical(f"OCR model load failed: {str(e)}") exit(1) # 保存目录 SAVE_DIR = "/boot/Pictures/" os.makedirs(SAVE_DIR, exist_ok=True) # 硬件初始化(使用OCR模型要求的分辨率) try: cam = camera.Camera(ocr.input_width(), ocr.input_height(), ocr.input_format()) logger.debug(f"Camera resolution: {cam.width()}x{cam.height()}") except RuntimeError as e: logger.critical(f"Camera init failed: {str(e)}") exit(1) disp = display.Display() # UART初始化 device = "/dev/ttyS0" serial0 = uart.UART(device, 115200) logger.info("UART initialized") # 登录获取token login_url = "http://111.230.114.23/api/user/login" headers_login = {'Content-Type': 'application/json'} login_data = {"userAccount": "lanyating", "userPassword": 12345678} json_data = json.dumps(login_data) try: login_response = requests.post(login_url, data=json_data, headers=headers_login) response_json = login_response.json() token = response_json.get('data') if token: logger.info(f"Login successful, token obtained: {token[:10]}...") else: logger.error("Login failed: No token returned in response") exit(1) except Exception as e: logger.critical(f"Login failed: {str(e)}") exit(1) class OperationController: def __init__(self): self.state = SystemState.NORMAL self.current_label = None self.last_detect_time = 0 self.upload_complete = False self.lock = threading.Lock() self.timers = [] # 初始发送forward命令 (0x02) self.send_uart("right") # 初始化 photo_url 和 data_url self.photo_url = "http://111.230.114.23/api/file/upload" self.data_url = "http://111.230.114.23/api/data/add" # 确保 token 在整个类中可用 self.token = token def send_uart(self, command): """发送带十六进制前缀的UART命令,命令为单字节""" # 如果当前处于上传状态,则不发送任何UART命令 if self.state == SystemState.UPLOADING: logger.warning(f"Blocked UART command during upload: {command}") return try: # 命令映射表 command_map = { "stop": 0x00, # 停止命令 "left": 0x01, # 左转命令 "right": 0x02 # 右转/前进命令 } # 获取命令对应的字节值 if command in command_map: cmd_byte = bytes([command_map[command]]) else: logger.error(f"Unknown command: {command}") return # 创建十六进制前缀字节序列 header = bytes.fromhex('ffff02') # 组合所有部分:header + cmd_byte data_to_send = header + cmd_byte # 发送完整的字节序列 serial0.write(data_to_send) logger.info(f"UART sent: {data_to_send.hex()} (hex)") except Exception as e: logger.error(f"UART send failed: {str(e)}") def save_and_upload(self, img, label): try: # 设置上传状态,阻止UART发送 self.state = SystemState.UPLOADING logger.info(f"Starting upload for label {label} (UART blocked)") # 生成文件名 timestamp = datetime.now().strftime("%Y%m%d_%H%M%S") filename = f"{SAVE_DIR}{label}_{timestamp}.jpg" # 保存图片 if img.save(filename, quality=90): logger.info(f"Image saved: {filename}") # 同步上传 with open(filename, 'rb') as file: files = { 'file': ('image.jpg', file, 'image/jpeg') } params = { 'biz': 'plant_picture', } headers = { "token": self.token } logger.info(f"Uploading {filename} with label {label}, Token: {self.token[:10]}...") response = requests.post( self.photo_url, files=files, headers=headers, params=params ) if response.json().get('code') == 0: logger.info(f"Upload success: {filename}, Response: {response.text}") return response.json().get('data') else: logger.warning(f"Upload failed: {response.text}") else: logger.error("Image save failed") except Exception as e: logger.error(f"Capture failed: {str(e)}") finally: # 恢复状态,允许UART发送 self.state = SystemState.NORMAL logger.info(f"Upload completed for label {label} (UART unblocked)") return None def save_data(self, data): try: # 设置上传状态,阻止UART发送 self.state = SystemState.UPLOADING logger.info("Starting data save (UART blocked)") params = [{ "deviceName": 1, "plantId": 1, "growthStage": "flowering", "healthStage": "healthy", "height": "5", "crownWidth": "5", "humidity": '', "ph": '', "dan": '', "lin": '', "jia": '', "photoUrl": data, "notes": "" }] headers = { "token": self.token } response = requests.post( self.data_url, headers=headers, json=params ) logger.info(f"Response: {data}") if response.json().get('code') == 0: logger.info(f"Data save success: {response.text}") else: logger.warning(f"Data save failed: {response.text}") except Exception as e: logger.error(f"Data upload error: {str(e)}") finally: # 恢复状态,允许UART发送 self.state = SystemState.NORMAL logger.info("Data save completed (UART unblocked)") def handle_detection(self, objs, img): with self.lock: current_time = time.time() # 状态机逻辑 if self.state == SystemState.NORMAL: for obj in objs: text = obj.char_str().strip() # 获取OCR识别结果并去除空格 logger.info(f"OCR detected text: {text}") # 处理01-07的情况 if text in ["01", "02", "03", "04", "05", "06", "07"]: num = int(text) # 转换为整数 logger.info(f"Label {num} detected via OCR") self.state = SystemState.OBJECT_DETECTED self.send_uart("stop") # 发送停止命令 (0x00) # 1秒后保存并上传 def delayed_save(): data = self.save_and_upload(img, num) if data: self.save_data(data) self.add_timer(1.0, delayed_save) # 2秒后发送前进命令 def delayed_forward(): self.send_uart("right") # 发送前进命令 (0x02) self.state = SystemState.NORMAL self.add_timer(2.0, delayed_forward) break # 处理一个有效结果后退出循环 # 处理08的情况 elif text == "08": logger.info("Special label 08 detected") self.state = SystemState.SPECIAL_HANDLING self.send_uart("stop") # 发送停止命令 (0x00) # 1秒后保存并上传 def delayed_save(): data = self.save_and_upload(img, 8) if data: self.save_data(data) self.send_uart("left") # 发送左转命令 (0x01) # 进入等待标签1状态 self.state = SystemState.WAIT_FOR_LABEL1 self.add_timer(1.0, delayed_save) break # 处理一个有效结果后退出循环 elif self.state == SystemState.SPECIAL_HANDLING: # 等待上传完成 pass elif self.state == SystemState.WAIT_FOR_LABEL1: for obj in objs: text = obj.char_str().strip() if text == "01": logger.info("Label1 after special handling") self.send_uart("stop") # 发送停止命令 (0x00) self.add_timer(1.0, lambda: self.send_uart("right")) # 发送前进命令 (0x02) self.state = SystemState.NORMAL break def add_timer(self, delay, callback): timer = threading.Timer(delay, callback) timer.start() self.timers.append(timer) def cleanup(self): for timer in self.timers: timer.cancel() logger.info("System cleanup completed") # 主控制实例 controller = OperationController() # 创建 Color 对象 red_color = image.Color(255, 0, 0) # 定义标准红色 # 主循环 try: while not app.need_exit(): try: img = cam.read() except Exception as e: logger.error(f"摄像头读取失败: {str(e)}") continue # 执行OCR识别 try: objs = ocr.detect(img) except Exception as e: logger.error(f"OCR识别失败: {str(e)}") disp.show(img) continue # 处理结果 if len(objs) > 0: controller.handle_detection(objs, img) # 显示OCR结果 for obj in objs: # 绘制检测框(四个点) points = obj.box.to_list() img.draw_keypoints( points, red_color, # 颜色 4, # 点大小 -1, # 连接所有点 1 # 线宽 ) # 绘制识别文本 img.draw_string( obj.box.x4, obj.box.y4, obj.char_str(), scale=0.5, color=red_color ) disp.show(img) except KeyboardInterrupt: logger.info("用户中断") except Exception as e: logger.critical(f"致命错误: {str(e)}") finally: controller.cleanup() logger.info("系统关闭")
07-13
修改下面代码,使模型只在下面的roi区域使用模型识别ROI (x: 76,y: 120,w: 169, h: 104)。 等待uart收到十六进制的0x02再次从下面代码的# 主循环。 import logging from maix import camera, display, image, nn, app, uart, time import requests import json import os import threading from datetime import datetime 日志配置 logging.basicConfig( level=logging.INFO, format=‘%(asctime)s [%(levelname)s] %(message)s’, handlers=[ logging.FileHandler(“/root/operation.log”), logging.StreamHandler() ] ) logger = logging.getLogger(“MAIX_PRO”) 状态定义 class SystemState: NORMAL = 0 # 正常检测模式 OBJECT_DETECTED = 1 # 物体检测处理中 SPECIAL_HANDLING = 2 # 特殊处理模式(标签08) WAIT_FOR_LABEL1 = 3 # 等待标签1状态 UPLOADING = 4 # 新增:上传处理中状态 OCR模型加载 try: ocr = nn.PP_OCR(model=“/root/models/pp_ocr.mud”) logger.info(“OCR model loaded”) except Exception as e: logger.critical(f"OCR model load failed: {str(e)}") exit(1) 保存目录 SAVE_DIR = “/boot/Pictures/” os.makedirs(SAVE_DIR, exist_ok=True) 硬件初始化(使用OCR模型要求的分辨率) try: cam = camera.Camera(ocr.input_width(), ocr.input_height(), ocr.input_format()) logger.debug(f"Camera resolution: {cam.width()}x{cam.height()}“) except RuntimeError as e: logger.critical(f"Camera init failed: {str(e)}”) exit(1) disp = display.Display() UART初始化 device = “/dev/ttyS0” serial0 = uart.UART(device, 115200) logger.info(“UART initialized”) 登录获取token login_url = “http://111.230.114.23/api/user/login” headers_login = {‘Content-Type’: ‘application/json’} login_data = {“userAccount”: “lanyating”, “userPassword”: 12345678} json_data = json.dumps(login_data) try: login_response = requests.post(login_url, data=json_data, headers=headers_login) response_json = login_response.json() token = response_json.get(‘data’) if token: logger.info(f"Login successful, token obtained: {token[:10]}…“) else: logger.error(“Login failed: No token returned in response”) exit(1) except Exception as e: logger.critical(f"Login failed: {str(e)}”) exit(1) class OperationController: def init(self): self.state = SystemState.NORMAL self.current_label = None self.last_detect_time = 0 self.upload_complete = False self.lock = threading.Lock() self.timers = [] # 初始发送forward命令 (0x02) self.send_uart(“right”) # 初始化 photo_url 和 data_url self.photo_url = “http://111.230.114.23/api/file/upload” self.data_url = “http://111.230.114.23/api/data/add” # 确保 token 在整个类中可用 self.token = token def send_uart(self, command): """发送带十六进制前缀的UART命令,命令为单字节""" # 如果当前处于上传状态,则不发送任何UART命令 if self.state == SystemState.UPLOADING: logger.warning(f"Blocked UART command during upload: {command}") return try: # 命令映射表 command_map = { "stop": 0x00, # 停止命令 "left": 0x01, # 左转命令 "right": 0x02 # 右转/前进命令 } # 获取命令对应的字节值 if command in command_map: cmd_byte = bytes([command_map[command]]) else: logger.error(f"Unknown command: {command}") return # 创建十六进制前缀字节序列 header = bytes.fromhex('ffff02') # 组合所有部分:header + cmd_byte data_to_send = header + cmd_byte # 发送完整的字节序列 serial0.write(data_to_send) logger.info(f"UART sent: {data_to_send.hex()} (hex)") except Exception as e: logger.error(f"UART send failed: {str(e)}") def save_and_upload(self, img, label): try: # 设置上传状态,阻止UART发送 self.state = SystemState.UPLOADING logger.info(f"Starting upload for label {label} (UART blocked)") # 生成文件名 timestamp = datetime.now().strftime("%Y%m%d_%H%M%S") filename = f"{SAVE_DIR}{label}_{timestamp}.jpg" # 保存图片 if img.save(filename, quality=90): logger.info(f"Image saved: {filename}") # 同步上传 with open(filename, 'rb') as file: files = { 'file': ('image.jpg', file, 'image/jpeg') } params = { 'biz': 'plant_picture', } headers = { "token": self.token } logger.info(f"Uploading {filename} with label {label}, Token: {self.token[:10]}...") response = requests.post( self.photo_url, files=files, headers=headers, params=params ) if response.json().get('code') == 0: logger.info(f"Upload success: {filename}, Response: {response.text}") return response.json().get('data') else: logger.warning(f"Upload failed: {response.text}") else: logger.error("Image save failed") except Exception as e: logger.error(f"Capture failed: {str(e)}") finally: # 恢复状态,允许UART发送 self.state = SystemState.NORMAL logger.info(f"Upload completed for label {label} (UART unblocked)") return None def save_data(self, data): try: # 设置上传状态,阻止UART发送 self.state = SystemState.UPLOADING logger.info("Starting data save (UART blocked)") params = [{ "deviceName": 1, "plantId": 1, "growthStage": "flowering", "healthStage": "healthy", "height": "5", "crownWidth": "5", "humidity": '', "ph": '', "dan": '', "lin": '', "jia": '', "photoUrl": data, "notes": "" }] headers = { "token": self.token } response = requests.post( self.data_url, headers=headers, json=params ) logger.info(f"Response: {data}") if response.json().get('code') == 0: logger.info(f"Data save success: {response.text}") else: logger.warning(f"Data save failed: {response.text}") except Exception as e: logger.error(f"Data upload error: {str(e)}") finally: # 恢复状态,允许UART发送 self.state = SystemState.NORMAL logger.info("Data save completed (UART unblocked)") def handle_detection(self, objs, img): with self.lock: current_time = time.time() # 状态机逻辑 if self.state == SystemState.NORMAL: for obj in objs: text = obj.char_str().strip() # 获取OCR识别结果并去除空格 logger.info(f"OCR detected text: {text}") # 处理01-07的情况 if text in ["01", "02", "03", "04", "05", "06", "07"]: num = int(text) # 转换为整数 logger.info(f"Label {num} detected via OCR") self.state = SystemState.OBJECT_DETECTED self.send_uart("stop") # 发送停止命令 (0x00) # 1秒后保存并上传 def delayed_save(): data = self.save_and_upload(img, num) if data: self.save_data(data) self.add_timer(1.0, delayed_save) # 2秒后发送前进命令 def delayed_forward(): self.send_uart("right") # 发送前进命令 (0x02) self.state = SystemState.NORMAL self.add_timer(2.0, delayed_forward) break # 处理一个有效结果后退出循环 # 处理08的情况 elif text == "08": logger.info("Special label 08 detected") self.state = SystemState.SPECIAL_HANDLING self.send_uart("stop") # 发送停止命令 (0x00) # 1秒后保存并上传 def delayed_save(): data = self.save_and_upload(img, 8) if data: self.save_data(data) self.send_uart("left") # 发送左转命令 (0x01) # 进入等待标签1状态 self.state = SystemState.WAIT_FOR_LABEL1 self.add_timer(1.0, delayed_save) break # 处理一个有效结果后退出循环 elif self.state == SystemState.SPECIAL_HANDLING: # 等待上传完成 pass elif self.state == SystemState.WAIT_FOR_LABEL1: for obj in objs: text = obj.char_str().strip() if text == "01": logger.info("Label1 after special handling") self.send_uart("stop") # 发送停止命令 (0x00) self.add_timer(1.0, lambda: self.send_uart("right")) # 发送前进命令 (0x02) self.state = SystemState.NORMAL break def add_timer(self, delay, callback): timer = threading.Timer(delay, callback) timer.start() self.timers.append(timer) def cleanup(self): for timer in self.timers: timer.cancel() logger.info("System cleanup completed") 主控制实例 controller = OperationController() 创建 Color 对象 red_color = image.Color(255, 0, 0) # 定义标准红色 主循环 try: while not app.need_exit(): try: img = cam.read() except Exception as e: logger.error(f"摄像头读取失败: {str(e)}") continue # 执行OCR识别 try: objs = ocr.detect(img) except Exception as e: logger.error(f"OCR识别失败: {str(e)}") disp.show(img) continue # 处理结果 if len(objs) > 0: controller.handle_detection(objs, img) # 显示OCR结果 for obj in objs: # 绘制检测框(四个点) points = obj.box.to_list() img.draw_keypoints( points, red_color, # 颜色 4, # 点大小 -1, # 连接所有点 1 # 线宽 ) # 绘制识别文本 img.draw_string( obj.box.x4, obj.box.y4, obj.char_str(), scale=0.5, color=red_color ) disp.show(img) except KeyboardInterrupt: logger.info(“用户中断”) except Exception as e: logger.critical(f"致命错误: {str(e)}") finally: controller.cleanup() logger.info(“系统关闭”)
07-13
[SAMPLE_COMM_ISP_Thread]-95: ISP Dev 0 running! 0 R:1257 B:3920 CT:2788 1 R:1588 B:2858 CT:3968 2 R:2169 B:1819 CT:7154 Golden 1588 1024 2858 wdrLEOnly:1 [SAMPLE_COMM_VO_StartChn]-351: u32Width:480, u32Height:640, u32Square:1 -- [I] [Maix Comm Protocol] exit... -- [I] [Maix Comm Protocol] exit success -- [I] [Maix Comm Protocol] UART /dev/serial0 ready to init 2025-07-11 15:21:45,777 [INFO] UART initialized 2025-07-11 15:21:45,904 [CRITICAL] Login failed: Expecting value: line 1 column 1 (char 0) maix multi-media driver released. ISP Vipipe(0) Free pa(0x8abdf000) va(0x0x3fde3a8000) program exit failed. exit code: 1. import logging from maix import camera, display, image, nn, app, uart, time import requests import json import os import threading from datetime import datetime # 日志配置 logging.basicConfig( level=logging.INFO, format='%(asctime)s [%(levelname)s] %(message)s', handlers=[ logging.FileHandler("/root/operation.log"), logging.StreamHandler() ] ) logger = logging.getLogger("MAIX_PRO") # 状态定义 class SystemState: NORMAL = 0 # 正常检测模式 OBJECT_DETECTED = 1 # 物体检测处理中 SPECIAL_HANDLING = 2# 特殊处理模式(标签19) WAIT_FOR_LABEL1 = 3 # 等待标签1状态 # 模型加载 try: model = "/root/models/pp_ocr.mud" ocr = nn.PP_OCR(model) logger.info("OCR model loaded") except Exception as e: logger.critical(f"Model load failed: {str(e)}") exit(1) # 保存目录 # SAVE_DIR = "/root/models/mymodel/" SAVE_DIR = "/boot/Pictures/" os.makedirs(SAVE_DIR, exist_ok=True) # 硬件初始化(调整为硬件支持的分辨率) try: cam = camera.Camera(width=1080, height=640) # 使用标准VGA分辨率 logger.debug(f"Camera resolution: {cam.width()}x{cam.height()}") except RuntimeError as e: logger.critical(f"Camera init failed: {str(e)}") exit(1) disp = display.Display() # UART初始化 device = "/dev/ttyS0" serial0 = uart.UART(device, 38400) logger.info("UART initialized") # 登录获取token login_url = "http://111.230.114.23/api/user/login" headers_login = {'Content-Type': 'application/json'} login_data = {"userAccount": "lanyating", "userPassword": 12345678} json_data = json.dumps(login_data) try: login_response = requests.post(login_url, data=json_data, headers=headers_login) response_json = login_response.json() token = response_json.get('data') if token: logger.info(f"Login successful, token obtained: {token[:10]}...") # 只显示部分token以保护隐私 else: logger.error(f"Login failed: No token returned in response") exit(1) except Exception as e: logger.critical(f"Login failed: {str(e)}") exit(1) def send_uart(data): try: serial0.write_str(data + "\n") logger.info(f"UART sent: {data}") except Exception as e: logger.error(f"UART send failed: {str(e)}") class OperationController: def __init__(self): self.state = SystemState.NORMAL self.current_label = None self.last_detect_time = 0 self.upload_complete = False self.lock = threading.Lock() self.timers = [] # 初始发送forward self.send_uart("forward") # 初始化 photo_url 和 data_url self.photo_url = "http://111.230.114.23/api/file/upload" self.data_url = "http://111.230.114.23/api/data/add" # 确保 token 在整个类中可用 self.token = token def send_uart(self, command): try: serial0.write_str(command + "\n") logger.info(f"UART sent: {command}") except Exception as e: logger.error(f"UART send failed: {str(e)}") def save_and_upload(self, img, label): try: # 生成文件名 timestamp = datetime.now().strftime("%Y%m%d_%H%M%S") filename = f"{SAVE_DIR}{label}_{timestamp}.jpg" # 保存图片 if img.save(filename, quality=90): logger.info(f"Image saved: {filename}") # 同步上传 with open(filename, 'rb') as file: files = { 'file': ('image.jpg', file, 'image/jpeg') } params = { 'biz': 'plant_picture', } headers = { "token": self.token } logger.info(f"Uploading {filename} with label {label}, Token: {self.token[:10]}...") response = requests.post( self.photo_url, files=files, headers=headers, params=params ) if response.json().get('code') == 0 : logger.info(f"Upload success: {filename}, Response: {response.text}") return response.json().get('data') else: logger.warning(f"Upload failed: {response.text}") else: logger.error("Image save failed") except Exception as e: logger.error(f"Capture failed: {str(e)}") return None def save_data(self, data): try: params = [{ "deviceName": 1, "plantId": 1, "growthStage": "flowering", "healthStage": "healthy", "height": "5", "crownWidth": "5", "humidity": '', "ph": '', "dan": '', "lin": '', "jia": '', "photoUrl": data, "notes": "" }] headers = { "token": self.token } response = requests.post( self.data_url, headers=headers, json=params ) logger.info(f"Response: {data}") if response.json().get('code') == 0 : logger.info(f"Data save success: {response.text}") else: logger.warning(f"Data save failed: {response.text}") except Exception as e: logger.error(f"Data upload error: {str(e)}") def handle_detection(self, objs, img): with self.lock: current_time = time.time() img=cam.read() objs = ocr.detect(img) # 状态机逻辑 if self.state == SystemState.NORMAL: for obj in objs: if obj.char_str() == 8: logger.info("Special label 19 detected") self.state = SystemState.SPECIAL_HANDLING self.send_uart("stop") # 1秒后保存并上传 def delayed_save(): print("开始上传") data = self.save_and_upload(img, 19) print("上传成功") if data: self.save_data(data) self.send_uart("back") self.add_timer(1.0, delayed_save) break elif 1 <= char_str() <= 7: logger.info(f"Label {obj.class_id} detected") self.state = SystemState.OBJECT_DETECTED self.send_uart("stop") # 1秒后保存并上传 def delayed_save(): print("开始上传") data = self.save_and_upload(img, obj.class_id) print("上传成功") if data: self.save_data(data) self.add_timer(1.0, delayed_save) # 2秒后发送forward def delayed_forward(): self.send_uart("forward") self.state = SystemState.NORMAL self.add_timer(2.0, delayed_forward) break elif self.state == SystemState.SPECIAL_HANDLING: # 等待上传完成 pass # 在同步上传的情况下不需要等待标志位 elif self.state == SystemState.WAIT_FOR_LABEL1: for obj in objs: if obj.class_id == 1: logger.info("Label1 after special handling") self.send_uart("stop") self.add_timer(1.0, lambda: self.send_uart("forward")) self.state = SystemState.NORMAL break def add_timer(self, delay, callback): timer = threading.Timer(delay, callback) timer.start() self.timers.append(timer) def cleanup(self): for timer in self.timers: timer.cancel() logger.info("System cleanup completed") # 主控制实例 controller = OperationController() # 创建 Color 对象 red_color = image.Color(255, 0, 0) # 定义标准红色 # 主循环 try: while not app.need_exit(): try: img = cam.read() except Exception as e: logger.error(f"摄像头读取失败: {str(e)}") continue # 执行检测 try: objs = detector.detect(img, conf_th=0.6) except Exception as e: logger.error(f"目标检测失败: {str(e)}") disp.show(img) continue # 处理结果 if len(objs) > 0: controller.handle_detection(objs, img) # 显示画面 for obj in objs: # 绘制检测框(使用位置参数) img.draw_rect( obj.x, obj.y, obj.w, obj.h, red_color, # 颜色参数位置 2 # 线宽参数位置 ) # 绘制标签文本 img.draw_string( obj.x, obj.y, f"{detector.labels[char_str()]} {obj.score:.2f}", scale=0.5, color=red_color ) disp.show(img) except KeyboardInterrupt: logger.info("用户中断") except Exception as e: logger.critical(f"致命错误: {str(e)}") finally: controller.cleanup() logger.info("系统关闭") 查找错误原因
07-12
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符  | 博主筛选后可见
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值