Google assistant - Rspi 3 - "sounddevice.PortAudioError: Error querying device -1" - raspberry-pi3

Installed google assistant sdk on raspi3, the speaker is a home mini bluetooth, it is paired and connected to raspi, played from youtube and it works! even google says it's connected!
However, when running command in terminal as (env) "googlesamples-assistant-pushtotalk --project-id (not going to paste ID) --device-model-id" I get the following:
/home/pi/env/lib/python3.5/site-packages/google/auth/crypt/_cryptography_rsa.py:22: CryptographyDeprecationWarning: Python 3.5 support will be dropped in the next release of cryptography. Please upgrade your Python.
import cryptography.exceptions
INFO:root:Connecting to embeddedassistant.googleapis.com
Traceback (most recent call last):
File "/home/pi/env/bin/googlesamples-assistant-pushtotalk", line 8, in
sys.exit(main())
File "/home/pi/env/lib/python3.5/site-packages/click/core.py", line 722, in call
return self.main(*args, **kwargs)
File "/home/pi/env/lib/python3.5/site-packages/click/core.py", line 697, in main
rv = self.invoke(ctx)
File "/home/pi/env/lib/python3.5/site-packages/click/core.py", line 895, in invoke
return ctx.invoke(self.callback, **ctx.params)
File "/home/pi/env/lib/python3.5/site-packages/click/core.py", line 535, in invoke
return callback(*args, **kwargs)
File "/home/pi/env/lib/python3.5/site-packages/googlesamples/assistant/grpc/pushtotalk.py", line 351, in main
flush_size=audio_flush_size
File "/home/pi/env/lib/python3.5/site-packages/googlesamples/assistant/grpc/audio_helpers.py", line 190, in init
blocksize=int(block_size/2), # blocksize is in number of frames.
File "/home/pi/env/lib/python3.5/site-packages/sounddevice.py", line 1345, in init
**_remove_self(locals()))
File "/home/pi/env/lib/python3.5/site-packages/sounddevice.py", line 762, in init
samplerate)
File "/home/pi/env/lib/python3.5/site-packages/sounddevice.py", line 2571, in _get_stream_parameters
info = query_devices(device)
File "/home/pi/env/lib/python3.5/site-packages/sounddevice.py", line 569, in query_devices
raise PortAudioError('Error querying device {0}'.format(device))
sounddevice.PortAudioError: Error querying device -1
When using arecord -l or aplay -l in terminal, get the same message for both: "aplay: device_list:270: no soundcards found..."
Also, running test in terminal using "speaker-test -t wav", the test runs but no sound is working"
" speaker-test 1.1.3
Playback device is default
Stream parameters are 48000Hz, S16_LE, 1 channels
WAV file(s)
Rate set to 48000Hz (requested 48000Hz)
Buffer size range from 9600 to 4194304
Period size range from 480 to 4096
Using max buffer size 4194304
Periods = 4
was set period_size = 4096
was set buffer_size = 4194304
0 - Front Left
Time per period = 0.339021
0 - Front Left
Time per period = 0.315553
0 - Front Left
Time per period = 0.315577
*Keeps generating but with no sound."
Finally, going through sudo nano /home/pi/.asoundrc file, when connected to speaker is:
pcm.!default {
type plug
slave.pcm {
type bluealsa
device "x❌x❌x:x"
profile "a2dp"
}
}
ctl.!default {
type bluealsa
}
AND when going to "sudo nano /etc/asound.conf" it seems that it generates another code, when also connected to same speaker:
pcm.!default {
type asym
capture.pcm "mic"
playback.pcm "speaker"
}
pcm.mic {
type plug
slave.pcm {
type bluealsa device "x❌x❌x:x"
profile "sco"
}
}
pcm.speaker {
type plug
slave.pcm {
type bluealsa device "x❌x❌x:x"
profile "sco"
}
}
I tried copy/paste code of /etc/asound.conf into /home/pi/.asoundrc and run speaker-test -t wav, but i get:
speaker-test 1.1.3
Playback device is default
Stream parameters are 48000Hz, S16_LE, 1 channels
WAV file(s)
ALSA lib bluealsa-pcm.c:680:(_snd_pcm_bluealsa_open) Couldn't get BlueALSA transport: No such device
Playback open error: -19,No such device"
So, whats the deal??

Related

Using PyAV to encode mono audio to file, params match docs, but still causes Errno 22

While trying to use PyAV to encode live mono audio from a microphone to a compressed audio stream (using mp2 or flac as encoder), the program kept raising an exception ValueError: [Errno 22] Invalid argument.
To remove the live microphone source as a cause of the problem, and to make the problematic code easier for others to run/test, I have removed the mic source and now just generate a pure tone as a sequence of input buffers.
All attempts to figure out the missing or mismatched or incorrect argument have just resulted in seeing documentation and examples that are the same as my code.
I would like to know from someone who has used PyAV successfully for mono audio what the correct method and parameters are for encoding mono frames into the mono stream.
The package used is av 10.0.0 installed with
pip3 install av --no-binary av
so it uses my package-manager provided ffmpeg library, which is version 4.2.7.
The problematic python code is:
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Recreating an error 22 when encoding sound with PyAV.
Created on Sun Feb 19 08:10:29 2023
#author: andrewm
"""
import typing
import sys
import math
import fractions
import av
from av import AudioFrame
""" Ensure some PyAudio constants are still defined without changing
the PyAudio recording callback function and without depending
on PyAudio simply for reproducing the PyAV bug [Errno 22] thrown in
File "av/filter/context.pyx", line 89, in av.filter.context.FilterContext.push
"""
class PA_Stub():
paContinue = True
paComplete= False
pyaudio = PA_Stub()
"""Generate pure tone at given frequency with amplitude 0...1.0 at
sampling frewuency fs and beginning at phase offset 'phase'.
Returns the new phase after the sinusoid has cycled over the
sampling window length.
"""
def generate_tone(
freq:int, phase:float, amp:float, fs, samp_fmt, buffer:bytearray
) -> float:
assert samp_fmt == "s16", "Only s16 supported atm"
samp_size_bytes = 2
n_samples = int(len(buffer)/samp_size_bytes)
window = [int(0) for i in range(n_samples)]
theta = phase
phase_inc = 2*math.pi * freq / fs
for i in range(n_samples):
v = amp * math.sin(theta)
theta += phase_inc
s = int((2**15-1)*v)
window[i] = s
for sample_i in range(len(window)):
byte_i = sample_i * samp_size_bytes
enc = window[sample_i].to_bytes(
2, byteorder=sys.byteorder, signed=True
)
buffer[byte_i] = enc[0]
buffer[byte_i+1] = enc[1]
return theta
channels = 1
fs = 44100 # Record at 44100 samples per second
fft_size_samps = 256
chunk_samps = fft_size_samps * 10 # Record in chunks that are multiples of fft windows.
# print(f"fft_size_samps={fft_size_samps}\nchunk_samps={chunk_samps}")
seconds = 3.0
out_filename = "testoutput.wav"
# Store data in chunks for 3 seconds
sample_limit = int(fs * seconds)
sample_len = 0
frames = [] # Initialize array to store frames
ffmpeg_codec_name = 'mp2' # flac, mp3, or libvorbis make same error.
sample_size_bytes = 2
buffer = bytearray(int(chunk_samps*sample_size_bytes))
chunkperiod = chunk_samps / fs
total_chunks = int(math.ceil(seconds / chunkperiod))
phase = 0.0
### uncomment if you want to see the synthetic data being used as a mic input.
# with open("test.raw","wb") as raw_out:
# for ci in range(total_chunks):
# phase = generate_tone(2600, phase, 0.8, fs, "s16", buffer)
# raw_out.write(buffer)
# print("finished gen test")
# sys.exit(0)
# #----
# Using mp2 or mkv as the container format gets the same error.
with av.open(out_filename+'.mp2', "w", format="mp2") as output_con:
output_con.metadata["title"] = "My title"
output_con.metadata["key"] = "value"
channel_layout = "mono"
sample_fmt = "s16p"
ostream = output_con.add_stream(ffmpeg_codec_name, fs, layout=channel_layout)
assert ostream is not None, "No stream!"
cctx = ostream.codec_context
cctx.sample_rate = fs
cctx.time_base = fractions.Fraction(numerator=1,denominator=fs)
cctx.format = sample_fmt
cctx.channels = channels
cctx.layout = channel_layout
print(cctx, f"layout#{cctx.channel_layout}")
# Define PyAudio-style callback for recording plus PyAV transcoding.
def rec_callback(in_data, frame_count, time_info, status):
global sample_len
global ostream
frames.append(in_data)
nsamples = int(len(in_data) / (channels*sample_size_bytes))
frame = AudioFrame(format=sample_fmt, layout=channel_layout, samples=nsamples)
frame.sample_rate = fs
frame.time_base = fractions.Fraction(numerator=1,denominator=fs)
frame.pts = sample_len
frame.planes[0].update(in_data)
print(frame, len(in_data))
for out_packet in ostream.encode(frame):
output_con.mux(out_packet)
for out_packet in ostream.encode(None):
output_con.mux(out_packet)
sample_len += nsamples
retflag = pyaudio.paContinue if sample_len<sample_limit else pyaudio.paComplete
return (in_data, retflag)
print('Beginning')
### some e.g. PyAudio code which starts the recording process normally.
# istream = p.open(
# format=sample_format,
# channels=channels,
# rate=fs,
# frames_per_buffer=chunk_samps,
# input=True,
# stream_callback=rec_callback
# )
# print(istream)
# Normally at this point you just sleep the main thread while
# PyAudio calls back with mic data, but here it is all generated.
for ci in range(total_chunks):
phase = generate_tone(2600, phase, 0.8, fs, "s16", buffer)
ret_data, ret_flag = rec_callback(buffer, ci, {}, 1)
print('.', end='')
print(" closing.")
# Stop and close the istream
# istream.stop_stream()
# istream.close()
If you uncomment the RAW output part you will find the generated data can be imported as PCM s16 Mono 44100Hz into Audacity and plays the expected tone, so the generated audio data does not seem to be the problem.
The normal program console output up until the exception is:
<av.AudioCodecContext audio/mp2 at 0x7f8e38202cf0> layout#4
Beginning
<av.AudioFrame 0, pts=0, 2560 samples at 44100Hz, mono, s16p at 0x7f8e38202eb0> 5120
.<av.AudioFrame 0, pts=2560, 2560 samples at 44100Hz, mono, s16p at 0x7f8e382025f0> 5120
The stack trace is:
Traceback (most recent call last):
File "Dev/multichan_recording/av_encode.py", line 147, in <module>
ret_data, ret_flag = rec_callback(buffer, ci, {}, 1)
File "Dev/multichan_recording/av_encode.py", line 121, in rec_callback
for out_packet in ostream.encode(frame):
File "av/stream.pyx", line 153, in av.stream.Stream.encode
File "av/codec/context.pyx", line 484, in av.codec.context.CodecContext.encode
File "av/audio/codeccontext.pyx", line 42, in av.audio.codeccontext.AudioCodecContext._prepare_frames_for_encode
File "av/audio/resampler.pyx", line 101, in av.audio.resampler.AudioResampler.resample
File "av/filter/graph.pyx", line 211, in av.filter.graph.Graph.push
File "av/filter/context.pyx", line 89, in av.filter.context.FilterContext.push
File "av/error.pyx", line 336, in av.error.err_check
ValueError: [Errno 22] Invalid argument
edit: It's interesting that the error happens on the 2nd AudioFrame, as apparently the first one was encoded okay, because they are given the same attribute values aside from the Presentation Time Stamp (pts), but leaving this out and letting PyAV/ffmpeg generate the PTS by itself does not fix the error, so an incorrect PTS does not seem the cause.
After a brief glance in av/filter/context.pyx the exception must come from a bad return value from res = lib.av_buffersrc_write_frame(self.ptr, frame.ptr)
Trying to dig into av_buffersrc_write_frame from the ffmpeg source it is not clear what could be causing this error. The only obvious one is a mismatch between channel layouts, but my code is setting the layout the same in the Stream and the Frame. That problem had been found by an old question pyav - cannot save stream as mono and their answer (that one parameter required is undocumented) is the only reason the code now has the layout='mono' argument when making the stream.
The program output shows layout #4 is being used, and from https://github.com/FFmpeg/FFmpeg/blob/release/4.2/libavutil/channel_layout.h you can see this is the value for symbol AV_CH_FRONT_CENTER which is the only channel in the MONO layout.
The mismatch is surely some other object property or an undocumented parameter requirement.
How do you encode mono audio to a compressed stream with PyAV?

Unable to read Core Dump info. "gdb process has already finished with return code: 127"

I am trying to read core dump info that will be saved in flash.
i am first reading the coredump paritition:
esptool.py --port /dev/ttyUSB0 read_flash 0x3ec000 0xE000 ./core.bin
Then I am trying to extract the info using:
espcoredump.py info_corefile --core ./core.bin --core-format raw build/httpsOTA_S_FE.elf
But the script is giving me the following error:
`
espcoredump.py v0.4-dev
===============================================================
==================== ESP32 CORE DUMP START ====================
Traceback (most recent call last):
File "/home/praveen/opt/esp/idf-4.4.2/esp-idf/components/espcoredump/espcoredump.py", line 350, in <module>
temp_core_files = info_corefile()
File "/home/praveen/opt/esp/idf-4.4.2/esp-idf/components/espcoredump/espcoredump.py", line 170, in info_corefile
gdb = EspGDB(gdb_tool, [rom_sym_cmd], core_elf_path, args.prog, timeout_sec=args.gdb_timeout_sec)
File "/home/praveen/opt/esp/idf-4.4.2/esp-idf/components/espcoredump/corefile/gdb.py", line 45, in __init__
self._gdbmi_run_cmd_get_responses(cmd='-data-list-register-values x pc',
File "/home/praveen/opt/esp/idf-4.4.2/esp-idf/components/espcoredump/corefile/gdb.py", line 63, in _gdbmi_run_cmd_get_responses
more_responses = self.p.get_gdb_response(timeout_sec=0, raise_error_on_timeout=False)
File "/home/praveen/.espressif/python_env/idf4.4_py3.10_env/lib/python3.10/site-packages/pygdbmi/gdbcontroller.py", line 269, in get_gdb_response
self.verify_valid_gdb_subprocess()
File "/home/praveen/.espressif/python_env/idf4.4_py3.10_env/lib/python3.10/site-packages/pygdbmi/gdbcontroller.py", line 175, in verify_valid_gdb_subprocess
raise NoGdbProcessError(
pygdbmi.gdbcontroller.NoGdbProcessError: gdb process has already finished with return code: 127
`
My end goal is to get send this partition data to my server and debug the info on server. I first wanted to see the process on the host machine and then implement same on my server.
espcoredump.py info_corefile --core ./core.bin --core-format raw build/httpsOTA_S_FE.elf
is supposed to print the core dump info.
I tried the same with a litle older version of idf IDF-4.2.4 and i get following error:
`
espcoredump.py v0.4-dev
===============================================================
==================== ESP32 CORE DUMP START ====================
Traceback (most recent call last):
File "/home/praveen/opt/esp/idf-4.2.4/esp-idf/components/espcoredump/espcoredump.py", line 1818, in <module>
main()
File "/home/praveen/opt/esp/idf-4.2.4/esp-idf/components/espcoredump/espcoredump.py", line 1813, in main
operation_func(args)
File "/home/praveen/opt/esp/idf-4.2.4/esp-idf/components/espcoredump/espcoredump.py", line 1644, in info_corefile
p,task_name = gdbmi_freertos_get_task_name(p, extra_info[0])
File "/home/praveen/opt/esp/idf-4.2.4/esp-idf/components/espcoredump/espcoredump.py", line 1543, in gdbmi_freertos_get_task_name
p,res = gdbmi_data_evaluate_expression(p, "(char*)((TCB_t *)0x%x)->pcTaskName" % tcb_addr)
File "/home/praveen/opt/esp/idf-4.2.4/esp-idf/components/espcoredump/espcoredump.py", line 1539, in gdbmi_data_evaluate_expression
p = gdbmi_cmd_exec(p, handlers, "-data-evaluate-expression \"%s\"" % expr)
File "/home/praveen/opt/esp/idf-4.2.4/esp-idf/components/espcoredump/espcoredump.py", line 1493, in gdbmi_cmd_exec
p.stdin.write(bytearray("%s\n" % gdbmi_cmd, encoding='utf-8'))
BrokenPipeError: [Errno 32] Broken pipe
`

MuscleCommandLine non-zero return code 1/is not recognized as an internal or external command,

I am trying to align 4 difference sequences using MuscleCommandLine. This code works perfectly on Anaconda and Mac but I am trying to make it work on Windows and I am having several issues.
muscle_exe = r'../muscle3.8.31_i86darwin64.exe'
in_file = r'../infile.fasta'
out_file = r'../aln_out.fasta'
muscle_cline = MuscleCommandline(muscle_exe, input=in_file, out=out_file)
muscle_cline()
When I try this using Anaconda on Mac, I get the result. However, when running the same code on Window, I get the following error:
---------------------------------------------------------------------------
ApplicationError Traceback (most recent call last)
<ipython-input-3-70ad09443dc6> in <module>
3 genome = genome_location(before, after, alignment)
4
----> 5 filename = custom_fasta(genome, alignment)
6
7 info = AlignIO.read(r'../aln_out.fasta','fasta')
<ipython-input-1-655071c8d454> in custom_fasta(locations_dict, names)
185
186 muscle_cline = MuscleCommandline(muscle_exe, input=in_file, out=out_file)
--> 187 muscle_cline()
188
189 return(filename)
~\Anaconda3\lib\site-packages\Bio\Application\__init__.py in __call__(self, stdin, stdout, stderr, cwd, env)
567
568 if return_code:
--> 569 raise ApplicationError(return_code, str(self), stdout_str, stderr_str)
570 return stdout_str, stderr_str
571
ApplicationError: Non-zero return code 1 from '../muscle3.8.31_i86darwin64.exe -in ../infile.fasta -out ../aln_out.fasta', message "'..' is not recognized as an internal or external command,"
I have read the documentation but this is not listed as an issue. This same question has been asked before but no solution has been offered. People keep asking to install muscle, but the way it works with Biopython and Anaconda is that you do not need to install it.
So why does this keep happening?

Yocto - failed to buid hddimg. Error: do_bootimg

I am working on yocto,dunfell, am trying to build .hddimg image for a genericx86-64 machine. I inherit image-live, add hhdimg to IMAGE_FSTYPES and everything works fine with iso, wic and ... But when I add hddimg I get this error:
ERROR: test-image-1.0-r0 do_bootimg: /path/build/tmp/work/genericx86_64-poky-linux/test-image/1.0-r0/test-image-1.0/hddimg/rootfs.img rootfs size is greather than or equal to 4GB,
ERROR: test-image-1.0-r0 do_bootimg: and this doesn't work on a FAT filesystem. You can either:
ERROR: test-image-1.0-r0 do_bootimg: 1) Reduce the size of rootfs.img, or,
ERROR: test-image-1.0-r0 do_bootimg: 2) Use wic, vmdk or vdi instead of hddimg
ERROR: test-image-1.0-r0 do_bootimg: Error executing a python function in exec_python_func() autogenerated:
The stack trace of python calls that resulted in this exception/failure was:
File: 'exec_python_func() autogenerated', lineno: 2, function: <module>
0001:
*** 0002:do_bootimg(d)
0003:
File: '/path/layers/poky/meta/classes/image-live.bbclass', lineno: 257, function: do_bootimg
0253: if d.getVar("PCBIOS") == "1":
0254: bb.build.exec_func('build_syslinux_cfg', d)
0255: if d.getVar("EFI") == "1":
0256: bb.build.exec_func('build_efi_cfg', d)
*** 0257: bb.build.exec_func('build_hddimg', d)
0258: bb.build.exec_func('build_iso', d)
0259: bb.build.exec_func('create_symlinks', d)
0260:}
0261:do_bootimg[subimages] = "hddimg iso"
File: '/path/layers/poky/bitbake/lib/bb/build.py', lineno: 251, function: exec_func
0247: with bb.utils.fileslocked(lockfiles):
0248: if ispython:
0249: exec_func_python(func, d, runfile, cwd=adir)
0250: else:
*** 0251: exec_func_shell(func, d, runfile, cwd=adir)
0252:
0253: try:
0254: curcwd = os.getcwd()
0255: except:
File: '/path/layers/poky/bitbake/lib/bb/build.py', lineno: 452, function: exec_func_shell
0448: with open(fifopath, 'r+b', buffering=0) as fifo:
0449: try:
0450: bb.debug(2, "Executing shell function %s" % func)
0451: with open(os.devnull, 'r+') as stdin, logfile:
*** 0452: bb.process.run(cmd, shell=False, stdin=stdin, log=logfile, extrafiles=[(fifo,readfifo)])
0453: finally:
0454: os.unlink(fifopath)
0455:
0456: bb.debug(2, "Shell function %s finished" % func)
File: '/path/layers/poky/bitbake/lib/bb/process.py', lineno: 182, function: run
0178: if not stderr is None:
0179: stderr = stderr.decode("utf-8")
0180:
0181: if pipe.returncode != 0:
*** 0182: raise ExecutionError(cmd, pipe.returncode, stdout, stderr)
0183: return stdout, stderr
Exception: bb.process.ExecutionError: Execution of '/path/build/tmp/work/genericx86_64-poky-linux/test-image/1.0-r0/temp/run.build_hddimg.18514' failed with exit code 1:
WARNING: exit code 1 from a shell command.
ERROR: Logfile of failure stored in: /path/build/tmp/work/genericx86_64-poky-linux/test-image/1.0-r0/temp/log.do_bootimg.18514
ERROR: Task (/path/layers/meta-ammsc2/recipes-core/images/test-image.bb:do_bootimg) failed with exit code '1'```
Your rootfs for test-image is larger than 4GB, which is the maximum filesystem size for FAT partitions (the default used by the .hddimg image type).
The error already contains two solutions:
Reduce the image size, by removing packages
Use the wic format (vmdk and vdi are for virtual machine engines)
To use the wic format, simply add wic to IMAGE_FSTYPES and Yocto will build a .wic image and place it in the deploy/images directory. You can flash this to your disk using dd or bmaptool, and boot it.
These images are built from a template specified by WKS_FILE, which defaults to genericx86.wks.in for the the genericx86-64 machine. This default template creates a partition table and installs an EFI bootloader (Grub).
If you'd like to manually generate the wic images or modify the templates, check out the documentation for Creating Partitioned Images Using Wic.

Trying to make simple timer to shutdown windows in python

Trying to make simple timer to shutdown windows in python (just for fun) but i'm having a small problem that can't find the answer, the script just ask if the user wants to use minutes or seconds to shut down using an if, the part of using seconds works fine, the problem is with minutes, the script get the time in minutes and convert to seconds, than runs: subprocess.call(["shutdown" "-s", "-t", ntime])
But it's not working, if i double click on the file.py and try this part, the script just close, but if a execute in the IDLE i recieve an this error:
Traceback (most recent call last):
File "C:\Users\User\Desktop\shutdown.py", line 17, in <module>
subprocess.call(["shutdown" "-s", "-t", ntime])
File "F:\Programs\python\lib\subprocess.py", line 267, in call
with Popen(*popenargs, **kwargs) as p:
File "F:\Programs\python\lib\subprocess.py", line 709, in __init__
restore_signals, start_new_session)
File "F:\Programs\python\lib\subprocess.py", line 997, in _execute_child
startupinfo)
FileNotFoundError: [WinError 2] The system cannot find the file specified
>>>
Code:
import subprocess
print('0:Seconds')
print('1:Minutes')
minorsec = input('Want to use minutes or seconds? ')
if minorsec == '0':
time = input('Type the time to shutdown in seconds: ')
subprocess.call(["shutdown", "-s", "-t", time])
elif minorsec == '1':
time = input('Type the time to shutdown in minutes: ')
ntime = int(time) * 60
subprocess.call(["c:\\windows\\system32\\shutdown.exe" "-s", "-t", str(ntime)])
else:
print('Error, Press just 0 or 1')
input('Press Enter to close: ')
Issue #1: This line
ntime = time * 60
Doesn't do what you think it does. time, the value returned from the previous input call is a string, not an integer. So if the user types "15" as his input, ntime becomes something insane like: "1515151515151515151515.....15". That's probably your core problem:
Convert the user's input from string back to integer:
ntime = int(time) * 60
Issue #2, which is a side effect of fixing #1: All the values in the argument list to subprocess.call must be strings:
time = input('Type the time to shutdown in minutes: ')
ntime = int(time) * 60
subprocess.call(["shutdown" "-s", "-t", str(ntime)])
Issue #3: Don't use an argument list:
subprocess.call("shutdown.exe -s -t " + str(ntime))

Resources