因為項目需求,要實現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)
數據庫表名是 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;}
}