Saturday, February 27, 2021

Much improved Pi Assistant message reader.

The most important improvement is that this program now works... 😎 

I just leave it running on the Pi Assistant, along with the Google provided assistant_library_with_button_demo.py program that I like to use, when I want to ask the Google Assistant something...

#!/usr/bin/python3
#
# Program to run on PiAssistant, to watch for newly arrived text files in
# /home/pi/Messages that it should speak, and delete them once it has.
import os
import paramiko
import time

path = "/home/pi/Messages/"

while True:
    with os.scandir(path) as entries:
        for entry in entries:
            f = open(entry, "r")
            content = f.read()
            f.close()
            command = "python ~/AIY-projects-python/src/aiy/voice/tts.py \"" + \
                      content + "\" --lang en-GB --volume 10 --pitch 60 --speed 90"
            os.system(command)
            os.remove(path+entry.name)      
            # Now wait for tts.py to finish
            command = "ps -ef | grep -v grep | grep \"voice.tts\" | wc -l"
            while True:
                ssh_stdin, ssh_stdout, ssh_stderr = ssh.exec_command(command)
                answer = str(ssh_stdout.read())
                if answer[2] == "0":
                break           
            time.sleep(0.5)
    time.sleep(0.5)

And here is a program to run on a cluster of Raspberry Pi computers, as say_who.py, which will each send a message to the Pi Assistant, from each core of the processor. The assistant will read them out, separately. It does seem still to lose some messages, and if I work out why, I will let you know! I have been searching for simple example programs for Raspberry Pi clusters on the internet for ages, and have not found very many. Here's my little gift...

#!/usr/bin/python3
from mpi4py import MPI
import os
import time
import subprocess as sp

# Attach to the cluster and find out who I am and what my rank is
comm = MPI.COMM_WORLD
my_rank = comm.Get_rank()
cluster_size = comm.Get_size()
my_host = os.popen('cat /etc/hostname').read().strip()
    
# Make something for the assistant to say
speech = "Host is  {} ".format(my_host)
speech = speech + "Rank {} ".format(my_rank)

# Make a unique filename and path
message = "/home/pi/" + my_host + str(my_rank)\
          + time.strftime("%H%M%S") + ".txt"
# Put the speech in the file
fp = open(message,"x")
fp.write(speech)
fp.close()

# Put a copy of the file on PiAssistant
cmd = "scp " + message + " pi@PiAssistant:/home/pi/Messages/"
sp.call(cmd,shell=True)
os.remove(message)

You would load that program on each of the Pi machines in your cluster, and then set it running using the command

mpiexec -n 16 -hostfile myhostfile python3 say_who.py

I'm assuming you have four Pi 3 machines in the cluster, hence the -n 16 parameter. 

#RaspberryPi #Cluster #Python

No comments: