I have an error when I run my custom voice assistant program on Raspberry Pi 3B .This script is made from two programs from examples(assistant_library_demo.py and cloud_speech.py).Consequently the script does the both functions from those examples.
This is how the program code looks like:
import argparse
import locale
import logging
import RPi.GPIO as GPIO
from gpiozero import Servo
import signal
import sys
from google.assistant.library.event import EventType
from aiy.assistant import auth_helpers
from aiy.assistant.library import Assistant
from aiy.board import Board, Led
from aiy.cloudspeech import CloudSpeechClient
import aiy.voice.tts
def get_hints(language_code):
if language_code.startswith('en_'):
return ('turn on the light',
'turn off the light',
'blink the light',
'goodbye',
'repeat after me',
'lights on',
'lights off',
'minimum',
'middle',
'maximum')
return None
def locale_language():
language, _ = locale.getdefaultlocale()
return language
def process_event(led, event):
logging.basicConfig(level=logging.INFO)
GPIO.setmode(GPIO.BCM)
GPIO.setwarnings(False)
GPIO.setup(24,GPIO.OUT)
servo = Servo(6)
parser = argparse.ArgumentParser(description='Assistant service example.')
parser.add_argument('--language', default=locale_language())
args = parser.parse_args()
logging.info('Initializing for language %s...', args.language)
hints = get_hints(args.language)
client = CloudSpeechClient()
logging.info(event)
text = client.recognize(language_code=args.language,hint_phrases=hints)
if 'lights on' in text:
GPIO.output(24,GPIO.HIGH)
elif 'lights off' in text:
GPIO.output(24,GPIO.LOW)
elif 'maximum' in text:
servo.max()
elif 'minimum' in text:
servo.min()
elif 'middle' in text:
servo.mid()
if event.type == EventType.ON_START_FINISHED:
led.state = Led.BEACON_DARK # Ready.
logging.info('Say "OK, Google" then speak, or press Ctrl+C to quit...')
elif event.type == EventType.ON_CONVERSATION_TURN_STARTED:
led.state = Led.ON # Listening.
elif event.type == EventType.ON_END_OF_UTTERANCE:
led.state = Led.PULSE_QUICK # Thinking.
elif (event.type == EventType.ON_CONVERSATION_TURN_FINISHED
or event.type == EventType.ON_CONVERSATION_TURN_TIMEOUT
or event.type == EventType.ON_NO_RESPONSE):
led.state = Led.BEACON_DARK
elif event.type == EventType.ON_ASSISTANT_ERROR and event.args and
event.args['is_fatal']:
main()
def main():
credentials = auth_helpers.get_assistant_credentials()
with Board() as board, Assistant(credentials) as assistant:
for event in assistant.start():
process_event(board.led, event)
if name == 'main':
main()
This is how error text looks like:
The error text when i run the sketch from python shell:
Backend terminated (returncode: -11) Fatal Python error: Segmentation
fault
Thread 0x580fe470 (most recent call first):
File "/usr/lib/python3.5/threading.py", line 297 in wait File
"/usr/lib/python3.5/threading.py", line 549 in wait File
"/opt/aiy/projects-python/src/aiy/board.py", line 208 in _run File
"/usr/lib/python3.5/threading.py", line 862 in run File
"/usr/lib/python3.5/threading.py", line 914 in _bootstrap_inner File
"/usr/lib/python3.5/threading.py", line 882 in _bootstrap
Thread 0x76f66640 (most recent call first): File
"/usr/local/lib/python3.5/dist-packages-linux-armv7l/google/assistant/library/assistant.py", line 114 in exit File
"/opt/aiy/projects-python/src/examples/voice/myassistant.py", line 96
in main File
"/opt/aiy/projects-python/src/examples/voice/myassistant.py", line 99
in File "/usr/lib/python3/dist-packages/thonny/backend.py", line 1232
in _execute_prepared_user_code File
"/usr/lib/python3/dist-packages/thonny/backend.py", line 1158 in
wrapper File "/usr/lib/python3/dist-packages/thonny/backend.py", line
1171 in wrapper File
"/usr/lib/python3/dist-packages/thonny/backend.py", line 1219 in
execute_source File
"/usr/lib/python3/dist-packages/thonny/backend.py", line 853 in
_execute_source File "/usr/lib/python3/dist-packages/thonny/backend.py", line 840 in
_execute_file File "/usr/lib/python3/dist-packages/thonny/backend.py", line 400 in _cmd_Run File
"/usr/lib/python3/dist-packages/thonny/backend.py", line 217 in
handle_command File
"/usr/lib/python3/dist-packages/thonny/backend.py", line 162 in
mainloop File
"/usr/lib/python3/dist-packages/thonny/backend_launcher.py", line 70
in Use 'Stop/Restart' to restart the backend ...
The error text when I run the sketch from terminal:
Segmentation fault
I tried to search for this error in the web, but it gave no actual results. I hope you will help me to solve this issue.
Related
from cryptofeed import FeedHandler
from cryptofeed.feed import Feed
from cryptofeed.defines import L2_BOOK, BID, ASK
from cryptofeed.exchange.ftx import FTX
from threading import Thread
from time import sleep
class Executor:
def __init__(self, feed: Feed, coin_symbol: str, fut_symbol: str):
self.coin_symbol = coin_symbol
self.fut_symbol = fut_symbol
self.feed = feed
self.fh = FeedHandler()
self.loop = None
self._coin_top_book: dict = {}
self._fut_top_book: dict = {}
async def _book_update(self, feed, symbol, book, timestamp, receipt_timestamp):
if symbol == self.coin_symbol:
self._coin_top_book[BID] = book[BID].peekitem(-1)
self._coin_top_book[ASK] = book[ASK].peekitem(0)
elif symbol == self.fut_symbol:
self._fut_top_book[BID] = book[BID].peekitem(-1)
self._fut_top_book[ASK] = book[ASK].peekitem(0)
def start_feed(self):
self.fh.add_feed(self.feed(symbols=[self.fut_symbol, self.coin_symbol], channels=[L2_BOOK],
callbacks={L2_BOOK: self._book_update}))
self.fh.run()
def shoot(self):
# give the orderbooks time to be populated
while len(self._coin_top_book) == 0 or len(self._fut_top_book) == 0:
sleep(1)
for i in range(5):
print(self._coin_top_book)
sleep(1) # do some stuff
self.fh.stop()
def run(self):
th1 = Thread(target=self.shoot)
th1.start()
self.start_feed()
def main():
g = Executor(feed=FTX, coin_symbol='SOL-USD', fut_symbol='SOL-PERP')
g.run()
if __name__ == '__main__':
main()
So in my current attempt to stop this program, I call self.fh.stop() when things are finished inside shoot(). However, I get this error:
Exception in thread Thread-1:
Traceback (most recent call last):
File "/Users/mc/.pyenv/versions/3.9.1/lib/python3.9/threading.py", line 954, in _bootstrap_inner
self.run()
File "/Users/mc/.pyenv/versions/3.9.1/lib/python3.9/threading.py", line 892, in run
self._target(*self._args, **self._kwargs)
File "/Users/mc/Library/Application Support/JetBrains/PyCharmCE2021.2/scratches/scratch_1.py", line 43, in shoot
self.fh.stop()
File "/Users/mc/.virtualenvs/crypto/lib/python3.9/site-packages/cryptofeed/feedhandler.py", line 175, in stop
loop = asyncio.get_event_loop()
File "/Users/mc/.pyenv/versions/3.9.1/lib/python3.9/asyncio/events.py", line 642, in get_event_loop
raise RuntimeError('There is no current event loop in thread %r.'
RuntimeError: There is no current event loop in thread 'Thread-1'.
Presumably it's because I'm trying to access the event loop from the child thread whereas it only exists in the parent thread. However, I don't know how to handle this properly.
I am making a bot that makes the chrome dinosaur jump every time it sees a cactus.
The RGB for the cactus is (83,83,83)
I made a specific coordinate for my code to look at, and check if the RGB of that pixel matches the cactus (jump_place)
However, when I run it, it works for about 2 seconds, and then gives me this error:
Traceback (most recent call last):
File "c:\Users\dofia\OneDrive\Desktop\coding VS\Other Projects\DINO BOT\tempCodeRunnerFile.py", line 29, in <module>
if pyautogui.pixel(810, 635)[0] == 83:
File "C:\Users\dofia\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.9_qbz5n2kfra8p0\LocalCache\local-packages\Python39\site-packages\pyscreeze\__init__.py", line 584, in pixel
return (r, g, b)
File "C:\Program Files\WindowsApps\PythonSoftwareFoundation.Python.3.9_3.9.496.0_x64__qbz5n2kfra8p0\lib\contextlib.py", line 124, in __exit__
next(self.gen)
File "C:\Users\dofia\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.9_qbz5n2kfra8p0\LocalCache\local-packages\Python39\site-packages\pyscreeze\__init__.py", line 113, in __win32_openDC
raise WindowsError("windll.user32.ReleaseDC failed : return 0")
OSError: windll.user32.ReleaseDC failed : return 0
Here is my code:
from pyautogui import *
import pyautogui
import time
import keyboard
import random
time.sleep(3)
replay = (1127,591)
jump_place = (866,630)
def restart():
pyautogui.click(replay)
def jump():
pyautogui.keyDown('space')
time.sleep(0.5)
print("Jump!")
pyautogui.keyUp('space')
restart()
while keyboard.is_pressed('p') == False:
if pyautogui.pixel(810, 635)[0] == 83:
jump()
Is there anything I am doing wrong?
The link to the dinosaur game is: http://www.trex-game.skipser.com/
I'm really new to python and I don't even know if the title of this python question is even right. Anyways I'm facing an error code that I have been trying to find a fix for in the last couple of hours. The error goes like this: raise RuntimeError("threads can only be started once").
Now I googled the error and I got a couple of solutions. I tried a couple of them and none of them seem to work. I know that you cannot use the start function for more than one time, But how else am I supposed to get my script to work again?
import pyautogui, requests, pyperclip
from pynput import mouse, keyboard
from tkinter import filedialog
url = "https://poxgur.com/"
file_path = filedialog.asksaveasfilename(defaultextension='.png')
def on_click(x, y, button, pressed):
global currentMouseX, currentMouseY
if pressed:
currentMouseX, currentMouseY = x, y
if not pressed:
mouse_listener.stop()
im = pyautogui.screenshot(region=(
currentMouseX, currentMouseY, abs(currentMouseX - x), abs(currentMouseY - y)))
im.save(file_path)
print(file_path)
files = {"file": open(file_path, "rb")}
r = requests.post(url + "api.php", files=files)
pyperclip.copy(url + r.text + ".png")
# os.remove(file_path)
mouse_listener.stop()
return False
mouse_listener = mouse.Listener(on_click=on_click)
def on_scroll_lock_release(key):
if key == keyboard.Key.scroll_lock:
if not mouse_listener.is_alive():
mouse_listener.start()
with keyboard.Listener(on_release=on_scroll_lock_release) as listener:
listener.join()
The error meesage:
Unhandled exception in listener callback
Traceback (most recent call last):
File "C:\Users\marti\anaconda3\envs\The 100 Projects\lib\site-packages\pynput\_util\__init__.py", line 162, in inner
return f(self, *args, **kwargs)
File "C:\Users\marti\anaconda3\envs\The 100 Projects\lib\site-packages\pynput\keyboard\_win32.py", line 283, in _process
self.on_release(key)
File "C:\Users\marti\anaconda3\envs\The 100 Projects\lib\site-packages\pynput\_util\__init__.py", line 78, in inner
if f(*args) is False:
File "C:/Users/marti/Documents/PythonProjects/Acutal Projects/The 100 Projects/Screenshot2.0.py", line 33, in on_scroll_lock_release
mouse_listener.start()
File "C:\Users\marti\anaconda3\envs\The 100 Projects\lib\threading.py", line 848, in start
raise RuntimeError("threads can only be started once")
RuntimeError: threads can only be started once
Traceback (most recent call last):
File "C:/Users/marti/Documents/PythonProjects/Acutal Projects/The 100 Projects/Screenshot2.0.py", line 37, in <module>
listener.join()
File "C:\Users\marti\anaconda3\envs\The 100 Projects\lib\site-packages\pynput\_util\__init__.py", line 210, in join
six.reraise(exc_type, exc_value, exc_traceback)
File "C:\Users\marti\anaconda3\envs\The 100 Projects\lib\site-packages\six.py", line 702, in reraise
raise value.with_traceback(tb)
File "C:\Users\marti\anaconda3\envs\The 100 Projects\lib\site-packages\pynput\_util\__init__.py", line 162, in inner
return f(self, *args, **kwargs)
File "C:\Users\marti\anaconda3\envs\The 100 Projects\lib\site-packages\pynput\keyboard\_win32.py", line 283, in _process
self.on_release(key)
File "C:\Users\marti\anaconda3\envs\The 100 Projects\lib\site-packages\pynput\_util\__init__.py", line 78, in inner
if f(*args) is False:
File "C:/Users/marti/Documents/PythonProjects/Acutal Projects/The 100 Projects/Screenshot2.0.py", line 33, in on_scroll_lock_release
mouse_listener.start()
File "C:\Users\marti\anaconda3\envs\The 100 Projects\lib\threading.py", line 848, in start
raise RuntimeError("threads can only be started once")
RuntimeError: threads can only be started once
Process finished with exit code 1
A possible solution would be to intialize a new Listener each time before starting the Listener.
You could re-code your solution in the following way:
mouse_listener = mouse.Listener(on_click=on_click)
def on_scroll_lock_release(key):
if key == keyboard.Key.scroll_lock:
if not mouse_listener.is_alive():
mouse_listener = mouse.Listener(on_click=on_click)
mouse_listener.start()
*Nanpy allows for a Raspi to have an Arduino slave through python
Right now I'm having extreme difficulty in using the nanpy Servo package, and I cant get it to run correctly. I'm using it to make a robot that is wirelessly controlled from a computer, this is what I have for code:
from nanpy import (ArduinoApi, SerialManager)
import pygame
from nanpy import Servo
import time
pygame.init()
a=0
d=0
window = pygame.display.set_mode((800,600))
pygame.display.set_caption("Console")
try :
connection = SerialManager()
ard = ArduinoApi(connection = connection)
run = True
except:
print("Connection Failed!")
servoA = Servo(2)
servoD = Servo(4)
while run :
for event in pygame.event.get():
keys = pygame.key.get_pressed()
# if (event.type==pygame.KEYDOWN):
if keys[pygame.K_s] and keys[pygame.K_a]:
a=a-1
servoA.write(a)
elif keys[pygame.K_s] and keys[pygame.K_d]:
d=d-1
servoD.write(d)
elif keys[pygame.K_w]:
a=a+1
d=d+1
servoD.write(d)
servoA.write(a)
elif keys[pygame.K_s]:
a=a-1
d=d-1
servoD.write(d)
servoA.write(a)
elif keys[pygame.K_d]:
d=d+1
servoD.write(d)
elif keys[pygame.K_a]:
a=a+1
servoA.write(a)
elif keys[pygame.K_t]:
run=False
pygame.quit()
This is the error the python shell throws:
Traceback (most recent call last):
File "/home/pi/Desktop/nanpy/RobotCode.py", line 28, in <module>
servoA = Servo(2)
File "/usr/local/lib/python3.4/dist-packages/nanpy-0.9.6-py3.4.egg/nanpy/servo.py", line 9, in __init__
self.id = self.call('new', pin)
File "/usr/local/lib/python3.4/dist-packages/nanpy-0.9.6-py3.4.egg/nanpy/arduinoboard.py", line 150, in call
return _call(self.namespace, self.id, args, self.connection)
File "/usr/local/lib/python3.4/dist-packages/nanpy-0.9.6-py3.4.egg/nanpy/arduinoboard.py", line 47, in _call
ret = return_value(connection)
File "/usr/local/lib/python3.4/dist-packages/nanpy-0.9.6-py3.4.egg/nanpy/arduinoboard.py", line 18, in return_value
return serial_manager.readline().replace('\r\n', '')
File "/usr/local/lib/python3.4/dist-packages/nanpy-0.9.6-py3.4.egg/nanpy/serialmanager.py", line 101, in readline
raise SerialManagerError('Serial timeout!')
nanpy.serialmanager.SerialManagerError: Serial timeout!
How can I fix this, and/or what am I doing wrong?
You need to specify the port of the Arduino. So could you try:
connection = SerialManager(device='/dev/ttyACM0')
or whatever port you are using.
update the configuration file to use the servo and upload it to arduino using the IDE then run this program.
you can find the cfg.h file in nanpy-firmware/nanpy folder.
I'm trying to write script which execute something after double click CTRL. It works well after first double click, but then I get that error. Also if I press CTRL once and again after timer execute function trigger I'll get same error.
import pythoncom, pyHook, threading
press = False
def triger():
global press
press=False
def something():
print 'hello'
def OnKeyboardEvent(event):
global press
if event.Key=='Lcontrol':
if press:
something()
press = False
else:
press=True
threading.Timer(1,triger).start()
hm = pyHook.HookManager()
hm.KeyDown = OnKeyboardEvent
hm.HookKeyboard()
pythoncom.PumpMessages()
Error:
hello
Warning (from warnings module):
File "C:\Python27\lib\threading.py", line 828
return _active[_get_ident()]
RuntimeWarning: tp_compare didn't return -1 or -2 for exception
Traceback (most recent call last):
File "C:\Python27\lib\site-packages\pyHook\HookManager.py", line 351, in KeyboardSwitch
return func(event)
File "C:\Users\123\Desktop\code\hooks.py", line 20, in OnKeyboardEvent
threading.Timer(1,triger).start()
File "C:\Python27\lib\threading.py", line 731, in Timer
return _Timer(*args, **kwargs)
File "C:\Python27\lib\threading.py", line 742, in __init__
Thread.__init__(self)
File "C:\Python27\lib\threading.py", line 446, in __init__
self.__daemonic = self._set_daemon()
File "C:\Python27\lib\threading.py", line 470, in _set_daemon
return current_thread().daemon
File "C:\Python27\lib\threading.py", line 828, in currentThread
return _active[_get_ident()]
TypeError: an integer is required
Acording to the documentation there have to be "return True" at the end of OnKeyboardEvent function. Here's how it looks like.
def OnKeyboardEvent(event):
global press
if event.Key=='Lcontrol':
if press:
something()
press = False
else:
press=True
threading.Timer(1,triger).start()
print 'waiting'
return True