因为项目需求,要实现PC远程控制警铃的效果。警铃结构简单,只需要通上12V的直流电就可以报警。本文的树莓派设备是在树莓派4B的基础上找硬件厂商搞的定制化产品。树莓派4B通过4G网卡连接互联网,并利用GPIO控制12V直流电的继电器开关。树莓派4B每隔5秒就访问一次后端HTTP接口,查询警铃是打开还是关闭。
树莓派的Python 代码:
import requests
import gpiozero
import time
from time import sleep
import logging
from logging.handlers import TimedRotatingFileHandler
# Config logging
new_formatter = '[%(levelname)s]%(asctime)s:%(msecs)s.%(process)d,%(thread)d#>[%(funcName)s]:%(lineno)s %(message)s'
fmt = logging.Formatter(new_formatter)
log_handel = TimedRotatingFileHandler('/home/pi/your_disk_path/logs/bell.log', when='M', backupCount=3)
log_handel.setFormatter(fmt)
log_info = logging.getLogger('error')
log_info.setLevel(logging.INFO)
log_info.addHandler(log_handel)
RELAY_PIN = 22
# Triggered by the output pin going high: active_high=True
# Initially off: initial_value=False
relay = gpiozero.OutputDevice(RELAY_PIN, active_high=True, initial_value=False)
def getBellSwitch():
res = requests.get(url='http://yourhost/api/raspberry/switch?no=1')
if res.text == '1':
relay.on()
else:
relay.off()
sleep(5)
while True:
try:
getBellSwitch()
except Exception as e:
log_info.error(e)
我们还需要树莓派开机启动我们的Python程序。
执行下面的命令:
crontab -e
输入下面的代码,使得Python脚本可以开机启动
@reboot python /home/pi/ry/lingShanWei/bell.py
数据库表名是 bell 。表结构如下:
id:int // 主键
no:int // 设备编号,唯一性约束
heartbeat_time: datetime //联系服务器的心跳时间
switch: int // 0是关闭,1是打开
下面是Java示例代码。思路比较简单。树莓派每隔5秒调用一次 /api/raspberry/switch?no=1 接口查询1号警铃的状态。Java接口查询数据库返回switch的值。0表示关闭,1表示打开。
同时 /api/raspberry/updateSwitch 接口给PC调用,用来更新数据库中警铃的开关状态。
@RestController
@RequestMapping("/api/raspberry")
public class ApiRaspberryController {
@GetMapping("/switch")
public int switch(@RequestParam("no") Integer no) {
// 根据设备编号查找 bell 表记录,并且返回switch的值。
return bell.getSwitch();
}
@PostMapping("/updateSwitch")
public Map<String,Object> updateBellSwitch(@RequestBody Bell bell) {
// 根据 no 和 switch 更新对应记录。具体代码省略。
// .....
Map<String, Object> map = new HashMap<>();
map.put("code", 200);
map.put("msg", "操作成功");
return map;
}
}