Sure! We can modify the Python GUI to start plotting temperatures only when a profile is started and to plot the selected temperature profile alongside the real-time temperatures. Below are the changes to implement this:
Modified Python GUI Code
-
TemperaturePlot Class:
- Add a method to plot the selected profile.
- Clear the plot when a profile is started.
-
MainWindow Class:
- Call the
clear_plot method when starting a profile.
- Plot the selected profile when starting a profile.
Here's the updated code:
import sys
import struct
import time
import threading
from datetime import datetime
from collections import deque
import serial
import serial.tools.list_ports
import numpy as np
from PyQt5.QtWidgets import *
from PyQt5.QtCore import *
from PyQt5.QtGui import *
import pyqtgraph as pg
# Protocol constants
START_BYTE = 0xAA
END_BYTE = 0x55
# Commands
CMD_GET_TEMP = 0x01
CMD_SET_PROFILE = 0x02
CMD_GET_PROFILE = 0x03
CMD_START_PROFILE = 0x04
CMD_STOP_PROFILE = 0x05
CMD_SET_PID = 0x06
CMD_GET_PID = 0x07
CMD_AUTOTUNE = 0x08
CMD_SET_MANUAL = 0x09
CMD_GET_STATUS = 0x0A
class ProfileSegment:
def __init__(self, target_temp=25, ramp_rate=1.0, soak_time=60):
self.target_temp = target_temp
self.ramp_rate = ramp_rate
self.soak_time = soak_time
class Profile:
def __init__(self, name="Profile"):
self.name = name
self.segments = []
class SerialWorker(QThread):
temperature_update = pyqtSignal(float, float, float)
connection_lost = pyqtSignal()
status_update = pyqtSignal(dict)
def __init__(self):
super().__init__()
self.serial_port = None
self.running = False
def connect_port(self, port, baud=115200):
try:
self.serial_port = serial.Serial(port, baud, timeout=1)
self.running = True
return True
except:
return False
def disconnect(self):
self.running = False
if self.serial_port:
self.serial_port.close()
def run(self):
while self.running:
try:
if self.serial_port and self.serial_port.is_open:
# Request temperature
self.send_command(CMD_GET_TEMP, b'')
response = self.read_response()
if response and response['cmd'] == CMD_GET_TEMP:
temps = struct.unpack('fff', response['data'])
self.temperature_update.emit(*temps)
# Request status
self.send_command(CMD_GET_STATUS, b'')
response = self.read_response()
if response and response['cmd'] == CMD_GET_STATUS:
status = {
'running': bool(response['data'][0]),
'segment': response['data'][1],
'setpoints': struct.unpack('BBB', response['data'][2:5])
}
self.status_update.emit(status)
time.sleep(0.5)
except:
self.connection_lost.emit()
self.running = False
def send_command(self, cmd, data):
if not self.serial_port or not self.serial_port.is_open:
return
packet = bytearray()
packet.append(START_BYTE)
packet.append(cmd)
packet.append(len(data))
packet.extend(data)
packet.append(END_BYTE)
self.serial_port.write(packet)
def read_response(self):
if not self.serial_port or not self.serial_port.is_open:
return None
# Read start byte
start = self.serial_port.read(1)
if not start or start[0] != START_BYTE:
return None
# Read command and length
cmd = self.serial_port.read(1)
length = self.serial_port.read(1)
if not cmd or not length:
return None
# Read data
data = self.serial_port.read(length[0])
# Read end byte
end = self.serial_port.read(1)
if not end or end[0] != END_BYTE:
return None
return {'cmd': cmd[0], 'data': data}
def set_profile(self, profile_index, profile):
# Pack profile data
data = bytearray()
# Name (16 bytes)
name_bytes = profile.name.encode('utf-8')[:15]
name_bytes += b'\0' * (16 - len(name_bytes))
data.extend(name_bytes)
# Segment count
data.append(len(profile.segments))
# Segments (up to 10)
for i in range(10):
if i < len(profile.segments):
seg = profile.segments[i]
data.extend(struct.pack('ffH', seg.target_temp, seg.ramp_rate, seg.soak_time))
else:
data.extend(struct.pack('ffH', 0, 0, 0))
# Add profile index
data.append(profile_index)
self.send_command(CMD_SET_PROFILE, data)
def start_profile(self, profile_index):
self.send_command(CMD_START_PROFILE, bytes([profile_index]))
def stop_profile(self):
self.send_command(CMD_STOP_PROFILE, b'')
def set_pid(self, zone, kp, ki, kd):
data = bytearray()
data.append(zone)
data.extend(struct.pack('ddd', kp, ki, kd))
self.send_command(CMD_SET_PID, data)
def set_manual_setpoints(self, top, bot1, bot2):
data = struct.pack('fff', top, bot1, bot2)
self.send_command(CMD_SET_MANUAL, data)
class TemperaturePlot(pg.PlotWidget):
def __init__(self):
super().__init__()
self.setLabel('left', 'Temperature', '°C')
self.setLabel('bottom', 'Time', 's')
self.showGrid(x=True, y=True)
# Data storage
self.max_points = 600 # 5 minutes at 2Hz
self.time_data = deque(maxlen=self.max_points)
self.temp_top = deque(maxlen=self.max_points)
self.temp_bot1 = deque(maxlen=self.max_points)
self.temp_bot2 = deque(maxlen=self.max_points)
# Plot lines
self.line_top = self.plot(pen=pg.mkPen('r', width=2), name='Top')
self.line_bot1 = self.plot(pen=pg.mkPen('g', width=2), name='Bottom 1')
self.line_bot2 = self.plot(pen=pg.mkPen('b', width=2), name='Bottom 2')
self.profile_line_top = self.plot(pen=pg.mkPen('r', width=2, style=QtCore.Qt.DashLine), name='Profile Top')
self.profile_line_bot1 = self.plot(pen=pg.mkPen('g', width=2, style=QtCore.Qt.DashLine), name='Profile Bottom 1')
self.profile_line_bot2 = self.plot(pen=pg.mkPen('b', width=2, style=QtCore.Qt.DashLine), name='Profile Bottom 2')
self.addLegend()
self.start_time = time.time()
def update_data(self, top, bot1, bot2):
current_time = time.time() - self.start_time
self.time_data.append(current_time)
self.temp_top.append(top)
self.temp_bot1.append(bot1)
self.temp_bot2.append(bot2)
self.line_top.setData(list(self.time_data), list(self.temp_top))
self.line_bot1.setData(list(self.time_data), list(self.temp_bot1))
self.line_bot2.setData(list(self.time_data), list(self.temp_bot2))
def plot_profile(self, profile):
# Generate profile data
time_data = [0]
temp_data_top = [25] # Start at room temperature
temp_data_bot1 = [25]
temp_data_bot2 = [25]
current_time = 0
current_temp = 25
for seg in profile.segments:
target_temp = seg.target_temp
ramp_rate = seg.ramp_rate
soak_time = seg.soak_time
# Ramp phase
if ramp_rate != 0:
ramp_time = abs((target_temp - current_temp) / ramp_rate)
current_time += ramp_time
time_data.append(current_time)
temp_data_top.append(target_temp)
temp_data_bot1.append(target_temp)
temp_data_bot2.append(target_temp)
# Soak phase
current_time += soak_time
time_data.append(current_time)
temp_data_top.append(target_temp)
temp_data_bot1.append(target_temp)
temp_data_bot2.append(target_temp)
current_temp = target_temp
# Update plot
self.profile_line_top.setData(time_data, temp_data_top)
self.profile_line_bot1.setData(time_data, temp_data_bot1)
self.profile_line_bot2.setData(time_data, temp_data_bot2)
def clear_plot(self):
self.time_data.clear()
self.temp_top.clear()
self.temp_bot1.clear()
self.temp_bot2.clear()
self.line_top.clear()
self.line_bot1.clear()
self.line_bot2.clear()
self.start_time = time.time()
class ProfileEditor(QWidget):
def __init__(self):
super().__init__()
self.profile = Profile()
self.init_ui()
def init_ui(self):
layout = QVBoxLayout()
# Profile name
name_layout = QHBoxLayout()
name_layout.addWidget(QLabel("Profile Name:"))
self.name_edit = QLineEdit("Profile 1")
name_layout.addWidget(self.name_edit)
layout.addLayout(name_layout)
# Segments table
self.table = QTableWidget()
self.table.setColumnCount(4)
self.table.setHorizontalHeaderLabels(['Target Temp (°C)', 'Ramp Rate (°C/s)', 'Soak Time (s)', 'Action'])
layout.addWidget(self.table)
# Add segment button
self.add_button = QPushButton("Add Segment")
self.add_button.clicked.connect(self.add_segment)
layout.addWidget(self.add_button)
# Profile preview
self.preview_plot = pg.PlotWidget()
self.preview_plot.setLabel('left', 'Temperature', '°C')
self.preview_plot.setLabel('bottom', 'Time', 's')
self.preview_plot.showGrid(x=True, y=True)
layout.addWidget(self.preview_plot)
self.setLayout(layout)
# Add initial segment
self.add_segment()
def add_segment(self):
row = self.table.rowCount()
self.table.insertRow(row)
# Temperature
temp_spin = QDoubleSpinBox()
temp_spin.setRange(0, 300)
temp_spin.setValue(150)
temp_spin.valueChanged.connect(self.update_preview)
self.table.setCellWidget(row, 0, temp_spin)
# Ramp rate
ramp_spin = QDoubleSpinBox()
ramp_spin.setRange(-10, 10)
ramp_spin.setValue(1.0)
ramp_spin.setSingleStep(0.1)
ramp_spin.valueChanged.connect(self.update_preview)
self.table.setCellWidget(row, 1, ramp_spin)
# Soak time
soak_spin = QSpinBox()
soak_spin.setRange(0, 3600)
soak_spin.setValue(60)
soak_spin.valueChanged.connect(self.update_preview)
self.table.setCellWidget(row, 2, soak_spin)
# Remove button
remove_btn = QPushButton("Remove")
remove_btn.clicked.connect(lambda: self.remove_segment(row))
self.table.setCellWidget(row, 3, remove_btn)
self.update_preview()
def remove_segment(self, row):
self.table.removeRow(row)
self.update_preview()
def update_preview(self):
# Generate preview data
time_data = [0]
temp_data = [25] # Start at room temperature
current_time = 0
current_temp = 25
for row in range(self.table.rowCount()):
target_temp = self.table.cellWidget(row, 0).value()
ramp_rate = self.table.cellWidget(row, 1).value()
soak_time = self.table.cellWidget(row, 2).value()
# Ramp phase
if ramp_rate != 0:
ramp_time = abs((target_temp - current_temp) / ramp_rate)
current_time += ramp_time
time_data.append(current_time)
temp_data.append(target_temp)
# Soak phase
current_time += soak_time
time_data.append(current_time)
temp_data.append(target_temp)
current_temp = target_temp
# Update plot
self.preview_plot.clear()
self.preview_plot.plot(time_data, temp_data, pen=pg.mkPen('w', width=2))
def get_profile(self):
profile = Profile(self.name_edit.text())
for row in range(self.table.rowCount()):
seg = ProfileSegment(
self.table.cellWidget(row, 0).value(),
self.table.cellWidget(row, 1).value(),
self.table.cellWidget(row, 2).value()
)
profile.segments.append(seg)
return profile
class PIDTuner(QWidget):
def __init__(self, serial_worker):
super().__init__()
self.serial_worker = serial_worker
self.init_ui()
def init_ui(self):
layout = QVBoxLayout()
# Zone selection
zone_layout = QHBoxLayout()
zone_layout.addWidget(QLabel("Zone:"))
self.zone_combo = QComboBox()
self.zone_combo.addItems(['Top Heater', 'Bottom Heater 1', 'Bottom Heater 2'])
zone_layout.addWidget(self.zone_combo)
layout.addLayout(zone_layout)
# PID parameters
param_layout = QGridLayout()
self.kp_spin = QDoubleSpinBox()
self.kp_spin.setRange(0, 100)
self.kp_spin.setSingleStep(0.1)
self.kp_spin.setValue(2.0)
param_layout.addWidget(QLabel("Kp:"), 0, 0)
param_layout.addWidget(self.kp_spin, 0, 1)
self.ki_spin = QDoubleSpinBox()
self.ki_spin.setRange(0, 100)
self.ki_spin.setSingleStep(0.1)
self.ki_spin.setValue(0.5)
param_layout.addWidget(QLabel("Ki:"), 1, 0)
param_layout.addWidget(self.ki_spin, 1, 1)
self.kd_spin = QDoubleSpinBox()
self.kd_spin.setRange(0, 100)
self.kd_spin.setSingleStep(0.1)
self.kd_spin.setValue(1.0)
param_layout.addWidget(QLabel("Kd:"), 2, 0)
param_layout.addWidget(self.kd_spin, 2, 1)
layout.addLayout(param_layout)
# Buttons
button_layout = QHBoxLayout()
self.apply_btn = QPushButton("Apply")
self.apply_btn.clicked.connect(self.apply_pid)
button_layout.addWidget(self.apply_btn)
self.autotune_btn = QPushButton("Autotune")
self.autotune_btn.clicked.connect(self.autotune)
button_layout.addWidget(self.autotune_btn)
layout.addLayout(button_layout)
# Tuning plot
self.tuning_plot = pg.PlotWidget()
self.tuning_plot.setLabel('left', 'Temperature', '°C')
self.tuning_plot.setLabel('bottom', 'Time', 's')
self.tuning_plot.showGrid(x=True, y=True)
layout.addWidget(self.tuning_plot)
self.setLayout(layout)
def apply_pid(self):
zone = self.zone_combo.currentIndex()
self.serial_worker.set_pid(zone, self.kp_spin.value(),
self.ki_spin.value(), self.kd_spin.value())
def autotune(self):
# Implement Ziegler-Nichols or relay tuning method
QMessageBox.information(self, "Autotune",
"Autotune will run a test cycle to determine optimal PID parameters.")
class MainWindow(QMainWindow):
def __init__(self):
super().__init__()
self.serial_worker = SerialWorker()
self.serial_worker.temperature_update.connect(self.update_temperature)
self.serial_worker.connection_lost.connect(self.handle_connection_lost)
self.serial_worker.status_update.connect(self.update_status)
self.init_ui()
def init_ui(self):
self.setWindowTitle("BGA Rework Station Control")
self.setGeometry(100, 100, 1200, 800)
# Central widget
central_widget = QWidget()
self.setCentralWidget(central_widget)
# Main layout
main_layout = QVBoxLayout(central_widget)
# Connection bar
conn_layout = QHBoxLayout()
self.port_combo = QComboBox()
self.refresh_ports()
conn_layout.addWidget(QLabel("Port:"))
conn_layout.addWidget(self.port_combo)
self.refresh_btn = QPushButton("Refresh")
self.refresh_btn.clicked.connect(self.refresh_ports)
conn_layout.addWidget(self.refresh_btn)
self.connect_btn = QPushButton("Connect")
self.connect_btn.clicked.connect(self.toggle_connection)
conn_layout.addWidget(self.connect_btn)
self.status_label = QLabel("Disconnected")
self.status_label.setStyleSheet("color: red")
conn_layout.addWidget(self.status_label)
conn_layout.addStretch()
main_layout.addLayout(conn_layout)
# Tab widget
self.tabs = QTabWidget()
# Temperature monitoring tab
temp_tab = QWidget()
temp_layout = QVBoxLayout(temp_tab)
# Current temperatures
temp_display_layout = QHBoxLayout()
self.temp_top_label = QLabel("Top: --°C")
self.temp_top_label.setStyleSheet("font-size: 20px; font-weight: bold")
temp_display_layout.addWidget(self.temp_top_label)
self.temp_bot1_label = QLabel("Bot1: --°C")
self.temp_bot1_label.setStyleSheet("font-size: 20px; font-weight: bold")
temp_display_layout.addWidget(self.temp_bot1_label)
self.temp_bot2_label = QLabel("Bot2: --°C")
self.temp_bot2_label.setStyleSheet("font-size: 20px; font-weight: bold")
temp_display_layout.addWidget(self.temp_bot2_label)
temp_display_layout.addStretch()
temp_layout.addLayout(temp_display_layout)
# Temperature plot
self.temp_plot = TemperaturePlot()
temp_layout.addWidget(self.temp_plot)
# Control buttons
control_layout = QHBoxLayout()
self.profile_combo = QComboBox()
self.profile_combo.addItems([f"Profile {i+1}" for i in range(10)])
control_layout.addWidget(QLabel("Profile:"))
control_layout.addWidget(self.profile_combo)
self.start_btn = QPushButton("Start Profile")
self.start_btn.clicked.connect(self.start_profile)
control_layout.addWidget(self.start_btn)
self.stop_btn = QPushButton("Stop")
self.stop_btn.clicked.connect(self.stop_profile)
control_layout.addWidget(self.stop_btn)
control_layout.addStretch()
temp_layout.addLayout(control_layout)
self.tabs.addTab(temp_tab, "Temperature Monitor")
# Profile editor tab
self.profile_editor = ProfileEditor()
self.tabs.addTab(self.profile_editor, "Profile Editor")
# PID tuning tab
self.pid_tuner = PIDTuner(self.serial_worker)
self.tabs.addTab(self.pid_tuner, "PID Tuning")
# Manual control tab
manual_tab = QWidget()
manual_layout = QVBoxLayout(manual_tab)
manual_grid = QGridLayout()
self.manual_top = QDoubleSpinBox()
self.manual_top.setRange(0, 300)
self.manual_top.setValue(25)
manual_grid.addWidget(QLabel("Top Setpoint:"), 0, 0)
manual_grid.addWidget(self.manual_top, 0, 1)
self.manual_bot1 = QDoubleSpinBox()
self.manual_bot1.setRange(0, 300)
self.manual_bot1.setValue(25)
manual_grid.addWidget(QLabel("Bottom 1 Setpoint:"), 1, 0)
manual_grid.addWidget(self.manual_bot1, 1, 1)
self.manual_bot2 = QDoubleSpinBox()
self.manual_bot2.setRange(0, 300)
self.manual_bot2.setValue(25)
manual_grid.addWidget(QLabel("Bottom 2 Setpoint:"), 2, 0)
manual_grid.addWidget(self.manual_bot2, 2, 1)
manual_layout.addLayout(manual_grid)
self.manual_apply_btn = QPushButton("Apply Setpoints")
self.manual_apply_btn.clicked.connect(self.apply_manual_setpoints)
manual_layout.addWidget(self.manual_apply_btn)
manual_layout.addStretch()
self.tabs.addTab(manual_tab, "Manual Control")
main_layout.addWidget(self.tabs)
# Menu bar
menubar = self.menuBar()
file_menu = menubar.addMenu('File')
save_profile_action = QAction('Save Profile', self)
save_profile_action.triggered.connect(self.save_profile)
file_menu.addAction(save_profile_action)
load_profile_action = QAction('Load Profile', self)
load_profile_action.triggered.connect(self.load_profile)
file_menu.addAction(load_profile_action)
def refresh_ports(self):
self.port_combo.clear()
ports = [port.device for port in serial.tools.list_ports.comports()]
self.port_combo.addItems(ports)
def toggle_connection(self):
if self.serial_worker.running:
self.serial_worker.disconnect()
self.serial_worker.wait()
self.connect_btn.setText("Connect")
self.status_label.setText("Disconnected")
self.status_label.setStyleSheet("color: red")
else:
port = self.port_combo.currentText()
if self.serial_worker.connect_port(port):
self.serial_worker.start()
self.connect_btn.setText("Disconnect")
self.status_label.setText("Connected")
self.status_label.setStyleSheet("color: green")
else:
QMessageBox.critical(self, "Connection Error",
f"Failed to connect to {port}")
def handle_connection_lost(self):
self.connect_btn.setText("Connect")
self.status_label.setText("Connection Lost")
self.status_label.setStyleSheet("color: red")
def update_temperature(self, top, bot1, bot2):
self.temp_top_label.setText(f"Top: {top:.1f}°C")
self.temp_bot1_label.setText(f"Bot1: {bot1:.1f}°C")
self.temp_bot2_label.setText(f"Bot2: {bot2:.1f}°C")
self.temp_plot.update_data(top, bot1, bot2)
def update_status(self, status):
if status['running']:
self.start_btn.setEnabled(False)
self.stop_btn.setEnabled(True)
else:
self.start_btn.setEnabled(True)
self.stop_btn.setEnabled(False)
def start_profile(self):
if not self.serial_worker.running:
QMessageBox.warning(self, "Not Connected",
"Please connect to the device first")
return
# First, send the current profile to the device
profile = self.profile_editor.get_profile()
profile_index = self.profile_combo.currentIndex()
self.serial_worker.set_profile(profile_index, profile)
time.sleep(0.1) # Give time for the profile to be saved
# Clear the plot
self.temp_plot.clear_plot()
# Plot the selected profile
self.temp_plot.plot_profile(profile)
# Then start the profile
self.serial_worker.start_profile(profile_index)
def stop_profile(self):
self.serial_worker.stop_profile()
def apply_manual_setpoints(self):
if not self.serial_worker.running:
QMessageBox.warning(self, "Not Connected",
"Please connect to the device first")
return
self.serial_worker.set_manual_setpoints(
self.manual_top.value(),
self.manual_bot1.value(),
self.manual_bot2.value()
)
def save_profile(self):
profile = self.profile_editor.get_profile()
filename, _ = QFileDialog.getSaveFileName(self, "Save Profile",
"", "Profile Files (*.json)")
if filename:
import json
data = {
'name': profile.name,
'segments': [
{
'target_temp': seg.target_temp,
'ramp_rate': seg.ramp_rate,
'soak_time': seg.soak_time
}
for seg in profile.segments
]
}
with open(filename, 'w') as f:
json.dump(data, f, indent=2)
def load_profile(self):
filename, _ = QFileDialog.getOpenFileName(self, "Load Profile",
"", "Profile Files (*.json)")
if filename:
import json
with open(filename, 'r') as f:
data = json.load(f)
# Update profile editor
self.profile_editor.name_edit.setText(data['name'])
# Clear existing segments
self.profile_editor.table.setRowCount(0)
# Add loaded segments
for seg_data in data['segments']:
self.profile_editor.add_segment()
row = self.profile_editor.table.rowCount() - 1
self.profile_editor.table.cellWidget(row, 0).setValue(seg_data['target_temp'])
self.profile_editor.table.cellWidget(row, 1).setValue(seg_data['ramp_rate'])
self.profile_editor.table.cellWidget(row, 2).setValue(seg_data['soak_time'])
self.profile_editor.update_preview()
def main():
app = QApplication(sys.argv)
window = MainWindow()
window.show()
sys.exit(app.exec_())
if __name__ == '__main__':
main()
Key Changes:
-
TemperaturePlot Class:
- Added
plot_profile method to plot the selected profile.
- Added
clear_plot method to clear the plot when a profile is started.
-
MainWindow Class:
- Called
clear_plot and plot_profile methods when starting a profile.
With these changes, the temperature plot will start when you start a temperature profile, and the selected profile will be plotted alongside the real-time temperatures.