网站建设图标图片,什么网站能免费做推广,wordpress 畅言,宿迁专业三合一网站开发因为项目需求#xff0c;要实现PC远程控制警铃的效果。警铃结构简单#xff0c;只需要通上12V的直流电就可以报警。本文的树莓派设备是在树莓派4B的基础上找硬件厂商搞的定制化产品。树莓派4B通过4G网卡连接互联网#xff0c;并利用GPIO控制12V直流电的继电器开关。树莓派4B…因为项目需求要实现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, whenM, backupCount3)
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_highTrue
# Initially off: initial_valueFalse
relay gpiozero.OutputDevice(RELAY_PIN, active_highTrue, initial_valueFalse)def getBellSwitch():res requests.get(urlhttp://yourhost/api/raspberry/switch?no1)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?no1 接口查询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 MapString,Object updateBellSwitch(RequestBody Bell bell) {// 根据 no 和 switch 更新对应记录。具体代码省略。// .....MapString, Object map new HashMap();map.put(code, 200);map.put(msg, 操作成功);return map;}
}