package ece448.iot_sim; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * Simulate a smart plug with power monitoring. */ public class PlugSim { private final String name; private boolean on = false; private double power = 0; // in watts public PlugSim(String name) { this.name = name; } /** * No need to synchronize if read a final field. */ public String getName() { return name; } /** * Switch the plug on. */ synchronized public void switchOn() { // P1: add your code here on = true; } /** * Switch the plug off. */ synchronized public void switchOff() { // P1: add your code here on = false; } /** * Toggle the plug. */ synchronized public void toggle() { // P1: add your code here on = !on; } /** * Measure power. */ synchronized public void measurePower() { if (!on) { updatePower(0); return; } // a trick to help testing if (name.indexOf(".") != -1) { updatePower(Integer.parseInt(name.split("\\.")[1])); } // do some random walk else if (power < 100) { updatePower(power + Math.random() * 100); } else if (power > 300) { updatePower(power - Math.random() * 100); } else { updatePower(power + Math.random() * 40 - 20); } } protected void updatePower(double p) { power = p; logger.debug("Plug {}: power {}", name, power); } /** * Getter: current state */ synchronized public boolean isOn() { return on; } /** * Getter: last power reading */ synchronized public double getPower() { return power; } private static final Logger logger = LoggerFactory.getLogger(PlugSim.class);
时间: 2024-02-14 21:21:53 浏览: 67
远程管理工具 FinalShell 3.9.2.2 免安装版
这段代码是用 Java 实现的模拟智能插座并进行电力监测。其中,PlugSim 类包括以下方法:
- switchOn():开启插座;
- switchOff():关闭插座;
- toggle():切换插座状态;
- measurePower():测量电力;
- isOn():获取当前插座状态;
- getPower():获取上次电力读数。
这些方法都被 synchronized 修饰,以确保线程安全。类的属性包括插座名称(name)、插座状态(on)和电力(power)。measurePower() 方法中,如果插座未开启,则电力为 0;否则,电力会根据一定规则进行变动。最后,updatePower() 方法用于更新电力读数,并使用 logger 对象打印日志。
阅读全文