logo-mobile

ROHM

ROHM
Menu
  • Arduino –
  • Raspberry Pi –
  • Trending –
  • Others –
  • About –
  • Contact –

Raspberry Pi

How to Add Siri Control to Your Raspberry Pi Project

DevicePlus Editorial Team
Published by DevicePlus Editorial Team at March 13, 2018
Categories
  • Raspberry Pi
Tags
  • diy
  • IoT
  • raspberry pi
  • Siri
  • smart home

1. Purpose
The purpose of this tutorial is to teach you how to use the SiriControl open-source Python framework to add Siri functionality and control to RaspberryPi Projects.

2. Overview

In this tutorial, I go over how to set up and use the SiriControl Python framework. I use the SiriControl module with a Raspberry Pi 3 to flash an LED on and off. After the tutorial, you will be able to use SiriControl to add Siri voice commands to any Raspberry Pi project. Before continuing, make sure you have the following equipment and materials and that your RaspberryPi is set up and running.

3. Equipment

  1. Raspberry Pi 3 – Link for Raspberry Pi
  2. HDMI Cable –Link for HDMI Cable
  3. LED – Link for LEDs from Adafruit
  4. Mouse + Keyboard – Amazon Link for Keyboard/Mouse
  5. Monitor/TV – Any TV or monitor with HDMI
  6. Jumper Wires – Amazon Link for Jumper Wires
  7. Micro USB Cable – Amazon Link for Micro USB Cable
  8. Breadboard – Amazon Link for Breadboard

4. Table of Contents

  1. Setting up a Gmail Account for SiriControl
  2. iOS Device Setup
  3. SiriControl
    1. Setting Up SiriControl
    2. Create Your Own Module
  4. Wiring the Circuit
  5. Uploading and Running the Code

Procedure

1.0 Setting up a Gmail Account for SiriControl

The SiriControl module requires a Gmail account to work. I set up a new Gmail account just for use with SiriControl and suggest doing the same. This is a good idea because the Python script will have the username and password for this account in it.

Once an account is created I allow less secure apps access to Gmail. This is because the Gmail server views the Python script as a less secure app. I do this under the Sign-in & Security section for my account.

Figure 1: App. Access (Off)

Figure 2: App. Access (On)

The last step of setting up your Gmail account is to enable IMAP protocol. This can be done under Gmail->Settings->Gear Part->Settings->Forwarding and POP/IMAP->IMAP Access.

Figure 3: IMAP (Disabled)

Figure 4: IMAP (Enabled)

2.0 IOS Device Setup

Connect “Notes” on your iOS device to the Gmail account set up to be used with SiriControl. I go to Settings->Accounts & Passwords->Add Account and add the Gmail account I just set up. After adding that account, I select it and enable notes (Figure 6: Notes Under Gmail Account). Next, I go to Settings->Notes and enable “On My iPhone” Account. I then change my Default Account to the Gmail Account. My iOS device is now set up.

Figure 5: Account & Passwords

Figure 6: Notes Under Gmail Account

Figure 7: Default Account – Notes

3.0 Siri Control

3.1 Setting Up SiriControl

To use SiriControl I clone the repository for the module to my RaspberryPi. To do this I open the terminal window and enter the following commands:

1. sudo apt-get update
2. sudo apt-get install git-core
3. git clone https://github.com/theraspberryguy/SiriControl-System

Figure 8: Cloning Repository

After cloning the repository, I open the script: siricontrol.py. Inside the script I entered my Gmail account username and password and save the script.

3.2 Create Your Own Module

Siricontrol.py works by loading module scripts from the modules folder. It is important to follow the template when writing new module scripts to perform different tasks. Because I am controlling an LED, I write one script to turn the LED on (LED_on.py) and one script to turn the LED off (LED_off.py).

To make your own module, follow the steps below within a template script:

1. Name the module in “moduleName”
2. Give the module “commandWords” that you need to give to Siri to execute a command.
3. Write the function you want executed under execute(command) function.
4. Make sure you save your script in the modules folder.

4.0 Wiring the Circuit

The circuit I set up SiriControl to command is a simple LED circuit. I always like to make a wiring diagram () using Fritzing, an open-source schematic capture and PCB routing software. You can download Fritzing using the following link (optional): http://fritzing.org/home/

Figure 9: Raspberry Pi LED Schematic

The LED and resistor should be connected in series between Pin 11 (GPIO17) and Pin 25 (Ground). The resistor is there to limit current through the LED and should be sized accordingly depending on your LED to prevent burning it out. Remember the longer lead on the LED is positive and should be connected to Pin 11.

5.0 Uploading and Running the Code

After completing all the steps, I run the SiriControl script with the following command:

python siricontrol.py

The script starts running and should initialize with all the modules in the module folder.

Figure 10: LED On Executing

Figure 11: LED Off Executing

Now I command Siri, “Note: Turn on LED,” and my LED turns on while the script tells me it executed the command and is listening for another. I now say, “Note: Turn off LED,” and the LED is turned off. The script will execute the commands I give to Siri from anywhere in the world as long as:

1. The script is running on the Raspberry Pi.
2. The Raspberry Pi is connected to the Internet so that it can poll the Gmail account.

You can now add any modules you want to add SiriControl to any Raspberry Pi projects. Although I used a Pi for this project, this should work on other Linux Development boards with Python installed.

6.0 Appendix: Scripts

6.1 Siricontrol.py

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
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

DevicePlus Editorial Team
DevicePlus Editorial Team

Check us out on Social Media

  • Facebook
  • Twitter

Recommended Posts

  • How to integrate an RFID module with Raspberry PiHow to integrate an RFID module with Raspberry Pi
  • DIY Tip: How to Set Up Your Raspberry PiDIY Tip: How to Set Up Your Raspberry Pi
  • Raspberry Pi WebIOPi IOT – Full-Color LED Christmas DecorationRaspberry Pi WebIOPi IOT – Full-Color LED Christmas Decoration
  • Want to Make DIY Internet of Things Projects?Want to Make DIY Internet of Things Projects?
  • DIY Smart Picture Frame & Calendar Using Raspberry Pi 3 – PART 1DIY Smart Picture Frame & Calendar Using Raspberry Pi 3 – PART 1
  • Latest Smart Home Products & Innovation Awards from CES 2017Latest Smart Home Products & Innovation Awards from CES 2017
Receive update on new postsPrivacy Policy

Recommended Tutorials

  • How to integrate an RFID module with Raspberry Pi How to integrate an RFID module with Raspberry Pi
  • How to Use the NRF24l01+ Module with Arduino How to Use the NRF24l01+ Module with Arduino
  • How to Run Arduino Sketches on Raspberry Pi How to Run Arduino Sketches on Raspberry Pi
  • Setting Up Raspberry Pi as a Home Media Server Setting Up Raspberry Pi as a Home Media Server

Recommended Trends

  • SewBot Is Revolutionizing the Clothing Manufacturing Industry SewBot Is Revolutionizing the Clothing Manufacturing Industry
  • All About The Sumo Robot Competition And Technology All About The Sumo Robot Competition And Technology
  • 5 Interesting Tips to Calculating the Forward Kinematics of a Robot 5 Interesting Tips to Calculating the Forward Kinematics of a Robot
  • Go Inside the Drones That Are Changing Food Delivery Go Inside the Drones That Are Changing Food Delivery
Menu
  • Arduino –
    Arduino Beginner’s Guide
  • Raspberry Pi –
    Raspberry Pi Beginner's Guide
  • Trending –
    Updates on New Technologies
  • Others –
    Interviews / Events / Others

Check us out on Social Media

  • Facebook
  • Twitter
  • About
  • Company
  • Privacy Policy
  • Terms of Service
  • Contact
  • Japanese
  • 简体中文
  • 繁體中文
Don’t Forget to Follow Us!
© Copyright 2016-2023. Device Plus - Powered by ROHM
© 2023 Device Plus. All Rights Reserved. Muffin group

istanbul escort istanbul escort istanbul escort