【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;
    }
}
相关推荐
小镇敲码人5 分钟前
深入剖析华为CANN框架下的Ops-CV仓库:从入门到实战指南
c++·python·华为·cann
码农小卡拉5 分钟前
深入解析Spring Boot文件加载顺序与加载方式
java·数据库·spring boot
向上的车轮13 分钟前
为什么.NET(C#)转 Java 开发时常常在“吐槽”Java:checked exception
java·c#·.net
Dragon Wu14 分钟前
Spring Security Oauth2.1 授权码模式实现前后端分离的方案
java·spring boot·后端·spring cloud·springboot·springcloud
跳动的梦想家h20 分钟前
环境配置 + AI 提效双管齐下
java·vue.js·spring
坚持就完事了22 分钟前
Java中的集合
java·开发语言
摘星编程25 分钟前
深入理解CANN ops-nn BatchNormalization算子:训练加速的关键技术
python
魔芋红茶26 分钟前
Python 项目版本控制
开发语言·python
wjhx31 分钟前
QT中对蓝牙权限的申请,整理一下
java·数据库·qt
lili-felicity32 分钟前
CANN批处理优化技巧:从动态批处理到流水线并行
人工智能·python