设置计时器 - 虚拟 IoT 硬件和 Raspberry Pi 在本课程的这一部分中,您将调用您的无服务器代码来理解语音,并根据结果在虚拟 IoT 设备或 Raspberry Pi 上设置一个计时器。 设置计时器 从语音转文本调用返回的文本需要发送到您的无服务器代码以供 LUIS 处理,获取用于计时器的秒数。这个秒数可以用来设置一个计时器。 可以使用 Python 的 类来设置计时器。该类接受延迟时间和一个函数,在延迟时间过后执行该函数。 任务 - 将文本发送到无服务器函数 在 VS Code 中打开 项目,并确保如果使用的是虚拟 IoT 设备,则在终端中加载了虚拟环境。
在本课程的这一部分中,您将调用您的无服务器代码来理解语音,并根据结果在虚拟 IoT 设备或 Raspberry Pi 上设置一个计时器。
从语音转文本调用返回的文本需要发送到您的无服务器代码以供 LUIS 处理,获取用于计时器的秒数。这个秒数可以用来设置一个计时器。
可以使用 Python 的 threading.Timer 类来设置计时器。该类接受延迟时间和一个函数,在延迟时间过后执行该函数。
在 VS Code 中打开 smart-timer 项目,并确保如果使用的是虚拟 IoT 设备,则在终端中加载了虚拟环境。
在 process_text 函数上方声明一个名为 get_timer_time 的函数来调用您创建的 REST 终端:
def get_timer_time(text):
在该函数中添加以下代码以定义要调用的 URL:
url = '<URL>'
将 <URL> 替换为您在上一课中构建的 REST 终端的 URL,无论是位于计算机上还是云端。
添加以下代码以将文本作为传递给调用的 JSON 属性:
body = { 'text': text } response = requests.post(url, json=body)
在此之下,从响应负载中检索 seconds,如果调用失败则返回 0:
if response.status_code != 200: return 0 payload = response.json() return payload['seconds']
成功的 HTTP 调用会返回 200 范围内的状态码,而您的无服务器代码会在处理并识别为设置计时器的意图时返回 200。
在文件顶部添加以下导入语句,以导入 Python 的 threading 库:
import threading
在 process_text 函数上方,添加一个用于说话的响应函数。目前这只会写入控制台,但在本课程的后续部分,它会说出文本。
def say(text): print(text)
在此之下,添加一个将在计时器完成后由计时器调用的函数:
def announce_timer(minutes, seconds): announcement = 'Times up on your ' if minutes > 0: announcement += f'{minutes} minute ' if seconds > 0: announcement += f'{seconds} second ' announcement += 'timer.' say(announcement)
该函数接收计时器的分钟数和秒数,并构建一个句子来宣布计时器已完成。它会检查分钟数和秒数,并仅在有数值时包括每个时间单位。例如,如果分钟数为 0,则仅在消息中包含秒数。然后将此句子发送给 say function.
Below this, add the following create_timer 函数以创建计时器:
def create_timer(total_seconds): minutes, seconds = divmod(total_seconds, 60) threading.Timer(total_seconds, announce_timer, args=[minutes, seconds]).start()
该函数接收将通过命令发送的计时器的总秒数,将其转换为分钟和秒,然后使用总秒数创建并启动一个计时器对象,传入 announce_timer function and a list containing the minutes and seconds. When the timer elapses, it will call the announce_timer function, and pass the contents of this list as the parameters - so the first item in the list gets passes as the minutes parameter, and the second item as the seconds parameter.
To the end of the create_timer 函数,并添加一些代码以构建一条消息告诉用户计时器即将开始:
announcement = '' if minutes > 0: announcement += f'{minutes} minute ' if seconds > 0: announcement += f'{seconds} second ' announcement += 'timer started.' say(announcement)
同样,只有在有值时才包括时间单位。这条消息随后会被发送给 say 函数。
在 process_text 函数末尾添加以下内容以从文本中获取计时器的时间,然后创建计时器:
seconds = get_timer_time(text) if seconds > 0: create_timer(seconds)
只有当秒数大于 0 时才会创建计时器。
运行应用程序,并确保函数应用也在运行。设置一些计时器,输出将显示计时器正在设置,并在计时器到期时显示:
pi@raspberrypi:~/smart-timer $ python3 app.py Set a two minute 27 second timer. 2 minute 27 second timer started. Times up on your 2 minute 27 second timer.
您可以在 code-timer/pi 或 code-timer/virtual-iot-device 文件夹中找到此代码。
您的计时器程序成功了!
声明:
本文件灏天文库团队进行了翻译。尽管我们力求准确,但请注意,翻译可能包含错误或不准确之处。原文档以其原始语言为准。我们不对因使用此翻译而产生的任何误解或误译负责。