一、树莓派启用摄像头
sudo raspi-config
选择Interfacing Options
→ Camera启用
二、编辑 /etc/modules-load.d/modules.conf 增加一行
bcm2835-v4l2
sudo nano /etc/modules-load.d/modules.conf
三、安装一些包
sudo apt-get install gstreamer1.0-tools gstreamer1.0-plugins-base gstreamer1.0-plugins-good gstreamer1.0-plugins-bad
四、创建一个Systemd服务
[Unit]
Description=Raspberry Pi Camera Stream Service
After=network.target
[Service]
Type=simple
User=你的用户名
ExecStartPre=/usr/bin/v4l2-ctl -c video_bitrate=4000000
ExecStart=/usr/bin/gst-launch-1.0 v4l2src ! video/x-h264,width=1280,height=720,framerate=30/1 ! h264parse config-interval=1 ! matroskamux streamable=true ! tcpserversink host=::0 port=9000 sync=false sync-method=2
[Install]
WantedBy=multi-user.target
$ sudo systemctl daemon-reload
$ sudo systemctl enable raspicam.service
$ sudo systemctl start raspicam.service
五、测试流是否打开
桌面版的Raspbian带有VLC播放器,可以直接在网络串流中输入tcp://<your-raspberry-ip>:9000来测试。帧数、分辨率等都可以在服务配置文件中更改。
六、HomeAssistant集成
1、编辑cameras.yaml
vi cameras.yaml
- platform: ffmpeg
name: Raspicam
input: tcp://<your-raspberry-ip>:9000
2、编辑shell_commands.yaml
vi shell_commands.yaml
record_raspicam_minute: ffmpeg -i tcp://<your-raspberry-ip>:9000 -an -c:v copy -t 00:01:00 /var/tmp/raspicam-{{ now().strftime("%Y-%m-%d_%H-%M-%S") }}.mkv
3、编辑automations.yaml
vi automations.yaml
- id: record_camera_on_motion
alias: Record some video if motion is detected while away
trigger:
- platform: template
value_template: "{{ is_state('binary.some_detector', 'on') }}"
condition:
- condition: template
value_template: "{{ not is_state('device_tracker.you', 'home') }}"
action:
- service: shell_command.record_raspicam_minute
4.编辑configuration.yaml
vi configuration.yaml
camera: !include cameras.yaml
automation: !include automations.yaml
shell_command: !include shell_commands.yaml
七、开启防火墙
$ sudo apt-get install ufw
$ sudo ufw allow ssh
$ sudo ufw allow from <your-home-assistant-host> to any port 9000 proto tcp
$ sudo ufw enable