Bitcoin verify a single block in python - python
Currently i try to verify the Bitcoin Block 77504 by my own. But from the satoshi whitepaper it seems i have more questions than answer to do so.
First information from the previous block:
### What we know from last block ###
# height = 77503
# id = 00000000000447829abff59b3208a08ff28b3eb184b1298929abe6dd65c3578a
# version = 1
# timestamp = 1283325019
# bits = 459874456
# nonce = 1839166754
# difficulty = 623.3869598689275
# merkle_root = f18107935e8853011e477244241b5d786966495f8c59be46c92ac323c9cc8cde
# tx_count = 6
# size = 1438
# weight = 5752
Then the information from the block i want to verify
### What we now want to mine ###
# height = 77504
# id = 00000000004582246e63ff7e0760c6f009e5ef5ce1eb5397be6f3eb9d698bda5
# version = 1
# timestamp = 1283326637
# bits = 459874456
# nonce = 191169021
# difficulty = 623.3869598689275
# merkle_root = 59c77dabd9f005c771b23b846c79c7741dc0e70d912f9470eace886b42a0d601
# tx_count = 44
# size = 11052
# weight = 44208
# txids = ["b899c55adb5a9604b72643c0f6cd5bf6c2447bb0fc035c50e13d2e471cbf5aa5","05180e3252c48a54d4d0abe9359621f54f3031fd318a812be96da0f13bfa8bf3","29d641bd4a5d4b01ceee1126af920513d52e088bad500fad1358c96962e25e28","40d52b5aa4be889739410f82f36c71fdda554b999fb14fc12aeab5bb2e6498cb","62d5e84500cc674a5172bea5755a223da974f90f614deb45c160478a8974419c","78de7a104617f58620ae9e7cf58bcd875d8043ee5046d93c9d69224c2ae39a1e","8831ad38deb23e1fbea6d376f1805aec194760b0f334a3c4b623aa0751445c9b","8a6bd0c2d74ea785d886bd6d87b6a4eb4cd35af5fb7ae3a364eb1f76b114c375","90d6da6a4b48e7330ae926cd00623fa8d94fd0a2b9a001475da22cbc49435ff9","d002da9953844c767cf7d42092b81e8c5bb03baf520d79028013fd3400bc8651","d1f8573148126e8d17641276f22ece33b8276311d93794ed2975ebb802b98fc8","d22ed765adba9c7f5fef19ff15cb89559b4148d571fcb40ee2889231ac1b8dea","f32b000adf9ab6d7a66593cb20cba4d3a3e0cbb3453608ce11a780fab532add5","32d2ff811677a8dbed4f317c9fcae4796b491bde944cca4a993734be787b4e79","4b806d44d9aff762601f21ad541c0e99a77d0a14b730774a2d7721dd094d9030","8c5258a8e3f60c9edfa55b86780a9832c8cd5f407dbe25948cd2fd87910ca4c4","bc4fcea23cd93bac13ab75bad8d23576be88a89e72f2c455932f096d6dd2a2da","ca5c53ef34ff5a2f816daf648c8dafb01680502c2c0c98b82b9527392f707e70","f9db6e9a62502dfe8057e7b1c0f3b8f145d354ee4e341233bfe8861fff143822","fc3730bbfa443558c677da6898f106ee7d5516b14e21bf369def7cb6a5bf6b8b","1cfa85d94ebfb9206ad49f421319a6ee99b339e4e8d292b866459bb742731d83","80fa7f38cc02b05b765675adba589d426e6122b1e8158726df0c55cf44c937eb","8c72683585901ff96edd14bde9c87ee91a9d54c187a15aa333e3d6b916399fd2","905e015afa4df7d9dc4a1a80a029e469258045fe9288071b16af49a2f458c2cb","bd8fab0ca0072cd230a4bb0a6efff5964756a023ca53d1f06c3fa22800fe044c","464280d62b8965255c286f1c4c5c457f594db64bdef1c8aaa7ddf776fc4d320e","625b8ec5af9ad2c1506aca8ad61670ce3acf7070fe5aabc2dec06dcda119503a","a2e06f6b0ea68cc2c9bf44d09e54832c830971961ed8ea5ec553918ab7eb48d2","a4de41f56f0970d9b1948f1e386a124860891d790f506c2e3bbe71dd289031d4","11475d2fbbc5e3aee2eff54aa9bf2f83d5f33fffce528cc9804f820e0f6a76e7","5dc019a6397c25d0e7db56f3ed2ccdc1db5642701224d56fb9ad1d1017279e7b","e5d1e0e5a2309cb07ec522a1eb56da5aa5e58ecaea6d49e278a52c1c24230dae","21d192ea46007dbeef7c9673ac158c0f9dbf80e0785380ae562a1fbb10430ae7","8fafe7a8168563c4c186d792b49fc0fa4368c6b2e5a1217f2f98b127ff1cdf87","d2410a45bcc0e4f5b7a8d84e730ffd9744e0dd0d9fb2d7e93fb71e590bf0f1fb","6103334a35171bc5a153b51dd7c94977c62822b1cec2fcac20ea9d0a959129d7","6551831774420989df2d9deeab196e14025f2e5fd502feb86dfc7ccedb917ce0","7c1a188e0c94c7d61aea1ebddb359f508c99fdd0e028887bbf3a3036a1b5bf8a","8b9c989cee69c107697b13aebd677879db48275c089ae206c85eb8db45acf50f","4195c5abf97adb2108de8aeee99cb751e2b4f9698607f60e326b9a67b9127a31","800b308f49fe86ff3323dd6240190212626d052a017dd1cad01540790604c00f","1d2fb37bab59d6f3f83f7596fde128a0b7b0f7ccd8fabc8d2a929923a268a847","8a8149d58791ace6cefd803021b4e870acca5b2c40e2e1415f423e6ec4333e32","7a1eb6b8ee1ff52648cd9a099c7658be53627732b226aa93f56d430c85a52991"]
I have prepared a small script that should calculate it for me but no matter what i am not able to get to the target hash 00000000004582246e63ff7e0760c6f009e5ef5ce1eb5397be6f3eb9d698bda5 to verify the block mined. What is also unclear to me where would one have to add his own Bitcoin wallet to get the reward of the transaction.
from hashlib import sha256
def SHA256(text):
return sha256(text.encode("ascii")).hexdigest()
def mine(block_number, transactions, previous_hash, prefix_zeros):
prefix_str = '0'*prefix_zeros
text = str(block_number) + str(transactions) + str(previous_hash) + str(nonce_to_verify)
new_hash = SHA256(text)
if new_hash.startswith(prefix_str):
print(f"Jipiiii! Successfully mined bitcoins with nonce value:{nonce_to_verify}")
return new_hash
else:
new_hash = None
return new_hash
### normally this is unknown, would be somethinge like range(0,100000000000), i just want to verify a block ###
nonce_to_verify = 191169021
### In what format are transactions presented ? ###
transactions = ["b899c55adb5a9604b72643c0f6cd5bf6c2447bb0fc035c50e13d2e471cbf5aa5","05180e3252c48a54d4d0abe9359621f54f3031fd318a812be96da0f13bfa8bf3","29d641bd4a5d4b01ceee1126af920513d52e088bad500fad1358c96962e25e28","40d52b5aa4be889739410f82f36c71fdda554b999fb14fc12aeab5bb2e6498cb","62d5e84500cc674a5172bea5755a223da974f90f614deb45c160478a8974419c","78de7a104617f58620ae9e7cf58bcd875d8043ee5046d93c9d69224c2ae39a1e","8831ad38deb23e1fbea6d376f1805aec194760b0f334a3c4b623aa0751445c9b","8a6bd0c2d74ea785d886bd6d87b6a4eb4cd35af5fb7ae3a364eb1f76b114c375","90d6da6a4b48e7330ae926cd00623fa8d94fd0a2b9a001475da22cbc49435ff9","d002da9953844c767cf7d42092b81e8c5bb03baf520d79028013fd3400bc8651","d1f8573148126e8d17641276f22ece33b8276311d93794ed2975ebb802b98fc8","d22ed765adba9c7f5fef19ff15cb89559b4148d571fcb40ee2889231ac1b8dea","f32b000adf9ab6d7a66593cb20cba4d3a3e0cbb3453608ce11a780fab532add5","32d2ff811677a8dbed4f317c9fcae4796b491bde944cca4a993734be787b4e79","4b806d44d9aff762601f21ad541c0e99a77d0a14b730774a2d7721dd094d9030","8c5258a8e3f60c9edfa55b86780a9832c8cd5f407dbe25948cd2fd87910ca4c4","bc4fcea23cd93bac13ab75bad8d23576be88a89e72f2c455932f096d6dd2a2da","ca5c53ef34ff5a2f816daf648c8dafb01680502c2c0c98b82b9527392f707e70","f9db6e9a62502dfe8057e7b1c0f3b8f145d354ee4e341233bfe8861fff143822","fc3730bbfa443558c677da6898f106ee7d5516b14e21bf369def7cb6a5bf6b8b","1cfa85d94ebfb9206ad49f421319a6ee99b339e4e8d292b866459bb742731d83","80fa7f38cc02b05b765675adba589d426e6122b1e8158726df0c55cf44c937eb","8c72683585901ff96edd14bde9c87ee91a9d54c187a15aa333e3d6b916399fd2","905e015afa4df7d9dc4a1a80a029e469258045fe9288071b16af49a2f458c2cb","bd8fab0ca0072cd230a4bb0a6efff5964756a023ca53d1f06c3fa22800fe044c","464280d62b8965255c286f1c4c5c457f594db64bdef1c8aaa7ddf776fc4d320e","625b8ec5af9ad2c1506aca8ad61670ce3acf7070fe5aabc2dec06dcda119503a","a2e06f6b0ea68cc2c9bf44d09e54832c830971961ed8ea5ec553918ab7eb48d2","a4de41f56f0970d9b1948f1e386a124860891d790f506c2e3bbe71dd289031d4","11475d2fbbc5e3aee2eff54aa9bf2f83d5f33fffce528cc9804f820e0f6a76e7","5dc019a6397c25d0e7db56f3ed2ccdc1db5642701224d56fb9ad1d1017279e7b","e5d1e0e5a2309cb07ec522a1eb56da5aa5e58ecaea6d49e278a52c1c24230dae","21d192ea46007dbeef7c9673ac158c0f9dbf80e0785380ae562a1fbb10430ae7","8fafe7a8168563c4c186d792b49fc0fa4368c6b2e5a1217f2f98b127ff1cdf87","d2410a45bcc0e4f5b7a8d84e730ffd9744e0dd0d9fb2d7e93fb71e590bf0f1fb","6103334a35171bc5a153b51dd7c94977c62822b1cec2fcac20ea9d0a959129d7","6551831774420989df2d9deeab196e14025f2e5fd502feb86dfc7ccedb917ce0","7c1a188e0c94c7d61aea1ebddb359f508c99fdd0e028887bbf3a3036a1b5bf8a","8b9c989cee69c107697b13aebd677879db48275c089ae206c85eb8db45acf50f","4195c5abf97adb2108de8aeee99cb751e2b4f9698607f60e326b9a67b9127a31","800b308f49fe86ff3323dd6240190212626d052a017dd1cad01540790604c00f","1d2fb37bab59d6f3f83f7596fde128a0b7b0f7ccd8fabc8d2a929923a268a847","8a8149d58791ace6cefd803021b4e870acca5b2c40e2e1415f423e6ec4333e32","7a1eb6b8ee1ff52648cd9a099c7658be53627732b226aa93f56d430c85a52991"]
### Just a check of 5 leading zeros... but why the difficulty 623.3869598689275 how to get to the 11 zeros? ###
difficulty=11
### Last Block (77503) found ###
lastfoundblock = "00000000000447829abff59b3208a08ff28b3eb184b1298929abe6dd65c3578a"
print("start mining")
new_hash = mine(77504,transactions,lastfoundblock, difficulty)
print("finnished mining.")
print(f"Found block is: {new_hash} should be the same as 00000000004582246e63ff7e0760c6f009e5ef5ce1eb5397be6f3eb9d698bda5")
Help would be appreciated so that i can verify a single block. Already pointing in the right directions would be appreciated so that i can solve my problem.
As no one was able to answer it... here is the code to verify a block's nonce:
import hashlib, struct, binascii
from time import time
def get_target_str(bits):
# https://en.bitcoin.it/wiki/Difficulty
exp = bits >> 24
mant = bits & 0xffffff
target_hexstr = '%064x' % (mant * (1<<(8*(exp - 3))))
print(f'T: {target_hexstr}')
target_str = bytes.fromhex(target_hexstr)
return target_str
def verify_nonce(version, prev_block, mrkl_root,
timestamp, bits_difficulty,nonce):
target_str = get_target_str(bits_difficulty)
header = ( struct.pack("<L", version) +
bytes.fromhex(prev_block)[::-1] +
bytes.fromhex(mrkl_root)[::-1] +
struct.pack("<LLL", timestamp, bits_difficulty, nonce))
hash_result = hashlib.sha256(hashlib.sha256(header).digest()).digest()
return bytes.hex(hash_result[::-1])
#nonce += 1
test1_version = 0x3fff0000
test1_prev_block = "0000000000000000000140ac4688aea45aacbe7caf6aaca46f16acd93e1064c3"
test1_merkle_root = "422458fced12693312058f6ee4ada19f6df8b29d8cac425c12f4722e0dc4aafd"
test1_timestamp = 0x5E664C76
test1_bits_diff = 0x17110119
test1_nonce1 = 538463288 #(0x20184C38)
test1_block_hash = "0000000000000000000d493c3c1b91c8059c6b0838e7e68fbcf8f8382606b82c"
test1_calc_block_hash = verify_nonce(test1_version,
test1_prev_block,
test1_merkle_root,
test1_timestamp,
test1_bits_diff,
test1_nonce1)
print(f'S: {test1_block_hash}')
print(f'R: {test1_calc_block_hash}')
if test1_block_hash == test1_calc_block_hash:
print("hashing is correct")
Thanks to https://github.com/razvancazacu/bitcoin-mining-crypto
Related
Problem with python code for Keithley 2450, pymeasure "apply current" does not work
I'm trying to make a python program to communicate with my keithley2450 sourcemeter but I can't impose a current. Let me explain I manage to communicate with the keithley2450, and I would like to impose a current for a period of time that I define and measure the resistance and the voltage. But I can't impose a current. from pymeasure.instruments.keithley import Keithley2450 import time import openpyxl t_acquisition = 10 tempsreel = 0 import pyvisa rm = pyvisa.ResourceManager() print(rm.list_resources()) wb = openpyxl.Workbook() sheet = wb.active try: keithley = Keithley2450('USB0::0x05E6::0x2450::04490659::0::INSTR') keithley.apply_current() # Sets up to source current keithley.source_current_range = 10e-3 # Sets the source current range to 10 mA keithley.compliance_voltage = 10 # Sets the compliance voltage to 10 V keithley.source_current = 0 # Sets the source current to 0 mA keithley.enable_source() # Enables the source output keithley.measure_resistance() keithley.measure_voltage() keithley.ramp_to_current(5e-3) # Ramps the current to 5 mA except: raise ConnectionError("Unable to connect to the Keithley 2450.") list_current = [] list_voltage = [] list_resistance = [] liste_temps_mesure = [] liste_temps = [] while int(tempsreel) < t_acquisition : #list_current.append(keithley.current) list_voltage.append(keithley.voltage) list_resistance.append(keithley.resistance) temps = time.time() liste_temps_mesure.append(temps) tempsreel = temps - liste_temps_mesure[0] liste_temps.append(tempsreel) print(f"{tempsreel}, {keithley.resistance}, {keithley.voltage}") sheet['A'+str(1)].value = 'Temps (s)' #sheet['B'+str(1)].value = 'Current (A)' sheet['C'+str(1)].value = 'Voltage (V)' sheet['D'+str(1)].value = 'Resistance' for i in range(0,len(liste_temps)): sheet['A'+str(i+2)].value = liste_temps[i] #sheet['B'+str(i+2)].value = list_current[i] sheet['C'+str(i+2)].value = list_voltage[i] sheet['D'+str(i+2)].value = list_resistance[i] wb.save('Data_sourcemetre.xlsx') print('Data saved !')
Sending and receiving a signal at the same time
I’m working in python on a raspberry pi. I’m trying to send out a signal on a motor controller, and then receive a signal with a sensing hat after it pass through my plant (an RC filter in this case). The important thing is I want to generate the output and read the input as close to simultaneously as possible. I was hoping to use multiprocessing to have a thread send the signal while the other read the incoming signal. But I keep getting confused on how threads work in python. In short is it possible to do 2 different tasks with multiprocessing and then repeat those tasks (sending and reading a signal) until a condition is met. (like in a while loop) (Edited with Code) from __future__ import print_function from PyQt5.QtWidgets import QAction from pyqtgraph.Qt import QtGui, QtCore from adafruit_motorkit import MotorKit import pyqtgraph as pg import sys from sys import stdout import numpy as np from daqhats import mcc118, OptionFlags, HatIDs, HatError from daqhats_utils import select_hat_device, enum_mask_to_string, \ chan_list_to_mask from decimal import * import math import time getcontext().prec = 3 total_samples_read = 0 READ_ALL_AVAILABLE = -1 channelData = np.zeros(4, dtype=float) CURSOR_BACK_2 = '\x1b[2D' ERASE_TO_END_OF_LINE = '\x1b[0K' # for plotting data ######################################## scan_rate = 1000 # scan rate in hz maxtime = 30 # second s to run for Datatime = np.zeros(maxtime * scan_rate, dtype=float)#List of times when smaples are taken Data1 = np.zeros(maxtime * scan_rate, dtype=float) #sampels taken data_index = 0 # Maximum index of data points taken dt = Decimal(1 / scan_rate) # difference in time between indexes of Datatime display_index = 0 # maximum index of Data being displayed on plot ################################# # variables for Data logger ########################## is_scanning = False channels = [0] channel_mask = chan_list_to_mask(channels) num_channels = len(channels) samples_per_channel = 0 options = OptionFlags.CONTINUOUS ###################################### startedTime = 0 # time at program start myTime = 0 # time since program started try: address = select_hat_device(HatIDs.MCC_118) hat = mcc118(address) except (HatError, ValueError) as err: print('\n', err) class MainWindow(pg.GraphicsWindow): def __init__(self, *args, **kwargs): super(pg.GraphicsWindow, self).__init__(*args, **kwargs) self.delay = 30 #ms self.quit = QAction("Quit", self) self.quit.triggered.connect(self.clean_close) self.timer = QtCore.QTimer() self.timer.setInterval(self.delay) self.timer.timeout.connect(self.update_plot) # plots data and runs calibrate between trials def update_plot(self): global display_index, Datatime, Data1 kit.motor1.throttle = .4 + .2 * math.cos((time.time()-startedTime)* 2 * np.pi* 1) # 1hz sinusiod out of motor if data_index < len(Data1): Collect_Data() plot.setXRange(0, 20, padding=0) plot.setXRange(0, 20, padding=0) curve.setData(Datatime[:display_index], Data1[:display_index]) display_index += 1 app.processEvents() def clean_close(self): self.close() # starts data collection def Collect_Data(): global is_scanning """ This function is executed automatically when the module is run directly. """ # Store the channels in a list and convert the list to a channel mask that # can be passed as a parameter to the MCC 118 functions. try: # Select an MCC 118 HAT device to use. # actual_scan_rate = hat.a_in_scan_actual_rate(num_channels, scan_rate) # Configure and start the scan. # Since the continuous option is being used, the samples_per_channel # parameter is ignored if the value is less than the default internal # buffer size (10000 * num_channels in this case). If a larger internal # buffer size is desired, set the value of this parameter accordingly. if not is_scanning: hat.a_in_scan_start(channel_mask, samples_per_channel, scan_rate, options) is_scanning = True try: read_and_display_data(hat, num_channels) except KeyboardInterrupt: # Clear the '^C' from the display. print(CURSOR_BACK_2, ERASE_TO_END_OF_LINE, '\n') print('Stopping') hat.a_in_scan_stop() hat.a_in_scan_cleanup() except (HatError, ValueError) as err: print('\n', err) # reads Data off of Hat and adds to Data1 def read_and_display_data(hat, num_channels): global channelData, data_index, Datatime, Data1 total_samples_read = 0 read_request_size = READ_ALL_AVAILABLE # When doing a continuous scan, the timeout value will be ignored in the # call to a_in_scan_read because we will be requesting that all available # samples (up to the default buffer size) be returned. timeout = 5.0 # Read all of the available samples (up to the size of the read_buffer which # is specified by the user_buffer_size). Since the read_request_size is set # to -1 (READ_ALL_AVAILABLE), this function returns immediately with # whatever samples are available (up to user_buffer_size) and the timeout # parameter is ignored. trigger = True while trigger == True: read_result = hat.a_in_scan_read(read_request_size, timeout) # Check for an overrun error if read_result.hardware_overrun: print('\n\nHardware overrun\n') break elif read_result.buffer_overrun: print('\n\nBuffer overrun\n') break samples_read_per_channel = int(len(read_result.data) / num_channels) total_samples_read += samples_read_per_channel # adds all data in buffer to data to be plotted. count = 0 if samples_read_per_channel > 0: index = samples_read_per_channel * num_channels - num_channels while count < samples_read_per_channel: for i in range(num_channels): channelData[i] = read_result.data[index + i] if data_index < len(Data1): Data1[data_index] = channelData[0] Datatime[data_index] = float(dt * Decimal(data_index)) data_index += 1 count += 1 trigger = False stdout.flush() if __name__ == '__main__': app = QtGui.QApplication([]) win = MainWindow() # display window plot = win.addPlot(1, 0) curve = plot.plot() win.show() kit = MotorKit() # implements motor driver kit.motor1.throttle = .4 # values 1 is 5v and 0 is 0 volts startedTime = time.time() # u = .2*math.cos(t * 2*np.pi*1) win.timer.start() sys.exit(app.exec_())
Give out value of a function variable
I have a code for a VoiceActivityDetector and want to give out the value speech_ratio which is in a function I tried to set up a new function to print out the value def __init__(self, wave_input_filename): self._read_wav(wave_input_filename)._convert_to_mono() self.sample_window = 0.02 #20 ms self.sample_overlap = 0.01 #10ms self.speech_window = 0.5 #half a second self.speech_energy_threshold = 0.6 #60% of energy in voice band self.speech_start_band = 300 self.speech_end_band = 3000 #self.speech_ratio = 0 def detect_speech(self): """ Detects speech regions based on ratio between speech band energy and total energy. Output is array of window numbers and speech flags (1 - speech, 0 - nonspeech). """ detected_windows = np.array([]) sample_window = int(self.rate * self.sample_window) sample_overlap = int(self.rate * self.sample_overlap) data = self.data sample_start = 0 start_band = self.speech_start_band end_band = self.speech_end_band while (sample_start < (len(data) - sample_window)): sample_end = sample_start + sample_window if sample_end>=len(data): sample_end = len(data)-1 data_window = data[sample_start:sample_end] energy_freq = self._calculate_normalized_energy(data_window) sum_voice_energy = self._sum_energy_in_band(energy_freq, start_band, end_band) sum_full_energy = sum(energy_freq.values()) speech_ratio = sum_voice_energy/sum_full_energy #self.speech_ratio2 = speech_ratio # Hipothesis is that when there is a speech sequence we have ratio of energies more than Threshold speech_ratio = speech_ratio>self.speech_energy_threshold detected_windows = np.append(detected_windows,[sample_start, speech_ratio]) sample_start += sample_overlap detected_windows = detected_windows.reshape(int(len(detected_windows)/2),2) detected_windows[:,1] = self._smooth_speech_detection(detected_windows) return detected_windows def printing(self): print(self.speech_ratio) return self.speech_ratio When I set speech_ratio as a variable in the init it does not change the variable later on in the detect_speech function. If I do not initialize speech_ratio in the init function it wont be a attribute of my object at all.
You use self.speech_ratio to try and print the value; you should use the same expression to assign to it.
Correct configuration of Aubio / Alsaaudio
I am trying to use aubio and python for a school project, here's the goal : detect when someone emit two sounds, each with a length of 2s, and with an interval between them of max 3s. The second one need to be higher than the first one. When these conditions are met, the program send a Wake-On-Lan package (not implemented in current code). import alsaaudio import numpy as np import aubio import time import threading class Audio_watcher: # constants samplerate = 44100 win_s = 2048 hop_s = win_s // 2 framesize = hop_s nb_samples = 20 tone_duration = 2.0 per_sampling = tone_duration / nb_samples tone_max_interval = 3.0 tone_diff_ratio = 2 def __init__(self): self.last_frequencies = np.zeros(Audio_watcher.nb_samples) self.last_energies = np.zeros(Audio_watcher.nb_samples) self.detected_tone = 0 # set up audio input recorder = alsaaudio.PCM(type=alsaaudio.PCM_CAPTURE) recorder.setperiodsize(Audio_watcher.framesize) recorder.setrate(Audio_watcher.samplerate) recorder.setformat(alsaaudio.PCM_FORMAT_FLOAT_LE) recorder.setchannels(1) self.recorder = recorder pitcher = aubio.pitch("default", Audio_watcher.win_s, Audio_watcher.hop_s, Audio_watcher.samplerate) pitcher.set_unit("Hz") pitcher.set_silence(-40) self.pitcher = pitcher # A filter f = aubio.digital_filter(7) f.set_a_weighting(Audio_watcher.samplerate) self.f = f def get_audio(self): # read and convert data from audio input _, data = self.recorder.read() samples = np.fromstring(data, dtype=aubio.float_type) filtered_samples = self.f(samples) print(filtered_samples) # pitch and energy of current frame freq = self.pitcher(filtered_samples)[0] print(freq) self.last_frequencies = np.roll(self.last_frequencies, 1) self.last_frequencies[0] = freq self.last_energies = np.roll(self.last_energies, 1) self.last_energies[0] = np.sum(filtered_samples**2)/len(filtered_samples) threading.Timer(Audio_watcher.per_sampling, self.get_audio).start() def reset_detected_tone(): self.detected_tone = 0 def detect_tone(self): std_last = np.std(self.last_frequencies) if std_last <= 200 and std_last > 0: mean_freq = np.mean(self.last_frequencies) if self.detected_tone == 0: self.detected_tone = mean_freq threading.Timer(Audio_watcher.tone_max_interval, self.reset_detected_tone).start() elif mean_freq > Audio_watcher.tone_diff_ratio * self.detected_tone: print('wol') threading.Timer(Audio_watcher.tone_duration, self.detect_tone).start() aw = Audio_watcher() aw.get_audio() aw.detect_tone() However with this code I get a great delay between the sounds and their detection, I think it has to do with the recorder being called only one time every 0.1s, but I can't find how to give correct parameters to aubio. Does anyone knows how to configure the constants so it works ? Thanks a lot !
Found out what was causing this error, I needed to put the code that sets up the audio input in the get_audio function so it renewed everytime
How do I get close event to work in wxPython using AUIManager?
How would I add another event to the pane created in our GUI manager class (below). I want to detect when the x button closes the pane. I've tried using the same format as wx.EVT_MENU for wx.EVT_CLOSE but it didn't work. def popup_panel(self, p): """ Add a panel object to the AUI manager :param p: panel object to add to the AUI manager :return: ID of the event associated with the new panel [int] """ ID = wx.NewId() self.panels[str(ID)] = p self.graph_num += 1 if p.window_caption.split()[0] in NOT_SO_GRAPH_LIST: windowcaption = p.window_caption else: windowcaption = 'Graph'#p.window_caption windowname = p.window_name # Append nummber captions = self._get_plotpanel_captions() while (1): caption = windowcaption + '%s'% str(self.graph_num) if caption not in captions: break self.graph_num += 1 # protection from forever-loop: max num = 1000 if self.graph_num > 1000: break if p.window_caption.split()[0] not in NOT_SO_GRAPH_LIST: p.window_caption = caption #p.window_caption = windowcaption+ str(self.graph_num) p.window_name = windowname + str(self.graph_num) style1 = self.__gui_style & GUIFRAME.FIXED_PANEL style2 = self.__gui_style & GUIFRAME.FLOATING_PANEL if style1 == GUIFRAME.FIXED_PANEL: self._mgr.AddPane(p, wx.aui.AuiPaneInfo(). Name(p.window_name). Caption(p.window_caption). Position(10). Floatable(). Right(). Dock(). MinimizeButton(). Resizable(True). # Use a large best size to make sure the AUI # manager takes all the available space BestSize(wx.Size(PLOPANEL_WIDTH, PLOPANEL_HEIGTH))) self._popup_fixed_panel(p) elif style2 == GUIFRAME.FLOATING_PANEL: self._mgr.AddPane(p, wx.aui.AuiPaneInfo(). Name(p.window_name).Caption(p.window_caption). MinimizeButton(). Resizable(True). # Use a large best size to make sure the AUI # manager takes all the available space BestSize(wx.Size(PLOPANEL_WIDTH, PLOPANEL_HEIGTH))) self._popup_floating_panel(p) # Register for showing/hiding the panel wx.EVT_MENU(self, ID, self.on_view) if p not in self.plot_panels.values() and p.group_id != None: self.plot_panels[ID] = p if len(self.plot_panels) == 1: self.panel_on_focus = p self.set_panel_on_focus(None) if self._data_panel is not None and \ self._plotting_plugin is not None: ind = self._data_panel.cb_plotpanel.FindString('None') if ind != wx.NOT_FOUND: self._data_panel.cb_plotpanel.Delete(ind) if caption not in self._data_panel.cb_plotpanel.GetItems(): self._data_panel.cb_plotpanel.Append(str(caption), p) return ID I want to be able to pick up the event in the plotting child class. def create_panel_helper(self, new_panel, data, group_id, title=None): """ """ ## Set group ID if available ## Assign data properties to the new create panel new_panel.set_manager(self) new_panel.group_id = group_id if group_id not in data.list_group_id: data.list_group_id.append(group_id) if title is None: title = data.title new_panel.window_caption = title new_panel.window_name = data.title event_id = self.parent.popup_panel(new_panel) #remove the default item in the menu if len(self.plot_panels) == 0: pos = self.menu.FindItem(DEFAULT_MENU_ITEM_LABEL) if pos != -1: self.menu.Delete(DEFAULT_MENU_ITEM_ID) # Set UID to allow us to reference the panel later new_panel.uid = event_id # Ship the plottable to its panel wx.CallAfter(new_panel.plot_data, data) self.plot_panels[new_panel.group_id] = new_panel # Set Graph menu and help string helpString = 'Show/Hide Graph: ' for plot in new_panel.plots.itervalues(): helpString += (' ' + plot.label + ';') self.menu.AppendCheckItem(event_id, new_panel.window_caption, helpString) self.menu.Check(event_id, IS_WIN) wx.EVT_MENU(self.parent, event_id, self._on_check_menu) wx.EVT_CLOSE(self.parent, event_id, self._on_close_panel) wx.EVT_SHOW(new_panel, self._on_show_panel)
Did you try catching wx.aui.EVT_AUINOTEBOOK_PAGE_CLOSE or wx.aui.EVT_AUINOTEBOOK_PAGE_CLOSED? I would think that would do what you want. I am assuming you're using wx.aui rather than wx.agw.aui. I suspect the latter is similar though. EDIT: Oops. I read this wrong. I thought the OP wanted to know about AUINotebook. The event you're probably looking for is wx.aui.EVT_AUI_PANE_CLOSE