基於上述工廠手部動作檢測場景,我來為您推薦幾個合適的開源規則引擎框架,並提供詳細的使用示例。
推薦的開源規則引擎框架
1. Drools - 企業級首選
特點:功能全面、性能強大、文檔豐富,適合複雜的生產規則管理。
2. Easy Rules - 輕量級簡易框架
特點:學習曲線低、API簡潔,適合規則數量不多、邏輯相對簡單的場景。
3. RuleBook - 現代流式API
特點:使用流暢的鏈式API,代碼可讀性好,支持DSL配置。
Drools 使用示例
Maven依賴
<dependency>
<groupId>org.drools</groupId>
<artifactId>drools-engine</artifactId>
<version>7.74.0.Final</version>
</dependency>
1. 定義數據模型
// 手部動作事件
public class HandActionEvent {
private String actionType; // "GRAB", "TIGHTEN", "WELD"
private String tool; // "SCREWDRIVER", "MULTIMETER", "NONE"
private String component; // "CIRCUIT_BOARD", "CAPACITOR_C1"
private String handLocation;
private Duration duration;
private boolean inDangerZone;
private Timestamp timestamp;
// constructors, getters, setters
}
// 規則執行結果
public class ComplianceResult {
private boolean isCompliant;
private String violationReason;
private String suggestedAction;
private int severityLevel; // 1-5, 5為最嚴重
}
2. 定義Drools規則文件 (sop-rules.drl)
package com.factory.sop.rules
import com.factory.model.HandActionEvent
import com.factory.model.ComplianceResult
import java.time.Duration
// 規則1: 安全區域檢測
rule "Hand in Danger Zone - Immediate Stop"
when
$event: HandActionEvent(inDangerZone == true)
then
ComplianceResult result = new ComplianceResult();
result.setCompliant(false);
result.setViolationReason("手部進入危險區域");
result.setSuggestedAction("立即停止作業並撤離");
result.setSeverityLevel(5);
insert(result);
end
// 規則2: 焊接前的電容檢測規則
rule "Capacitor Welding Pre-check"
when
$event: HandActionEvent(actionType == "WELD",
component == "CAPACITOR_C1",
$prevAction: HandActionEvent(
actionType == "TEST_WITH_MULTIMETER",
component == "CAPACITOR_C1",
this before[0s, 2s] $event
))
then
// 如果找到前序的檢測動作,則合規
System.out.println("電容焊接前檢測合規");
end
rule "Capacitor Welding Without Test - Violation"
when
$event: HandActionEvent(actionType == "WELD",
component == "CAPACITOR_C1")
not exists HandActionEvent(actionType == "TEST_WITH_MULTIMETER",
component == "CAPACITOR_C1",
this before[0s, 2s] $event)
then
ComplianceResult result = new ComplianceResult();
result.setCompliant(false);
result.setViolationReason("焊接電容C1前未進行極性及容值檢測");
result.setSuggestedAction("停止焊接,使用萬用表檢測電容");
result.setSeverityLevel(3);
insert(result);
end
// 規則3: 螺絲擰緊時間檢查
rule "Screw Tightening Duration Check"
when
$event: HandActionEvent(actionType == "TIGHTEN",
tool == "SCREWDRIVER",
duration < Duration.ofSeconds(3))
then
ComplianceResult result = new ComplianceResult();
result.setCompliant(false);
result.setViolationReason("螺絲擰緊時間不足3秒");
result.setSuggestedAction("重新擰緊並確保達到規定時間");
result.setSeverityLevel(2);
insert(result);
end
// 規則4: 防靜電手環檢查
rule "ESD Protection Check"
when
$event: HandActionEvent(actionType == "HANDLE_SENSITIVE",
tool == "NONE")
not exists HandActionEvent(actionType == "WEAR_ESD_BRACELET",
this before[0s, 10s] $event)
then
ComplianceResult result = new ComplianceResult();
result.setCompliant(false);
result.setViolationReason("操作精密部件時未佩戴防靜電手環");
result.setSuggestedAction("立即停止操作,佩戴防靜電裝備");
result.setSeverityLevel(4);
insert(result);
end
3. Java集成代碼
@Service
public class ProductionRuleEngine {
private KieContainer kieContainer;
@PostConstruct
public void initialize() {
KieServices ks = KieServices.Factory.get();
kieContainer = ks.getKieClasspathContainer();
}
public List<ComplianceResult> evaluateHandAction(HandActionEvent event) {
KieSession kieSession = kieContainer.newKieSession("sop-session");
List<ComplianceResult> results = new ArrayList<>();
// 設置回調收集結果
kieSession.setGlobal("results", results);
// 插入事實並觸發規則
kieSession.insert(event);
kieSession.fireAllRules();
kieSession.dispose();
return results;
}
// 批量評估多個事件(用於時序分析)
public List<ComplianceResult> evaluateActionSequence(List<HandActionEvent> events) {
KieSession kieSession = kieContainer.newKieSession("sop-session");
List<ComplianceResult> results = new ArrayList<>();
kieSession.setGlobal("results", results);
for (HandActionEvent event : events) {
kieSession.insert(event);
}
kieSession.fireAllRules();
kieSession.dispose();
return results;
}
}
4. 與DeepSeek的集成示例
@Service
public class HybridComplianceService {
@Autowired
private ProductionRuleEngine ruleEngine;
@Autowired
private DeepSeekClient deepSeekClient; // 自定義的DeepSeek API客户端
public ComplianceResult evaluateComplexScenario(List<HandActionEvent> events,
String sopDescription) {
// 第一步:先用規則引擎進行快速判斷
List<ComplianceResult> quickResults = ruleEngine.evaluateActionSequence(events);
// 如果有嚴重違規,立即返回
Optional<ComplianceResult> criticalViolation = quickResults.stream()
.filter(r -> r.getSeverityLevel() >= 4)
.findFirst();
if (criticalViolation.isPresent()) {
return criticalViolation.get();
}
// 第二步:對於複雜或不確定的情況,調用DeepSeek
if (requiresDeepSeekAnalysis(quickResults, events)) {
return invokeDeepSeekAnalysis(events, sopDescription);
}
// 第三步:如果都合規,返回成功結果
return new ComplianceResult(true, "所有操作符合規範", "繼續作業", 0);
}
private boolean requiresDeepSeekAnalysis(List<ComplianceResult> quickResults,
List<HandActionEvent> events) {
// 規則引擎無法確定的情況
return quickResults.isEmpty() && events.size() > 3;
}
private ComplianceResult invokeDeepSeekAnalysis(List<HandActionEvent> events,
String sopDescription) {
// 構建發送給DeepSeek的提示詞
String prompt = buildAnalysisPrompt(events, sopDescription);
// 調用DeepSeek API
String deepSeekResponse = deepSeekClient.analyzeCompliance(prompt);
// 解析DeepSeek的返回結果
return parseDeepSeekResponse(deepSeekResponse);
}
private String buildAnalysisPrompt(List<HandActionEvent> events, String sop) {
StringBuilder prompt = new StringBuilder();
prompt.append("作為生產線SOP專家,請分析以下操作序列:\n\n");
prompt.append("觀察到的動作序列:\n");
for (int i = 0; i < events.size(); i++) {
HandActionEvent event = events.get(i);
prompt.append(String.format("%d. %s: 工具=%s, 部件=%s, 位置=%s\n",
i + 1, event.getActionType(), event.getTool(),
event.getComponent(), event.getHandLocation()));
}
prompt.append("\n相關SOP規定:\n").append(sop);
prompt.append("\n請判斷是否合規,如不合規請説明具體違反的規定和建議措施。");
return prompt.toString();
}
}
Easy Rules 輕量級示例
Maven依賴
<dependency>
<groupId>org.jeasy</groupId>
<artifactId>easy-rules-core</artifactId>
<version>4.1.0</version>
</dependency>
規則定義
@Rule(name = "危險區域規則", description = "檢測手部是否進入危險區域")
public class DangerZoneRule {
@Condition
public boolean isInDangerZone(@Fact("event") HandActionEvent event) {
return event.isInDangerZone();
}
@Action
public void triggerAlarm(@Fact("event") HandActionEvent event) {
System.out.println("警報:手部進入危險區域!");
// 觸發聲光報警
AlarmSystem.triggerImmediateStop();
}
}
// 規則引擎使用
public class SimpleRuleEngine {
private RulesEngine rulesEngine;
private Rules rules;
public SimpleRuleEngine() {
rulesEngine = new DefaultRulesEngine();
rules = new Rules();
rules.register(new DangerZoneRule());
// 註冊其他規則...
}
public void evaluate(HandActionEvent event) {
Facts facts = new Facts();
facts.put("event", event);
rulesEngine.fire(rules, facts);
}
}
推薦總結
|
框架
|
適用場景
|
優點
|
缺點
|
|
Drools |
複雜生產線、規則數量多、需要規則版本管理
|
功能強大、性能優秀、有圖形化規則編輯器
|
學習曲線較陡、配置複雜
|
|
Easy Rules |
簡單場景、快速原型、規則數量少
|
簡單易用、輕量級、與Spring集成容易
|
不適合複雜規則流
|
|
RuleBook |
需要流暢API、規則可讀性要求高
|
DSL風格、代碼清晰
|
社區相對較小
|
建議:對於正式的工廠生產環境,推薦使用 Drools,因為它具有企業級的功能和穩定性。對於原型開發或規則較簡單的場景,可以從 Easy Rules 開始。
這樣的架構既能處理大量實時的高速規則判斷,又能在遇到複雜情況時調用DeepSeek進行深度推理,實現了效率與智能的完美結合。