Yesterday I installed the Google Assistant SDK on my Raspberry Pi 4, Ii used this (https://developers.google.com/assistant/sdk/guides/service/python) tutorial from Google and wanted to make GPIO 25 to turn on and off via the onoff trait, explained in this section (https://developers.google.com/assistant/sdk/guides/service/python/extend/handle-device-commands).
But the way they did it, did not work for me and when I run the assistant and say "Turn on" the Gpio does not react in any way.
When running "pushtotalk.py" directly it will give you an Error output and it showed, that the device handler wasn't defined, even though it is right before the onoff function.
Here is my Code (Original from Google):
device_handler = device_helpers.DeviceRequestHandler(device_id)
GPIO.setmode(GPIO.BCM)
GPIO.setup(25, GPIO.OUT, initial=GPIO.LOW)
device_handler.command('action.devices.commands.OnOff')
def onoff(on):
if on:
logging.info('Turning device on')
GPIO.output(25, 1)
else:
logging.info('Turning device off')
GPIO.output(25, 0)
And here is the Error:
Traceback (most recent call last):
File "pushtotalk.py", line 465, in <module>
main()
File "/home/pi/env/lib/python3.7/site-packages/click/core.py", line 722, in __call__
return self.main(*args, **kwargs)
File "/home/pi/env/lib/python3.7/site-packages/click/core.py", line 697, in main
rv = self.invoke(ctx)
File "/home/pi/env/lib/python3.7/site-packages/click/core.py", line 895, in invoke
return ctx.invoke(self.callback, **ctx.params)
File "/home/pi/env/lib/python3.7/site-packages/click/core.py", line 535, in invoke
return callback(*args, **kwargs)
File "pushtotalk.py", line 425, in main
device_handler.command('action.devices.commands.OnOff')
UnboundLocalError: local variable 'device_handler' referenced before assignment
This way works really stable now and the device Handler is now recognized, even though I only changed the lines in the if statement, apparently there were problems with importing the GPIO module.
device_handler = device_helpers.DeviceRequestHandler(device_id)
@device_handler.command('action.devices.commands.OnOff')
def onoff(on):
if on:
logging.info('Turning device on')
os.system('python <Filename>.py')
else:
logging.info('Turning device off')
os.system('python <filename>.py')
That way you can easily activate a Python script with Google Assisant on eg. an Raspberry Pi by just saying "Turn on".