前端頁面
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Message Generator</title>
<link rel="stylesheet" href="{{ url_for('static', filename='css/style.css') }}">
</head>
<body>
<div class="container">
<h1>Message Generator</h1>
<form id="messageForm">
<div class="form-group">
<label for="controller">Controller Type</label>
<select id="controller" class="form-control">
<option value="LCE">LCE</option>
<option value="KCE">KCE</option>
<option value="GCE">GCE</option>
<option value="STEP">STEP</option>
<option value="ESC">ESC</option>
<option value="KSE">KSE</option>
<option value="DTU">DTU</option>
<option value="AE">AE</option>
<option value="SN">SN</option>
</select>
</div>
<div class="form-group">
<label for="msgType">Message Type</label>
<select id="msgType" class="form-control">
<option value="fault">Fault</option>
<option value="alarm">Alarm</option>
<option value="faultRecovered">Fault Recovered</option>
<option value="movementData">Movement Data</option>
<option value="serviceModeChange">Service Mode Change</option>
</select>
</div>
<button type="submit" class="btn btn-primary">Generate Message</button>
<button type="button" class="btn btn-secondary" id="clearButton">Clear Messages</button>
<button type="button" class="btn btn-danger" id="resetButton">Reset All</button>
</form>
<div id="response" class="response"></div>
<div id="messageBox" class="message-box"></div>
</div>
<!-- 複製成功提示框 -->
<div id="copyAlert" class="copy-alert" style="display: none;">Message copied to clipboard!</div>
<script src="{{ url_for('static', filename='js/main.js') }}"></script>
</body>
</html>
CSS 樣式
/* 通用樣式 */
body {
font-family: 'Arial', sans-serif; /* 設定全域性字型為 Arial,無襯線字型作為備用 */
background-color: #f5f5f5; /* 設定頁面背景顏色為淺灰色 */
margin: 0; /* 移除預設外邊距 */
padding: 0; /* 移除預設內邊距 */
}
.container {
max-width: 800px; /* 設定容器最大寬度為 800px,適配大螢幕 */
margin: 50px auto; /* 水平居中容器,並在頂部和底部留出 50px 的間距 */
padding: 30px; /* 容器內邊距為 30px */
background: #fff; /* 容器背景顏色為白色 */
border-radius: 10px; /* 圓角邊框,半徑為 10px */
box-shadow: 0 4px 10px rgba(0, 0, 0, 0.1); /* 新增陰影效果,提升層次感 */
}
h1 {
text-align: center; /* 標題居中對齊 */
color: #333; /* 標題文字顏色為深灰色 */
margin-bottom: 30px; /* 標題與下方內容的間距為 30px */
}
.form-group {
margin-bottom: 20px; /* 每個表單組之間的間距為 20px */
}
label {
display: block; /* 將標籤設定為塊級元素,獨佔一行 */
margin-bottom: 8px; /* 標籤與表單控制元件的間距為 8px */
font-weight: 600; /* 加粗字型 */
color: #555; /* 標籤文字顏色為中灰色 */
}
select.form-control {
width: 100%; /* 下拉選單寬度佔滿父容器 */
padding: 12px; /* 內邊距為 12px */
border: 1px solid #ddd; /* 邊框為淺灰色虛線 */
border-radius: 5px; /* 圓角邊框,半徑為 5px */
background: #fff; /* 背景顏色為白色 */
box-sizing: border-box; /* 確保內邊距和邊框不超出容器寬度 */
font-size: 16px; /* 字型大小為 16px */
}
/* 按鈕樣式 */
button.btn {
background-color: #007bff; /* 主按鈕顏色為藍色 */
color: #fff; /* 按鈕文字顏色為白色 */
border: none; /* 無邊框 */
padding: 12px 24px; /* 內邊距為 12px(垂直)和 24px(水平) */
border-radius: 5px; /* 圓角邊框,半徑為 5px */
cursor: pointer; /* 滑鼠懸停時顯示指標 */
font-size: 16px; /* 字型大小為 16px */
transition: background-color 0.3s ease; /* 新增平滑的背景色過渡效果 */
}
button.btn:hover {
background-color: #0056b3; /* 滑鼠懸停時,按鈕顏色變深 */
}
button.btn:active {
background-color: #003d80; /* 按鈕被點選時,顏色更深,增強互動感 */
}
/* 清除按鈕樣式 */
button.btn-secondary {
background-color: #28a745; /* 清除按鈕顏色為綠色 */
color: #fff; /* 按鈕文字顏色為白色 */
}
button.btn-secondary:hover {
background-color: #218838; /* 滑鼠懸停時,按鈕顏色變深 */
}
button.btn-secondary:active {
background-color: #1d742d; /* 按鈕被點選時,顏色更深 */
}
/* 重置按鈕樣式 */
button.btn-danger {
background-color: #17a2b8; /* 淺藍色 */
color: #fff;
}
button.btn-danger:hover {
background-color: #138496; /* 滑鼠懸停時的顏色 */
}
button.btn-danger:active {
background-color: #106b7d; /* 按鈕被點選時的顏色 */
}
/* 訊息響應區域 */
.response {
margin-top: 20px; /* 訊息響應區域與上方內容的間距為 20px */
padding: 15px; /* 內邊距為 15px */
background: #e9f5ff; /* 背景顏色為淺藍色 */
border-radius: 5px; /* 圓角邊框,半徑為 5px */
font-size: 14px; /* 字型大小為 14px */
color: #333; /* 文字顏色為深灰色 */
}
/* 訊息框樣式 */
.message-box {
margin-top: 20px; /* 訊息框與上方內容的間距為 20px */
padding: 15px; /* 內邊距為 15px */
background: #fff; /* 背景顏色為白色 */
border-radius: 5px; /* 圓角邊框,半徑為 5px */
box-shadow: 0 2px 5px rgba(0, 0, 0, 0.1); /* 新增陰影效果 */
font-size: 14px; /* 字型大小為 14px */
color: #555; /* 文字顏色為中灰色 */
max-height: 400px; /* 設定最大高度為 400px,防止內容溢位 */
overflow-y: auto; /* 內容超出時顯示垂直捲軸 */
}
/* 訊息內容樣式 */
.message-content pre {
background: #f8f9fa; /* 訊息內容背景顏色為淺灰色 */
padding: 10px; /* 內邊距為 10px */
border-radius: 5px; /* 圓角邊框,半徑為 5px */
font-family: 'Courier New', monospace; /* 字型為等寬字型,適合顯示程式碼 */
}
/* 提示框樣式 */
.alert {
position: fixed;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
background: #d4edda; /* 淺綠色背景 */
color: #155724; /* 深綠色文字 */
padding: 20px 40px;
text-align: center;
font-size: 18px;
font-weight: bold;
border-radius: 8px;
box-shadow: 0 4px 12px rgba(0, 0, 0, 0.2);
z-index: 1000;
opacity: 0;
transition: opacity 0.3s ease-in-out, transform 0.3s ease-in-out;
}
.alert.show {
opacity: 1;
transform: translate(-50%, -50%);
}
.alert.hide {
opacity: 0;
transform: translate(-50%, -50%);
}
.success {
background-color: #d4edda; /* 成功訊息背景顏色為淺綠色 */
border: 1px solid #c3e6cb; /* 邊框為綠色 */
color: #155724; /* 文字顏色為深綠色 */
}
.error {
background-color: #f8d7da; /* 錯誤訊息背景顏色為淺紅色 */
border: 1px solid #f5c6cb; /* 邊框為紅色 */
color: #721c24; /* 文字顏色為深紅色 */
}
/* 複製按鈕樣式 */
.copy-btn {
background-color: #007bff; /* 主按鈕顏色為藍色 */
color: #fff; /* 按鈕文字顏色為白色 */
border: none; /* 無邊框 */
padding: 10px 20px; /* 內邊距為 10px(垂直)和 20px(水平) */
border-radius: 5px; /* 圓角邊框,半徑為 5px */
cursor: pointer; /* 滑鼠懸停時顯示指標 */
font-size: 14px; /* 字型大小為 14px */
margin-top: 10px; /* 按鈕與上方內容的間距為 10px */
box-shadow: 0 2px 5px rgba(0, 123, 255, 0.3); /* 新增陰影效果 */
transition: background-color 0.3s ease, box-shadow 0.3s ease; /* 新增平滑的過渡效果 */
}
.copy-btn:hover {
background-color: #0056b3; /* 滑鼠懸停時,按鈕顏色變深 */
box-shadow: 0 4px 10px rgba(0, 123, 255, 0.5); /* 滑鼠懸停時,陰影效果更明顯 */
}
.copy-btn:active {
background-color: #004085; /* 按鈕被點選時,顏色更深 */
box-shadow: 0 2px 5px rgba(0, 123, 255, 0.3); /* 恢復陰影 */
transform: translateY(1px); /* 按鈕被點選時,輕微下沉效果 */
}
/* 複製成功提示框樣式 */
.copy-alert {
position: fixed;
bottom: 0; /* 如果在底部 */
/* top: 0; 如果在頂部 */
left: 0;
width: 100%;
background: #d4edda; /* 淺綠色背景 */
color: #155724; /* 深綠色文字 */
padding: 15px 0;
text-align: center;
font-size: 16px;
font-weight: bold;
box-shadow: 0 -2px 5px rgba(0, 0, 0, 0.1); /* 頂部陰影 */
z-index: 1000;
opacity: 0;
transition: opacity 0.3s ease-in-out, transform 0.3s ease-in-out;
}
.copy-alert.show {
opacity: 1;
transform: translateY(0);
}
.copy-alert.hide {
opacity: 0;
transform: translateY(100%);
}
/* 捲軸樣式 */
.message-box::-webkit-scrollbar {
width: 8px; /* 設定捲軸寬度為 8px */
}
.message-box::-webkit-scrollbar-track {
background: #f8f9fa; /* 捲軸軌道顏色為淺灰色 */
border-radius: 4px; /* 捲軸軌道圓角,半徑為 4px */
}
.message-box::-webkit-scrollbar-thumb {
background: #007bff; /* 捲軸滑塊顏色為藍色 */
border-radius: 4px; /* 捲軸滑塊圓角,半徑為 4px */
}
.message-box::-webkit-scrollbar-thumb:hover {
background: #0056b3; /* 捲軸滑塊懸停時顏色變深 */
}
JS 指令碼
document.getElementById('messageForm').addEventListener('submit', async (e) => {
e.preventDefault();
const controller = document.getElementById('controller').value;
const msgType = document.getElementById('msgType').value;
document.getElementById('messageBox').innerHTML = '';
document.getElementById('response').innerHTML = '';
if (!controller || !msgType) {
// 顯示固定的錯誤提示框
const errorAlert = document.createElement('div');
errorAlert.className = 'alert error';
errorAlert.innerHTML = `
<strong>Error:</strong> Please select both Controller Type and Message Type.
`;
document.body.appendChild(errorAlert);
errorAlert.classList.add('show');
// 3秒後自動清除提示
setTimeout(() => {
errorAlert.classList.remove('show');
setTimeout(() => {
errorAlert.remove();
}, 300); // 等待動畫完成
}, 3000);
return;
}
try {
const response = await fetch('/get_template', {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({ controller, msgType })
});
const data = await response.json();
if (data.status === 'success') {
// 渲染訊息內容和複製按鈕
document.getElementById('messageBox').innerHTML = `
<div class="message-content">
<pre>${JSON.stringify(data.message, null, 2)}</pre>
</div>
<button class="btn copy-btn">Copy Message</button>
`;
// 顯示動態生成成功的提示資訊
const responseAlert = document.createElement('div');
responseAlert.className = 'alert success';
responseAlert.innerHTML = `
<strong>Success:</strong> Message generated successfully!
`;
document.body.appendChild(responseAlert);
responseAlert.classList.add('show');
// 繫結複製按鈕事件監聽器
const copyBtn = document.querySelector('.copy-btn');
if (copyBtn) {
copyBtn.addEventListener('click', async () => {
const messageContent = document.querySelector('.message-content pre')?.textContent;
if (!messageContent) {
alert('No message content to copy. Please generate a message first.');
return;
}
try {
// 檢查是否支援 Clipboard API
if (!navigator.clipboard) {
console.warn('Your browser does not support async clipboard API. Fallback to execCommand.');
// 使用傳統複製方法
const tempTextArea = document.createElement('textarea');
tempTextArea.value = messageContent;
document.body.appendChild(tempTextArea);
tempTextArea.select();
document.execCommand('copy');
document.body.removeChild(tempTextArea);
} else {
await navigator.clipboard.writeText(messageContent);
}
// 顯示固定的複製成功提示框
const copyAlert = document.getElementById('copyAlert');
if (copyAlert) {
copyAlert.style.display = 'block'; // 確保元素可見
copyAlert.classList.add('show'); // 新增顯示類
// 3秒後自動移除提示框
setTimeout(() => {
copyAlert.classList.remove('show'); // 移除顯示類
setTimeout(() => {
copyAlert.style.display = 'none'; // 隱藏元素
}, 300); // 等待動畫完成
}, 3000);
} else {
console.error('copyAlert element not found in the DOM.');
}
} catch (err) {
console.error('Failed to copy message:', err);
alert('Failed to copy message. Please try again.');
}
});
}
// 3秒後自動清除生成成功提示
setTimeout(() => {
responseAlert.classList.remove('show');
setTimeout(() => {
responseAlert.remove();
}, 300); // 等待動畫完成
}, 3000);
} else if (data.status === 'error') {
// 顯示後端返回的錯誤資訊
const errorAlert = document.createElement('div');
errorAlert.className = 'alert error';
errorAlert.innerHTML = `
<strong>Error:</strong> ${data.message || 'Unable to generate message. Please try again.'}
`;
document.body.appendChild(errorAlert);
errorAlert.classList.add('show');
// 3秒後自動清除提示
setTimeout(() => {
errorAlert.classList.remove('show');
setTimeout(() => {
errorAlert.remove();
}, 300); // 等待動畫完成
}, 3000);
} else {
// 顯示通用錯誤提示
const errorAlert = document.createElement('div');
errorAlert.className = 'alert error';
errorAlert.innerHTML = `
<strong>Error:</strong> Unable to generate message. Please try again.
`;
document.body.appendChild(errorAlert);
errorAlert.classList.add('show');
// 3秒後自動清除提示
setTimeout(() => {
errorAlert.classList.remove('show');
setTimeout(() => {
errorAlert.remove();
}, 300); // 等待動畫完成
}, 3000);
}
} catch (error) {
console.error('Error:', error);
// 顯示通用錯誤提示
const errorAlert = document.createElement('div');
errorAlert.className = 'alert error';
errorAlert.innerHTML = `
<strong>Error:</strong> Unable to generate message. Please try again.
`;
document.body.appendChild(errorAlert);
errorAlert.classList.add('show');
// 3秒後自動清除提示
setTimeout(() => {
errorAlert.classList.remove('show');
setTimeout(() => {
errorAlert.remove();
}, 300); // 等待動畫完成
}, 3000);
}
// 頁面滾動到生成訊息區域
document.getElementById('messageBox').scrollIntoView({ behavior: 'smooth' });
});
// 清除按鈕功能
document.getElementById('clearButton').addEventListener('click', () => {
// 僅清空訊息框和響應區域
document.getElementById('messageBox').innerHTML = '';
document.getElementById('response').innerHTML = '';
// 顯示清除成功的提示資訊
const responseAlert = document.createElement('div');
responseAlert.className = 'alert success';
responseAlert.innerHTML = `
<strong>Success:</strong> Messages cleared successfully!
`;
document.body.appendChild(responseAlert);
responseAlert.classList.add('show');
// 3秒後自動清除提示
setTimeout(() => {
responseAlert.classList.remove('show');
setTimeout(() => {
responseAlert.remove();
}, 300); // 等待動畫完成
}, 3000);
});
// 重置按鈕功能
document.getElementById('resetButton').addEventListener('click', () => {
// 清空所有內容,包括下拉選項
document.getElementById('controller').value = '';
document.getElementById('msgType').value = '';
document.getElementById('messageBox').innerHTML = '';
document.getElementById('response').innerHTML = '';
// 顯示重置成功的提示資訊
const responseAlert = document.createElement('div');
responseAlert.className = 'alert success';
responseAlert.innerHTML = `
<strong>Success:</strong> All fields reset successfully!
`;
document.body.appendChild(responseAlert);
responseAlert.classList.add('show');
// 3秒後自動清除提示
setTimeout(() => {
responseAlert.classList.remove('show');
setTimeout(() => {
responseAlert.remove();
}, 300); // 等待動畫完成
}, 3000);
});
獲取訊息模板資料
#!/usr/bin/env python3
# -*- coding:utf-8 -*-
import os
import json
import uuid
import datetime
import random
import copy
import time, random, queue
from collections import OrderedDict
from threading import Thread
import ast
# 1.建立Kafka訊息mock服務類
class KafkaMsgMock:
def __init__(self):
'''
類初始化
'''
self.template = self.loadTemplate()
self.equipmentNumber = self.loadEquipmentNumber()
self.faultCode = self.loadFaultCode()
print('Load resources ...')
def loadTemplate(self):
'''
讀取模板檔案,為快速處理,所有模板均載入到記憶體
'''
dict_template = dict()
for i in os.listdir('./MsgTamplate/Kafka'):
if len(i) > 7: continue;
print(f'Load resource for {i}')
with open(os.path.abspath(os.path.dirname(i)) + '/MsgTamplate/Kafka/' + i, 'r', encoding='utf-8') as f:
file_content = f.read().replace("\\n", "").replace("\\t", "").replace(" ", "")
# print(f"Debug: File content for {i}: {file_content}") # Debugging line
dict_template.update({i: json.loads(file_content)})
return dict_template
def loadEquipmentNumber(self):
'''
讀取ken檔案,為快速處理,所有模板均載入到記憶體
'''
dict_template = dict()
with open(os.path.abspath(os.path.dirname('./')) + '/MsgTamplate/EQUIPMETN', 'r', encoding='utf-8') as f:
dict_template.update(
{'EQUIPMETN': json.loads(f.read().replace("\\n", "").replace("\\t", "").replace(" ", ""))})
return dict_template
def loadFaultCode(self):
'''
讀取fault code檔案,為快速處理,所有模板均載入到記憶體
'''
dict_template = dict()
with open(os.path.abspath(os.path.dirname('./')) + '/MsgTamplate/FAULTCODE', 'r', encoding='utf-8') as f:
dict_template.update(
{'FAULTCODE': json.loads(f.read().replace("\\n", "").replace("\\t", "").replace(" ", ""))})
return dict_template
def utcTime(self):
'''
make utc time for timestemp
'''
a = datetime.datetime.utcnow()
# 2020-11-06T09:10:36.000Z
# return (str(a.year) + '-' + str(a.month).zfill(2) + '-' + str(a.day).zfill(2) + 'T' + str(a.hour).zfill(
# 2) + ':' + str(a.minute).zfill(2) + ':' + str(a.second).zfill(2) + '.' + '%03dZ' % (int(a.microsecond / 1000)))
return datetime.datetime.utcnow().isoformat()[0:23] + 'Z'
def uuid(self):
'''
make uuid for timestemp
'''
return str(uuid.uuid4())
def comon_msg(self, controller='LCE', msgType='random', count=1):
'''
generate lce/gce/step/esc message
LCE is default
'''
# 讀取LCE模板
data = self.template[controller]
# 讀取裝置編號列表
equipmentNumbers = self.equipmentNumber['EQUIPMETN']
# 讀取fault code列表
faultCodes = self.faultCode['FAULTCODE']
# list容器
msages = list()
idx = 0
while idx < count:
idx += 1
# 隨機裝置號碼
equipmentNumber = str(random.choice(equipmentNumbers[controller]))
# 隨機fault code
faultCode = str(random.choice(faultCodes[controller]))
# 隨機訊息型別
if msgType == 'random':
# 隨機訊息模板
msgtype = random.choice(sorted(data.keys()))
content = data[msgtype].copy()
# alarm訊息
elif msgType == 'alarm':
content = data['alarmTamplate'].copy()
# fault 訊息
elif msgType == 'fault':
content = data['faultTamplate'].copy()
# fault recover訊息
elif msgType == 'faultRecovered':
content = data['faultRecoveredTamplate'].copy()
# service mode change訊息
elif msgType == 'serviceModeChange':
content = data['serviceModeChangeTamplate'].copy()
# movment data訊息
elif msgType == 'movementData':
content = data['movementDataTamplate'].copy()
# routine call
elif msgType == 'usagedata':
content = data['usagedataTamplate'].copy()
# button
elif msgType == 'button':
content = data['buttonTamplate'].copy()
# door
elif msgType == 'door':
content = data['doorTamplate'].copy()
# real time status
elif msgType == 'realtimestatus':
content = data['realtimestatusTamplate'].copy()
# real time status
elif msgType == 'serviceorderv2':
content = data['serviceorderv2Tamplate'].copy()
# edge
elif msgType == 'edge':
content = data['edgeTamplate'].copy()
# upperpitsensor
elif msgType == 'upperpitsensor':
content = data['upperpitsensorTamplate'].copy()
# upperpitnoise
elif msgType == 'upperpitnoise':
content = data['upperpitnoiseTamplate'].copy()
# lowerpitsensor
elif msgType == 'lowerpitsensor':
content = data['lowerpitsensorTamplate'].copy()
# lowerpitnoise
elif msgType == 'lowerpitnoise':
content = data['lowerpitnoiseTamplate'].copy()
# movementv2
elif msgType == 'movementv2':
content = data['movementv2Tamplate'].copy()
else:
print(f'未定義的訊息型別 - {msgType}')
# 合成訊息
if content.get('EquipmentNumber'):
content['EquipmentNumber'] = equipmentNumber
if content.get('Param', {}).get('UUID'):
content['Param']['UUID'] = self.uuid()
if content.get('Param', {}).get('FaultCode'):
content['Param']['FaultCode'] = faultCode
if content.get('Param', {}).get('Timestamp'):
content['Param']['Timestamp'] = self.utcTime()
if content.get('value', {}).get('Timestamp'):
content['value']['Timestamp'] = self.utcTime()
if content.get('value', {}).get('Param', {}).get('Timestamp'):
content['value']['Param']['Timestamp'] = self.utcTime()
# topic = content.get('topic')
# msages.append((topic, copy.deepcopy(content)))
# 儲存最新的訊息
msg = content
return msg
def kce_msg(self, msgType='random', count=1):
'''
generate kce message
'''
# 讀取LCE模板
data = self.template['KCE']
# 讀取裝置編號列表
equipmentNumbers = self.equipmentNumber['EQUIPMETN']
# 讀取fault code列表
faultCodes = self.faultCode['FAULTCODE']
# list容器
msages = list()
idx = 0
while idx < count:
idx += 1
# 隨機裝置號碼
equipmentNumber = str(random.choice(equipmentNumbers['KCE']))
# 隨機fault code
faultCode = str(random.choice(faultCodes['KCE']))
# 隨機訊息型別
if msgType == 'random':
# 隨機訊息模板
msgtype = random.choice(sorted(data.keys()))
content = data[msgtype].copy()
# alarm訊息
elif msgType == 'alarm':
content = data['alarmTamplate'].copy()
# fault 訊息
elif msgType == 'fault':
content = data['faultTamplate'].copy()
# fault recover訊息
elif msgType == 'faultRecovered':
content = data['faultRecoveredTamplate'].copy()
# movment data訊息
elif msgType == 'movementData':
content = data['movementDataTamplate'].copy()
# service mode change訊息
elif msgType == 'serviceModeChange':
content = data['serviceModeChangeTamplate'].copy()
# routine call
elif msgType == 'usagedata':
content = data['usagedataTamplate'].copy()
# real time status
elif msgType == 'realtimestatus':
content = data['realtimestatusTamplate'].copy()
# edge
elif msgType == 'edge':
content = data['edgeTamplate'].copy()
else:
print(f'未定義的訊息型別 - {msgType}')
# 合成訊息
if content.get('EquipmentNumber'):
content['EquipmentNumber'] = equipmentNumber
if content.get('equipment'):
content['equipment'] = equipmentNumber
if content.get('Param', {}).get('UUID'):
content['Param']['UUID'] = self.uuid()
if content.get('Param', {}).get('FaultCode'):
content['Param']['FaultCode'] = faultCode
'''
if content.get('Param',{}).get('Timestamp'):
content['Param']['Timestamp'] = self.utcTime()
if content.get('startTime'):
content['startTime'] = self.utcTime()
if content.get('endTime'):
content['endTime'] = self.utcTime()
'''
topic = content.get('topic')
msages.append((topic, copy.deepcopy(content)))
return msages
def kcecpuc_msg(self, msgType='random', count=1):
'''
generate kcecpuc message
'''
# 讀取LCE模板
data = self.template['KCECPUC']
# 讀取裝置編號列表
equipmentNumbers = self.equipmentNumber['EQUIPMETN']
# 讀取fault code列表
faultCodes = self.faultCode['FAULTCODE']
# list容器
msages = list()
idx = 0
while idx < count:
idx += 1
# 隨機裝置號碼
equipmentNumber = str(random.choice(equipmentNumbers['KCECPUC']))
# 隨機fault code
faultCode = str(random.choice(faultCodes['KCECPUC']))
# 隨機訊息型別
if msgType == 'random':
# 隨機訊息模板
msgtype = random.choice(sorted(data.keys()))
content = data[msgtype].copy()
# alarm訊息
elif msgType == 'alarm':
content = data['alarmTamplate'].copy()
# kcecpucMainfault
elif msgType == 'kcecpucMainfault':
content = data['kcecpucMainfaultTamplate'].copy()
# kcecpucMainfaultRecovered
elif msgType == 'kcecpucMainfaultRecovered':
content = data['kcecpucMainfaultRecoveredTamplate'].copy()
# fault 訊息
elif msgType == 'faultGcd':
content = data['faultGcdTamplate'].copy()
# fault recover訊息
elif msgType == 'faultGcdRecovered':
content = data['faultGcdRecoveredTamplate'].copy()
# fault 訊息
elif msgType == 'faultGw':
content = data['faultGwTamplate'].copy()
# fault recover訊息
elif msgType == 'faultGwRecovered':
content = data['faultGwRecoveredTamplate'].copy()
# movement data訊息
elif msgType == 'movementData':
content = data['movementDataTamplate'].copy()
# routine call
elif msgType == 'usagedata':
content = data['usagedataTamplate'].copy()
# button
elif msgType == 'button':
content = data['buttonTamplate'].copy()
# door
elif msgType == 'door':
content = data['doorTamplate'].copy()
# real time status
elif msgType == 'realtimestatus':
content = data['realtimestatusTamplate'].copy()
# movement data訊息
elif msgType == 'ckpicapabilities':
content = data['ckpicapabilitiesTamplate'].copy()
# routine call
elif msgType == 'ckpidailystatistics':
content = data['ckpidailystatisticsTamplate'].copy()
# button
elif msgType == 'noservicepredict':
content = data['noservicepredictTamplate'].copy()
# door
elif msgType == 'toolconnectivity':
content = data['toolconnectivityTamplate'].copy()
# mode maintenance change
elif msgType == 'modemaintenancechange':
content = data['modemaintenancechangeTamplate'].copy()
else:
print(f'未定義的訊息型別 - {msgType}')
# 合成訊息
if content.get('value', {}).get('equipment'):
content['value']['equipment'] = equipmentNumber
elif content.get('value', {}).get('eq'):
content['value']['eq'] = equipmentNumber
elif content.get('eq'):
content['eq'] = equipmentNumber
if content.get('Param', {}).get('UID'):
content['value']['UID'] = self.uuid().upper().replace('-', '')
if content.get('code'):
content['code'] = faultCode
'''
if content.get('Timestamp'):
content['Timestamp'] = self.utcTime()
if content.get('startTime'):
content['startTime'] = self.utcTime()
if content.get('endTime'):
content['endTime'] = self.utcTime()
'''
topic = content.get('topic')
msages.append((topic, copy.deepcopy(content)))
return msages
# if __name__ == '__main__':
# wss = KafkaMsgMock()
# start = time.time()
# msg = wss.comon_msg( controller = 'LCE', msgType = 'fault',count = 1 )
# print(msg)
# print(time.time() -start)
# while msg:
# #print(msg.pop())
# pass
flask 服務
from flask import Flask, request, jsonify, render_template
from DataMock import KafkaMsgMock
app = Flask(__name__)
kafka_mock = KafkaMsgMock()
@app.route('/')
def index():
return render_template('index.html')
@app.route('/get_template', methods=['POST'])
def get_template():
data = request.json
controller = data.get('controller', 'LCE')
msgType = data.get('msgType', 'fault')
# try:
message = kafka_mock.comon_msg(controller=controller, msgType=msgType)
if message:
return jsonify({"status": "success", "message": message})
else:
return jsonify({"status": "error", "message": "Message template not found"}), 500
# except Exception as e:
# return jsonify({"status": "error", "message": str(e)}), 500
if __name__ == '__main__':
app.run(host='0.0.0.0', port=5000, debug=True)
最終效果圖
如果覺得我的文章對您有用,請隨意打賞。您的支援將鼓勵我繼續創作!
打賞支援
暫無回覆。