這篇文章來源于DevicePlus.com英語網站的翻譯稿。
1. 目的
本教程旨在教您如何使用SiriControl開源Python框架在RaspberryPi項目中添加Siri功能和控制功能。
2. 概述
在本教程中,我將介紹如何設置和使用SiriControl Python框架。我將利用SiriControl模塊和Raspberry Pi 3來點亮和熄滅一個LED。學完本教程之后,您將能夠使用SiriControl將Siri語音命令添加到任何Raspberry Pi項目中。開始學習之前,請確保您擁有以下設備和材料,并確保已經安裝RaspberryPi且軟件能夠正常運行。
3. 設備
Raspberry Pi 3 – Raspberry Pi鏈接
HDMI線–HDMI線鏈接
LED – LED的Adafruit鏈接
鼠標 + 鍵盤 – 鍵盤/鼠標的Amazon鏈接
顯示器/TV – 任何帶HDMI接口的TV或顯示器
跳線 – 跳線的Amazon鏈接
Micro USB電纜 – Micro USB 電纜的Amazon鏈接
面包板 – 面包板的Amazon鏈接
4. 目錄
為SiriControl創建一個Gmail帳戶
iOS設備設置
SiriControl
設置SiriControl
創建自己的模塊
電路接線
上傳并運行程序
程序
1.0 為SiriControl創建一個Gmail帳戶
SiriControl模塊需要一個Gmail帳戶才能工作。我創建了一個新的Gmail帳戶,僅供SiriControl使用。我建議您也這樣做。這是一個好主意,因為Python腳本可以包含該帳戶的用戶名和密碼。
創建帳戶后,我們需要允許不太安全的應用程序訪問Gmail。這是因為Gmail服務器將Python腳本視為不太安全的應用程序。我們可以在Sign-in & Security(登錄和安全) 部分進行設置。
圖1:應用程序訪問(關閉)
圖2:應用程序訪問(開啟)
設置Gmail帳戶的最后一步是啟用IMAP協議。設置路徑如下: Gmail->Settings->Gear Part->Settings->Forwarding and POP/IMAP->IMAP Access.
圖3:IMAP(禁用)
圖4:IMAP(啟用)
2.0 iOS設備設置
將iOS設備上的“Notes”連至已經設置好與SiriControl配合使用的Gmail帳戶。選擇 Settings->Accounts & Passwords->Add Account(設置->帳戶和密碼->添加帳戶), 添加剛才設置好的Gmail帳戶。添加該帳戶后,選擇它并啟用Notes(圖6:Gmail帳戶下的Notes)。接下來,選擇 Settings->Notes,并啟用“On My iPhone” Account(我iPhone上的帳戶)。 然后,將 Default Account 改為Gmail帳戶。現在,我的iOS設備設置完畢。
圖5:帳戶和密碼
圖6:Gmail帳戶下的Notes
圖7:默認帳戶-Notes
3.0 Siri控制
3.1 設置SiriControl
要使用SiriControl,我們需要將模塊的資源庫克隆到RaspberryPi。要做到這一點,請打開終端窗口并輸入以下命令:
1. sudo apt-get update
2. sudo apt-get install git-core
3. git clone https://github.com/theraspberryguy/SiriControl-System
圖8:克隆資源庫
克隆資源庫之后,打開腳本siricontrol.py。在腳本中輸入Gmail帳戶的用戶名和密碼,然后保存腳本。
3.2 創建自己的模塊
Siricontrol.py 運行時,會從模塊(modules)文件夾中加載模塊腳本。執行不同的任務時,按照模板編寫新的模塊腳本很重要。因為我想控制一個LED,所以我寫了一個腳本來打開LED (LED_on.py) 和一個腳本來關閉LED (LED_off.py).
要制作自己的模塊,請在模板腳本中執行以下步驟:
1. 在“moduleName”中命名該模塊
2. 為模塊提供“commandWords”,以便讓Siri執行命令。
3. 在execute(command) 函數下寫入想要執行的功能。
4. 確保將腳本保存在模塊文件夾中。
4.0 連接電路
為了讓SiriControl執行命令,我搭建了一個簡單的LED電路。我總是喜歡用Fritzing繪制接線圖。Fritzing是一款開源原理圖設計和PCB布線軟件。Fritzing的下載地址(可選)如下:https://fritzing.org/home/
圖9:Raspberry Pi LED原理圖
LED和電阻應串聯在引腳11(GPIO17)和引腳25(地)之間。電阻的作用是限制流過LED的電流,并應根據您的LED進行相應調整,以防止電流過大將LED燒壞。請記住,LED較長的引線是正極,應連接到引腳11。
5.0 上傳并運行程序
完成上述步驟后,我使用以下命令運行SiriControl腳本:
python siricontrol.py
該腳本開始運行,并使用模塊文件夾中的所有模塊進行初始化。
圖10:執行LED點亮
圖11:執行LED熄滅
現在我命令Siri,“Note: Turn on LED(注意:打開LED)”,LED燈亮起,同時腳本會告訴我它執行了我的命令并且正在傾聽另一個命令。我現在說,“Note: Turn off LED(注意:關閉LED)”,LED熄滅。只要符合以下條件,該腳本就會執行我(不管在任何地方)對Siri發出的命令:
1. Raspberry Pi正在運行該腳本。
2. Raspberry Pi已連至互聯網,以便可以輪詢Gmail帳戶。
現在,您可以為任意Raspberry Pi項目添加任何SiriControl控制模塊。雖然我在這個項目中使用了Pi,但是該教程在安裝了Python的其他Linux開發板上同樣可以工作。
6.0 附件:腳本
6.1 Siricontrol.py
import time import imaplib import email import os import pkgutil ########################################## # Add your gmail username and password here username = "" password = "" ########################################## class ControlException(Exception): pass class Control(): def __init__(self, username, password): print("------------------------------------------------------") print("- SIRI CONTROL -") print("- Created by Sanjeet Chatterjee -") print("- Website: thereallycoolstuff.wordpress.com -") print("------------------------------------------------------") try: self.last_checked = -1 self.mail = imaplib.IMAP4_SSL("imap.gmail.com", 993) self.mail.login(username, password) self.mail.list() self.mail.select("Notes") # Gets last Note id to stop last command from executing result, uidlist = self.mail.search(None, "ALL") try: self.last_checked = uidlist[0].split()[-1] except IndexError: pass self.load() self.handle() except imaplib.IMAP4.error: print("Your username and password is incorrect") print("Or IMAP is not enabled.") def load(self): """Try to load all modules found in the modules folder""" print("n") print("Loading modules...") self.modules = [] path = os.path.join(os.path.dirname(__file__), "modules") directory = pkgutil.iter_modules(path=[path]) for finder, name, ispkg in directory: try: loader = finder.find_module(name) module = loader.load_module(name) if hasattr(module, "commandWords") and hasattr(module, "moduleName") and hasattr(module, "execute"): self.modules.append(module) print("The module '{0}' has been loaded, " "successfully.".format(name)) else: print("[ERROR] The module '{0}' is not in the " "correct format.".format(name)) except: print("[ERROR] The module '" + name + "' has some errors.") print("n") def fetch_command(self): """Retrieve the last Note created if new id found""" self.mail.list() self.mail.select("Notes") result, uidlist = self.mail.search(None, "ALL") try: latest_email_id = uidlist[0].split()[-1] except IndexError: return if latest_email_id == self.last_checked: return self.last_checked = latest_email_id result, data = self.mail.fetch(latest_email_id, "(RFC822)") voice_command = email.message_from_string(data[0][1].decode('utf-8')) return str(voice_command.get_payload()).lower().strip() def handle(self): """Handle new commands Poll continuously every second and check for new commands. """ print("Fetching commands...") print("n") while True: try: command = self.fetch_command() if not command: raise ControlException("No command found.") print("The word(s) '" + command + "' have been said") for module in self.modules: foundWords = [] for word in module.commandWords: if str(word) in command: foundWords.append(str(word)) if len(foundWords) == len(module.commandWords): try: module.execute(command) print("The module {0} has been executed " "successfully.".format(module.moduleName)) except: print("[ERROR] There has been an error " "when running the {0} module".format( module.moduleName)) else: print("n") except (TypeError, ControlException): pass except Exception as exc: print("Received an exception while running: {exc}".format( **locals())) print("Restarting...") time.sleep(1) if __name__ == '__main__': Control(username, password)
6.2 Led_on.py
#You can import any modules required here
import RPi.GPIO as GPIO #import GPIO module
import time
#This is name of the module – it can be anything you want
moduleName = “LED_on”
#These are the words you must say for this module to be executed
commandWords = [“turn”, “on”, “led”]
#This is the main function which will be execute when the above command words are said
def execute(command):
LED = 11 # Set LED pin to pin 11
GPIO.setmode(GPIO.BOARD)
GPIO.setup(LED, GPIO.OUT) #configure LED as an output
print(“n”)
print(“LED is On.”)
6.3 Led_off.py
#You can import any modules required here
import RPi.GPIO as GPIO #import GPIO module
import time
#This is name of the module – it can be anything you want
moduleName = “LED_off”
#These are the words you must say for this module to be executed
commandWords = [“turn”, “off”, “led”]
#This is the main function which will be execute when the above command words are said
def execute(command):
LED = 11 # Set LED pin to pin 11
GPIO.setmode(GPIO.BOARD)
GPIO.setup(LED, GPIO.OUT) #configure LED as an output
print(“n”)
print(“LED is off.”)
GPIO.output(LED, GPIO.LOW) #turn LED on
審核編輯:湯梓紅
-
led
+關注
關注
242文章
23593瀏覽量
668565 -
HDMI
+關注
關注
32文章
1802瀏覽量
153982
發布評論請先 登錄
相關推薦
如何在Raspberry Pi上安裝TensorFlow

如何在Raspbian上設置沒有顯示器和鍵盤的Raspberry Pi

如何使用Raspberry pi和Python來控制Arduino

如何在基于Raspberry Pi的項目中使用霍爾傳感器

基于Raspberry Pi 5的蜂窩物聯網項目

安裝Raspberry Pi Clock Hat的教程分享
分享一個不錯的Raspberry Pi串行控制臺迷你帽項目
分享在Raspberry Pi項目中添加Siri控制的方案設計

如何在Raspberry Pi Pico中使用OLED顯示器

基于諾基亞5110的Raspberry Pi帽子
在Raspberry Pi上模擬Commodore Amiga

如何在Raspberry Pi零2W上阻止帶有Pi孔的廣告

評論