【189】Java Spring利用HTTP轮询远程控制树莓派4B继电器开关

因为项目需求,要实现PC远程控制警铃的效果。警铃结构简单,只需要通上12V的直流电就可以报警。本文的树莓派设备是在树莓派4B的基础上找硬件厂商搞的定制化产品。树莓派4B通过4G网卡连接互联网,并利用GPIO控制12V直流电的继电器开关。树莓派4B每隔5秒就访问一次后端HTTP接口,查询警铃是打开还是关闭。

树莓派的Python 代码:

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 。表结构如下:

bash 复制代码
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调用,用来更新数据库中警铃的开关状态。

java 复制代码
@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;
    }
}
相关推荐
qq_158895411111 小时前
AI 音乐生成完成后,音频 URL 为什么会过期?一套可恢复的交付方案
python·api·ai音乐
2601_962106643 小时前
【Java Set综合实战】商品管理系统 + 图书收藏系统|Product、Book自定义类全套代码
java
Warson_L3 小时前
高性能架构设计
python·go
databook4 小时前
新数据到手,先跑哪几步检查
python·数据分析
RuoyiOffice4 小时前
SpringBoot+Vue3 凭证生命周期设计:审核、过账、冲销与反过账怎样保持账目一致
java·spring boot·事务·springboot3·财务系统·会计凭证·ruoyi office
2601_962106644 小时前
HashMap入门|工号-姓名键值存储、两种遍历方式、根据key/value查
java
czq_26867194875 小时前
Python打卡第46天
开发语言·python
杨凯凡5 小时前
Spring Framework 7 API 版本管理实战:请求头路由、兼容迁移与废弃策略
java·rest api·springframework·spring boot 4·api版本管理
T_Wizard5 小时前
同一个问题写了 4 遍:官方 SDK / HTTP / Spring AI / LangChain4j,到底该选哪个
java·ai编程
hai_android5 小时前
AudioTrack 深度解析:从原理到实战
android·java·kotlin