Compare commits

..

No commits in common. "59103cb2a178cea3dcf316ed68d33f9156da588d" and "026dd1ed9c058f38817a89d023490be77d578156" have entirely different histories.

10 changed files with 89 additions and 207 deletions

View File

@ -69,11 +69,10 @@ The scope of this setting is per TCP session.
| `pid <0/1> integral_min <value>` | Set integral lower bound |
| `pid <0/1> integral_max <value>` | Set integral upper bound |
| `s-h` | Show Steinhart-Hart equation parameters |
| `s-h <0/1> <t0/b/r0> <value>` | Set Steinhart-Hart parameter for a channel |
| `s-h <0/1> <t/b/r0> <value>` | Set Steinhart-Hart parameter for a channel |
| `postfilter` | Show postfilter settings |
| `postfilter <0/1> off` | Disable postfilter |
| `postfilter <0/1> rate <rate>` | Set postfilter output data rate |
| `load` | Restore configuration from EEPROM |
| `save` | Save configuration to EEPROM |
| `reset` | Reset the device |
| `ipv4 <X.X.X.X>` | Configure IPv4 address |

View File

@ -34,7 +34,6 @@ series = {
'i_set': Series(),
'pid_output': Series(),
'vref': Series(),
'dac_value': Series(),
'dac_feedback': Series(),
'i_tec': Series(),
'tec_i': Series(),

View File

@ -34,92 +34,24 @@ class Client:
return result
def get_pwm(self):
"""Retrieve PWM limits for the TEC
Example::
[{'channel': 0,
'center': 'vref',
'i_set': {'max': 2.9802790335151985, 'value': -0.02002179650216762},
'max_i_neg': {'max': 3.0, 'value': 3.0},
'max_v': {'max': 5.988, 'value': 5.988},
'max_i_pos': {'max': 3.0, 'value': 3.0}},
{'channel': 1,
'center': 'vref',
'i_set': {'max': 2.9802790335151985, 'value': -0.02002179650216762},
'max_i_neg': {'max': 3.0, 'value': 3.0},
'max_v': {'max': 5.988, 'value': 5.988},
'max_i_pos': {'max': 3.0, 'value': 3.0}}
]
"""
return self._get_conf("pwm")
def get_pid(self):
"""Retrieve PID control state
Example::
[{'channel': 0,
'parameters': {
'kp': 10.0,
'ki': 0.02,
'kd': 0.0,
'output_min': 0.0,
'output_max': 3.0,
'integral_min': -100.0,
'integral_max': 100.0},
'target': 37.0,
'integral': 38.41138597026372},
{'channel': 1,
'parameters': {
'kp': 10.0,
'ki': 0.02,
'kd': 0.0,
'output_min': 0.0,
'output_max': 3.0,
'integral_min': -100.0,
'integral_max': 100.0},
'target': 36.5,
'integral': nan}]
"""
return self._get_conf("pid")
def get_steinhart_hart(self):
"""Retrieve Steinhart-Hart parameters for resistance to temperature conversion
Example::
[{'params': {'b': 3800.0, 'r0': 10000.0, 't0': 298.15}, 'channel': 0},
{'params': {'b': 3800.0, 'r0': 10000.0, 't0': 298.15}, 'channel': 1}]
"""
return self._get_conf("s-h")
def get_postfilter(self):
"""Retrieve DAC postfilter configuration
Example::
[{'rate': None, 'channel': 0},
{'rate': 21.25, 'channel': 1}]
"""
return self._get_conf("postfilter")
def report_mode(self):
"""Start reporting measurement values
Example of yielded data::
{'channel': 0,
'time': 2302524,
'adc': 0.6199188965423515,
'sens': 6138.519310282602,
'temperature': 36.87032392655527,
'pid_engaged': True,
'i_set': 2.0635816680889123,
'vref': 1.494,
'dac_value': 2.527790834044456,
'dac_feedback': 2.523,
'i_tec': 2.331,
'tec_i': 2.0925,
'tec_u_meas': 2.5340000000000003,
'pid_output': 2.067581958092247}
"""
self._command("report mode", "on")
self._read_line()
while True:
line = self._read_line()
@ -131,33 +63,15 @@ class Client:
pass
def set_param(self, topic, channel, field="", value=""):
"""Set configuration parameters
Examples::
tec.set_param("pwm", 0, "max_v", 2.0)
tec.set_param("pid", 1, "output_max", 2.5)
tec.set_param("s-h", 0, "t0", 20.0)
tec.set_param("center", 0, "vref")
tec.set_param("postfilter", 1, 21)
See the firmware's README.md for a full list.
"""
if type(value) is float:
value = "{:f}".format(value)
if type(value) is not str:
value = str(value)
self._command(topic, str(channel), field, value)
# read response line
self._read_line()
def power_up(self, channel, target):
"""Start closed-loop mode"""
self.set_param("pid", channel, "target", value=target)
self.set_param("pwm", channel, "pid")
def save_config(self):
"""Save current configuration to EEPROM"""
self._command("save")
def load_config(self):
"""Load current configuration from EEPROM"""
self._command("load")

View File

@ -1,8 +1,6 @@
from pytec.client import Client
tec = Client() #(host="localhost", port=6667)
tec.set_param("s-h", 1, "t0", 20)
print(tec.get_pid())
print(tec.get_steinhart_hart())
tec.set_param("s-h", 0, "t", 20)
for data in tec.report_mode():
print(data)

View File

@ -135,7 +135,6 @@ pub enum Command {
Load,
Save,
Reset,
Ipv4([u8; 4]),
Show(ShowCommand),
Reporting(bool),
/// PWM parameter setting
@ -182,19 +181,6 @@ fn whitespace(input: &[u8]) -> IResult<&[u8], ()> {
fold_many1(char(' '), (), |(), _| ())(input)
}
fn unsigned(input: &[u8]) -> IResult<&[u8], Result<u32, Error>> {
take_while1(is_digit)(input)
.map(|(input, digits)| {
let result =
from_utf8(digits)
.map_err(|e| e.into())
.and_then(|digits| u32::from_str_radix(digits, 10)
.map_err(|e| e.into())
);
(input, result)
})
}
fn float(input: &[u8]) -> IResult<&[u8], Result<f64, Error>> {
let (input, sign) = opt(is_a("-"))(input)?;
let negative = sign.is_some();
@ -429,30 +415,11 @@ fn postfilter(input: &[u8]) -> IResult<&[u8], Result<Command, Error>> {
))(input)
}
fn ipv4(input: &[u8]) -> IResult<&[u8], Result<Command, Error>> {
let (input, _) = tag("ipv4")(input)?;
let (input, _) = whitespace(input)?;
let (input, a) = unsigned(input)?;
let (input, _) = tag(".")(input)?;
let (input, b) = unsigned(input)?;
let (input, _) = tag(".")(input)?;
let (input, c) = unsigned(input)?;
let (input, _) = tag(".")(input)?;
let (input, d) = unsigned(input)?;
end(input)?;
let result = a.and_then(|a| b.and_then(|b| c.and_then(|c| d.map(|d|
Command::Ipv4([a as u8, b as u8, c as u8, d as u8])
))));
Ok((input, result))
}
fn command(input: &[u8]) -> IResult<&[u8], Result<Command, Error>> {
alt((value(Ok(Command::Quit), tag("quit")),
value(Ok(Command::Load), tag("load")),
value(Ok(Command::Save), tag("save")),
value(Ok(Command::Reset), tag("reset")),
ipv4,
map(report, Ok),
pwm,
center_point,
@ -497,12 +464,6 @@ mod test {
assert_eq!(command, Ok(Command::Save));
}
#[test]
fn parse_ipv4() {
let command = Command::parse(b"ipv4 192.168.1.26");
assert_eq!(command, Ok(Command::Ipv4([192, 168, 1, 26])));
}
#[test]
fn parse_report() {
let command = Command::parse(b"report");

View File

@ -1,6 +1,5 @@
use postcard::{from_bytes, to_slice};
use serde::{Serialize, Deserialize};
use smoltcp::wire::Ipv4Address;
use stm32f4xx_hal::i2c;
use uom::si::{
electric_potential::volt,
@ -41,17 +40,15 @@ impl From<postcard::Error> for Error {
#[derive(Debug, PartialEq, Serialize, Deserialize)]
pub struct Config {
channels: [ChannelConfig; CHANNELS],
pub ipv4_address: [u8; 4],
}
impl Config {
pub fn new(channels: &mut Channels, ipv4_address: Ipv4Address) -> Self {
pub fn new(channels: &mut Channels) -> Self {
Config {
channels: [
ChannelConfig::new(channels, 0),
ChannelConfig::new(channels, 1),
],
ipv4_address: ipv4_address.0,
}
}
@ -194,7 +191,6 @@ impl PwmLimits {
#[cfg(test)]
mod test {
use super::*;
use crate::DEFAULT_IPV4_ADDRESS;
#[test]
fn test_fit_eeprom() {
@ -215,7 +211,6 @@ mod test {
channel_config.clone(),
channel_config.clone(),
],
ipv4_address: DEFAULT_IPV4_ADDRESS.0,
};
let mut buffer = [0; EEPROM_SIZE];
@ -242,7 +237,6 @@ mod test {
channel_config.clone(),
channel_config.clone(),
],
ipv4_address: DEFAULT_IPV4_ADDRESS.0,
};
let mut buffer = [0; EEPROM_SIZE];

View File

@ -4,7 +4,7 @@ use crate::usb;
pub fn init_log() {
static USB_LOGGER: usb::Logger = usb::Logger;
let _ = log::set_logger(&USB_LOGGER);
log::set_max_level(log::LevelFilter::Debug);
log::set_max_level(log::LevelFilter::Trace);
}
#[cfg(feature = "semihosting")]

View File

@ -24,9 +24,10 @@ use stm32f4xx_hal::{
use smoltcp::{
time::Instant,
socket::TcpSocket,
wire::{EthernetAddress, Ipv4Address},
wire::EthernetAddress,
};
use uom::{
fmt::DisplayStyle::Abbreviation,
si::{
f64::{
ElectricCurrent,
@ -76,7 +77,6 @@ const WATCHDOG_INTERVAL: u32 = 30_000;
pub const EEPROM_PAGE_SIZE: usize = 8;
pub const EEPROM_SIZE: usize = 128;
pub const DEFAULT_IPV4_ADDRESS: Ipv4Address = Ipv4Address([192, 168, 1, 26]);
const TCP_PORT: u16 = 23;
@ -160,15 +160,10 @@ fn main() -> ! {
usb::State::setup(usb);
let mut ipv4_address = DEFAULT_IPV4_ADDRESS;
let mut channels = Channels::new(pins);
let _ = Config::load(&mut eeprom)
.map(|config| {
config.apply(&mut channels);
ipv4_address = Ipv4Address::from_bytes(&config.ipv4_address);
})
.map(|config| config.apply(&mut channels))
.map_err(|e| warn!("error loading config: {:?}", e));
info!("IPv4 address: {}", ipv4_address);
// EEPROM ships with a read-only EUI-48 identifier
let mut eui48 = [0; 6];
@ -176,8 +171,7 @@ fn main() -> ! {
let hwaddr = EthernetAddress(eui48);
info!("EEPROM MAC address: {}", hwaddr);
net::run(clocks, dp.ETHERNET_MAC, dp.ETHERNET_DMA, eth_pins, hwaddr, ipv4_address, |iface| {
let mut new_ipv4_address = None;
net::run(clocks, dp.ETHERNET_MAC, dp.ETHERNET_DMA, eth_pins, hwaddr, |iface| {
Server::<Session>::run(iface, |server| {
leds.r1.off();
@ -208,11 +202,11 @@ fn main() -> ! {
Ok(SessionInput::Command(command)) => match command {
Command::Quit =>
socket.close(),
Command::Reporting(_reporting) => {
// handled by session
Command::Reporting(reporting) => {
let _ = writeln!(socket, "report={}", if reporting { "on" } else { "off" });
}
Command::Show(ShowCommand::Reporting) => {
let _ = writeln!(socket, "{{ \"report\": {:?} }}", session.reporting());
let _ = writeln!(socket, "report={}", if session.reporting() { "on" } else { "off" });
}
Command::Show(ShowCommand::Input) => {
for channel in 0..CHANNELS {
@ -266,6 +260,8 @@ fn main() -> ! {
Command::PwmPid { channel } => {
channels.channel_state(channel).pid_engaged = true;
leds.g3.on();
let _ = writeln!(socket, "channel {}: PID enabled to control PWM", channel
);
}
Command::Pwm { channel, pin, value } => {
match pin {
@ -273,20 +269,44 @@ fn main() -> ! {
channels.channel_state(channel).pid_engaged = false;
leds.g3.off();
let current = ElectricCurrent::new::<ampere>(value);
channels.set_i(channel, current);
let (current, max) = channels.set_i(channel, current);
channels.power_up(channel);
let _ = writeln!(
socket, "channel {}: i_set DAC output set to {:.3} / {:.3}",
channel,
current.into_format_args(ampere, Abbreviation),
max.into_format_args(ampere, Abbreviation),
);
}
PwmPin::MaxV => {
let voltage = ElectricPotential::new::<volt>(value);
channels.set_max_v(channel, voltage);
let (voltage, max) = channels.set_max_v(channel, voltage);
let _ = writeln!(
socket, "channel {}: max_v set to {:.3} / {:.3}",
channel,
voltage.into_format_args(volt, Abbreviation),
max.into_format_args(volt, Abbreviation),
);
}
PwmPin::MaxIPos => {
let current = ElectricCurrent::new::<ampere>(value);
channels.set_max_i_pos(channel, current);
let (current, max) = channels.set_max_i_pos(channel, current);
let _ = writeln!(
socket, "channel {}: max_i_pos set to {:.3} / {:.3}",
channel,
current.into_format_args(ampere, Abbreviation),
max.into_format_args(ampere, Abbreviation),
);
}
PwmPin::MaxINeg => {
let current = ElectricCurrent::new::<ampere>(value);
channels.set_max_i_neg(channel, current);
let (current, max) = channels.set_max_i_neg(channel, current);
let _ = writeln!(
socket, "channel {}: max_i_neg set to {:.3} / {:.3}",
channel,
current.into_format_args(ampere, Abbreviation),
max.into_format_args(ampere, Abbreviation),
);
}
}
}
@ -296,6 +316,15 @@ fn main() -> ! {
state.center = center;
if !state.pid_engaged {
channels.set_i(channel, i_tec);
let _ = writeln!(
socket, "channel {}: center point updated, output readjusted for {:.3}",
channel, i_tec.into_format_args(ampere, Abbreviation),
);
} else {
let _ = writeln!(
socket, "channel {}: center point updated",
channel,
);
}
}
Command::Pid { channel, parameter, value } => {
@ -322,6 +351,7 @@ fn main() -> ! {
IntegralMax =>
pid.parameters.integral_max = value as f32,
}
let _ = writeln!(socket, "PID parameter updated");
}
Command::SteinhartHart { channel, parameter, value } => {
let sh = &mut channels.channel_state(channel).sh;
@ -331,40 +361,52 @@ fn main() -> ! {
B => sh.b = value,
R0 => sh.r0 = ElectricalResistance::new::<ohm>(value),
}
let _ = writeln!(socket, "Steinhart-Hart equation parameter updated");
}
Command::PostFilter { channel, rate: None } => {
channels.adc.set_postfilter(channel as u8, None).unwrap();
let _ = writeln!(
socket, "channel {}: postfilter disabled",
channel
);
}
Command::PostFilter { channel, rate: Some(rate) } => {
let filter = ad7172::PostFilter::closest(rate);
match filter {
Some(filter) =>
channels.adc.set_postfilter(channel as u8, Some(filter)).unwrap(),
None =>
error!("unable to choose postfilter for rate {:.3}", rate),
Some(filter) => {
channels.adc.set_postfilter(channel as u8, Some(filter)).unwrap();
let _ = writeln!(
socket, "channel {}: postfilter set to {:.2} SPS",
channel, filter.output_rate().unwrap()
);
}
None => {
let _ = writeln!(socket, "Unable to choose postfilter");
}
}
}
Command::Load => {
match Config::load(&mut eeprom) {
Ok(config) => {
config.apply(&mut channels);
new_ipv4_address = Some(Ipv4Address::from_bytes(&config.ipv4_address));
let _ = writeln!(socket, "Config loaded from EEPROM.");
}
Err(e) => {
let _ = writeln!(socket, "Error: {:?}", e);
}
Err(e) =>
error!("unable to load eeprom config: {:?}", e),
}
}
Command::Save => {
let config = Config::new(&mut channels, ipv4_address);
let config = Config::new(&mut channels);
match config.save(&mut eeprom) {
Ok(()) => {},
Err(e) =>
error!("unable to save eeprom config: {:?}", e),
Ok(()) => {
let _ = writeln!(socket, "Config saved to EEPROM.");
}
Err(e) => {
let _ = writeln!(socket, "Error saving config: {:?}", e);
}
}
}
Command::Ipv4(address) => {
new_ipv4_address = Some(Ipv4Address::from_bytes(&address));
}
Command::Reset => {
for i in 0..CHANNELS {
channels.power_down(i);
@ -373,8 +415,9 @@ fn main() -> ! {
SCB::sys_reset();
}
}
Ok(SessionInput::Error(e)) =>
error!("session input: {:?}", e),
Ok(SessionInput::Error(e)) => {
let _ = writeln!(socket, "Command error: {:?}", e);
}
Err(_) =>
socket.close(),
}
@ -387,11 +430,6 @@ fn main() -> ! {
}
});
// Apply new IPv4 address
new_ipv4_address.map(|ipv4_address|
server.set_ipv4_address(ipv4_address)
);
// Update watchdog
wd.feed();

View File

@ -8,7 +8,7 @@ use stm32f4xx_hal::{
rcc::Clocks,
stm32::{interrupt, Peripherals, ETHERNET_MAC, ETHERNET_DMA},
};
use smoltcp::wire::{EthernetAddress, IpCidr, Ipv4Address};
use smoltcp::wire::{EthernetAddress, IpAddress, IpCidr};
use smoltcp::iface::{NeighborCache, EthernetInterfaceBuilder, EthernetInterface};
use stm32_eth::{Eth, RingEntry, PhyAddress, RxDescriptor, TxDescriptor};
use crate::pins::EthernetPins;
@ -29,9 +29,7 @@ pub fn run<F>(
clocks: Clocks,
ethernet_mac: ETHERNET_MAC, ethernet_dma: ETHERNET_DMA,
eth_pins: EthernetPins,
ethernet_addr: EthernetAddress,
local_addr: Ipv4Address,
f: F
ethernet_addr: EthernetAddress, f: F
) where
F: FnOnce(EthernetInterface<&mut stm32_eth::Eth<'static, 'static>>),
{
@ -52,9 +50,8 @@ pub fn run<F>(
eth_dev.enable_interrupt();
// IP stack
// Netmask 0 means we expect any IP address on the local segment.
// No routing.
let mut ip_addrs = [IpCidr::new(local_addr.into(), 0)];
let local_addr = IpAddress::v4(192, 168, 1, 26);
let mut ip_addrs = [IpCidr::new(local_addr, 24)];
let mut neighbor_storage = [None; 16];
let neighbor_cache = NeighborCache::new(&mut neighbor_storage[..]);
let iface = EthernetInterfaceBuilder::new(&mut eth_dev)

View File

@ -3,7 +3,6 @@ use smoltcp::{
iface::EthernetInterface,
socket::{SocketSet, SocketHandle, TcpSocket, TcpSocketBuffer, SocketRef},
time::Instant,
wire::{IpCidr, Ipv4Address, Ipv4Cidr},
};
@ -84,21 +83,4 @@ impl<'a, 'b, S: Default> Server<'a, 'b, S> {
callback(socket, &mut state.state);
}
}
pub fn set_ipv4_address(&mut self, ipv4_address: Ipv4Address) {
self.net.update_ip_addrs(|addrs| {
for addr in addrs.iter_mut() {
match addr {
IpCidr::Ipv4(_) => {
*addr = IpCidr::Ipv4(Ipv4Cidr::new(ipv4_address, 0));
// done
break
}
_ => {
// skip
}
}
}
});
}
}