上一篇介紹了一個串流網站的應用,在設定上比較複雜,對於新手來說並不太容易成功。如果只是想要監看畫面的話,其實有一個更簡單的作法,就是利用Apache2網頁伺服器以及定時執行的cron功能就可以了。也就是先建立一個WWW網頁伺服器,讓它每隔一段時間(5分鐘)就自動重新整理一次,而再利用cron每5分鐘啟動一個Python程式透過相機拍照存檔,就可以搞定了。要在Raspberry安裝Apache2很簡單,只要以下這兩行指定就可以了:
$ sudo apt-get update $ sudo apt-get -y install apache2
安裝完畢之後,在/var/www/html之下,把原有的index.html刪除,然後建立一個自己的index.html,由於權限的關係,請記得要使用sudo指定才行(sudo vi index.html)。
<!DOCTYPE html> <html> <head> <meta charset='utf-8'> <script> function timedRefresh(timeoutPeriod) { setTimeout("location.reload(true);", timeoutPeriod); } </script> <title> Welcome to Raspberry Site </title> </head> <body onload="JavaScript:timedRefresh(300000);"> <h2> Welcome to Raspberry Site </h2> <hr> <img src='images/lab.jpg' width=640> </body> </html>
然後在/var/www/html目錄下編寫一個Python程式,假設叫做takepic.py。這個程式使用picamera啟用Raspberry的相機,拍攝一張照片之後,把相片存在images/資料夾下,命名為lab.jpg,接著再使用PIL模組把目前的日期以及時間印上去。由於ImageFont需要一個TrueType的ttf檔案,可以到網路上去下載一個免費的字型檔。
#! /usr/bin/python import picamera import datetime from PIL import Image, ImageDraw, ImageFont cam = picamera.PiCamera() cam.vflip = True cam.hflip = True cam.capture('/var/www/html/images/lab.jpg') cam.close() font = ImageFont.truetype('/var/www/html/open24.ttf', 20) img = Image.open('/var/www/html/images/lab.jpg') draw = ImageDraw.Draw(img) now = str(datetime.datetime.now()) draw.text((10,10),now, font=font, fill=(255,255,255,128)) img.save('/var/www/html/images/lab.jpg')
有了這個檔案之後,再使用sudo crontab -e 去編輯目前的定期排程,讓它可以每隔5分鐘執行一次takepic.py就可以了,設定如下:
*/5 * * * * /var/www/html/takepic.py
如此這般,就完成了。之後連線到Raspberry Pi的網址,就可以看到每5分鐘更新一次的監看照片了。以下是網頁看起來的樣子:
(3579)
近期留言