0
  • 聊天消息
  • 系统消息
  • 评论与回复
登录后你可以
  • 下载海量资料
  • 学习在线课程
  • 观看技术视频
  • 写文章/发帖/加入社区
创作中心

完善资料让更多小伙伴认识你,还能领取20积分哦,立即完善>

3天内不再提示

如何在Raspberry Pi项目中添加Siri控制

贾永世 来源:大洼球王 作者:大洼球王 2023-02-27 10:27 次阅读

这篇文章来源于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(登录和安全) 部分进行设置。

poYBAGPzJZ-AY-KWAABeQAGI8uQ997.jpg

图1:应用程序访问(关闭)

poYBAGPzJaGASqkQAABdsc2xRCE538.jpg

图2:应用程序访问(开启)

设置Gmail帐户的最后一步是启用IMAP协议。设置路径如下: Gmail->Settings->Gear Part->Settings->Forwarding and POP/IMAP->IMAP Access.

pYYBAGPzJaKAdTbgAADT_NM49WM959.jpg

图3:IMAP(禁用)

pYYBAGPzJaSAevnSAADj-bkeYpc407.jpg

图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设备设置完毕。

poYBAGPzJaWAbNNGAACL6B9dmNw095.jpg

图5:帐户和密码

pYYBAGPzJaeADsD-AACTrO_DgGk360.jpg

图6:Gmail帐户下的Notes

poYBAGPzJamASxKjAABTjOPAc0c016.jpg

图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

pYYBAGPzJaqAEnFAAAGAWjSxfsA313.jpg

图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/

poYBAGPzJayADcTXAAD9UJf0q74715.jpg

图9:Raspberry Pi LED原理图

LED和电阻应串联在引脚11(GPIO17)和引脚25(地)之间。电阻的作用是限制流过LED的电流,并应根据您的LED进行相应调整,以防止电流过大将LED烧坏。请记住,LED较长的引线是正极,应连接到引脚11。

5.0 上传并运行程序

完成上述步骤后,我使用以下命令运行SiriControl脚本:

python siricontrol.py

该脚本开始运行,并使用模块文件夹中的所有模块进行初始化。

pYYBAGPzJa2AEnEyAAC7fripAaU435.jpg

图10:执行LED点亮

poYBAGPzJa-Aav6kAAGeBf2KGbc255.jpg

图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
    led
    +关注

    关注

    237

    文章

    22450

    浏览量

    645891
  • HDMI
    +关注

    关注

    32

    文章

    1489

    浏览量

    149753
收藏 人收藏

    评论

    相关推荐

    何在Raspberry Pi上安装TensorFlow

     在本教程中,我们将学习如何在 Raspberry Pi 上安装 TensorFlow,并将展示一些在预训练神经网络上进行简单图像分类的示例。
    发表于 09-01 16:35 1740次阅读
    如<b class='flag-5'>何在</b><b class='flag-5'>Raspberry</b> <b class='flag-5'>Pi</b>上安装TensorFlow

    何在Raspbian上设置没有显示器和键盘的Raspberry Pi

    在本教程中,我们将了解如何在新安装的 Raspbian 上设置没有显示器和键盘的 Raspberry Pi
    发表于 09-22 16:31 1094次阅读
    如<b class='flag-5'>何在</b>Raspbian上设置没有显示器和键盘的<b class='flag-5'>Raspberry</b> <b class='flag-5'>Pi</b>

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

    如果你同时拥有Arduino和Raspberry pi板,本文将向您展示如何使用Raspberry pi和Python来控制Arduino。
    的头像 发表于 11-08 16:51 3970次阅读
    如何使用<b class='flag-5'>Raspberry</b> <b class='flag-5'>pi</b>和Python来<b class='flag-5'>控制</b>Arduino

    何在基于Raspberry Pi项目中使用霍尔传感器

    汽车行业产品中的速度、位置和距离。霍尔传感器的多功能性使其成为制造商和电气工程师的必备品,这就是为什么今天,我将向我们展示如何在基于 Raspberry Pi项目中使用霍尔传感器。
    的头像 发表于 11-16 17:16 1926次阅读
    如<b class='flag-5'>何在</b>基于<b class='flag-5'>Raspberry</b> <b class='flag-5'>Pi</b>的<b class='flag-5'>项目中</b>使用霍尔传感器

    基于Raspberry Pi 5的蜂窝物联网项目

    今天小拜年给大家带来的是来自美国的Maker Rob Lauer的基于树莓派5的蜂窝网络项目,了解如何为新的 Raspberry Pi 5 单板计算机添加低带宽蜂窝连接。
    的头像 发表于 12-25 10:55 695次阅读
    基于<b class='flag-5'>Raspberry</b> <b class='flag-5'>Pi</b> 5的蜂窝物联网<b class='flag-5'>项目</b>

    如何添加GPS时间和位置至Raspberry Pi 项目

    以下,欧时电子工程师将详细描述如何在Raspberry Pi 项目添加GPS时间和位置。向 Raspbe
    发表于 01-25 15:57

    安装Raspberry Pi Clock Hat的教程分享

    Raspberry Pi 系统的关键参数,例如时间、日期、CPU 使用率、CPU 温度、网络 IP等。除此之外,它还允许您通过板载大头钉按钮控制一些基本操作,例如关机和重启。这个项目
    发表于 07-05 06:01

    分享一个不错的Raspberry Pi串行控制台迷你帽项目

    描述Raspberry Pi串行控制台迷你帽该项目包含带有 USB 到 UART 转换器的 Mini-HAT,连接到 Raspberry
    发表于 09-01 06:03

    何在Raspberry Pi 3上安装OpenCV4库

    今天我们将学习如何在 Raspberry Pi 3 上安装 OpenCV4 库,以便我们可以将其用于计算机视觉应用程序。这将允许 OpenCV 在像 Pi 这样的便携式设备上运行,从而
    的头像 发表于 09-08 16:09 1370次阅读
    如<b class='flag-5'>何在</b><b class='flag-5'>Raspberry</b> <b class='flag-5'>Pi</b> 3上安装OpenCV4库

    何在Raspberry Pi Pico中使用OLED显示器

    电子发烧友网站提供《如何在Raspberry Pi Pico中使用OLED显示器.zip》资料免费下载
    发表于 10-18 09:15 4次下载
    如<b class='flag-5'>何在</b><b class='flag-5'>Raspberry</b> <b class='flag-5'>Pi</b> Pico中使用OLED显示器

    Raspberry Pi上模拟Commodore Amiga

    现在,您只要使用一个Raspberry Pi就可以轻松实现对Amiga的探索!在本项目中,您可以使用任意Pi,但是为了获得更好的性能,Raspber
    的头像 发表于 02-25 17:29 700次阅读
    在<b class='flag-5'>Raspberry</b> <b class='flag-5'>Pi</b>上模拟Commodore Amiga

    基于Raspberry Pi的DIY面部识别功能

    目的:本教程的目的在于展示如何在Raspberry Pi项目中添加面部识别功能。注意:该面部识别门锁设计并不应该被应用于保护或锁定任何有价值
    的头像 发表于 02-24 18:25 477次阅读
    基于<b class='flag-5'>Raspberry</b> <b class='flag-5'>Pi</b>的DIY面部识别功能

    寻找实用的Raspberry Pi项目? 制作一个智能伞架!

    本教程将分步指导您如何制作一个智能伞架。这是我最喜欢的Raspberry Pi 项目之一。
    的头像 发表于 02-24 17:22 689次阅读
    寻找实用的<b class='flag-5'>Raspberry</b> <b class='flag-5'>Pi</b><b class='flag-5'>项目</b>? 制作一个智能伞架!

    何在Raspberry Pi零2W上阻止带有Pi孔的广告

    电子发烧友网站提供《如何在Raspberry Pi零2W上阻止带有Pi孔的广告.zip》资料免费下载
    发表于 06-14 10:38 0次下载
    如<b class='flag-5'>何在</b><b class='flag-5'>Raspberry</b> <b class='flag-5'>Pi</b>零2W上阻止带有<b class='flag-5'>Pi</b>孔的广告

    Raspberry Pi添加15美元的显示器

    电子发烧友网站提供《为Raspberry Pi添加15美元的显示器.zip》资料免费下载
    发表于 06-20 11:04 0次下载
    为<b class='flag-5'>Raspberry</b> <b class='flag-5'>Pi</b><b class='flag-5'>添加</b>15美元的显示器