NRF24L01 issue with Raspberry Pi and Raspberry Pi Pico - python-3.x

I've tried to communicate my tiny Raspberry Pi Zero 2W and Raspberry Pi Pico with NRF24L01. After my researchs and tryings I decided to the projects on the internet usualy not working. After sifting through alternatives and libraries, I decided to use lib_nrf24 library at Raspberry Pi and nrf24l01.py library at Raspberry Pi Pico. When I look carefully, I saw the libraries very similar with variable names. There is some configuration parameters both of them. I tried to set the parameters in the same way in both files. And I created a sender code on Raspberry Pi Pico and create basic receiver code at Raspberry Pi Zero 2W. But it didn't work. How can I solve this issue?
Raspberry Pi Pico Code:
from machine import Pin, SPI
import struct
import time
from nrf24l01 import NRF24L01
csn = Pin(15, mode=Pin.OUT, value=1)
ce = Pin(14, mode=Pin.OUT, value=0)
pipes = (b"\xf1\xf1\xf0\xf0\xfe0", b"\xe0\xe0\xf1\xf1\xe0")
def setup():
nrf = NRF24L01(SPI(0), csn, ce, payload_size=6)
nrf.open_tx_pipe(pipes[0])
nrf.open_rx_pipe(1, pipes[1])
nrf.start_listening()
return nrf
def dataSend(nrf):
while True:
testValue = 5
print("Mesafe: ", distance, "cm")
try:
nrf.send(struct.pack("i", distance))
time.sleep(0.1)
except OSError:
print('message lost')
def auto_ack(nrf):
nrf.reg_write(0x01, 0b11111000) # enable auto-ack on all pipes
nrf = setup()
auto_ack(nrf)
dataSend(nrf)
Raspberry Pi Zero 2W Code:
import RPi.GPIO as GPIO
import time
import spidev
from lib_nrf24 import NRF24
GPIO.setmode(GPIO.BCM)
pipes = [[0xE0, 0xE0, 0xF1, 0xF1, 0xE0], [0xF1, 0xF1, 0xF0, 0xF0, 0xE0]]
radio = NRF24(GPIO,spidev.SpiDev())
radio.begin(0, 25)
radio.setPayloadSize(32)
radio.setChannel(0x05)
radio.setDataRate(NRF24.BR_1MBPS)
radio.setPALevel(NRF24.PA_MIN)
radio.openReadingPipe(1, pipes[0])
radio.printDetails()
while len(sendMessage) < 32:
sendMessage.append(0)
while True:
start = time.time()
radio.startListening()
while not radio.available(0):
time.sleep(1/100)
if time.time() - start > 2:
print("Timed out.")
break
radio.stopListening()
time.sleep(3)
Except thoose codes, when thoose codes not working I've changed some parameters in library files both of them.
**Parameters of nrf24l01.py library at Raspberry Pi Pico:
**
# nRF24L01+ registers
CONFIG = const(0x00)
EN_RXADDR = const(0x02)
SETUP_AW = const(0x03)
SETUP_RETR = const(0x04)
RF_CH = const(0x05)
RF_SETUP = const(0x06)
STATUS = const(0x07)
RX_ADDR_P0 = const(0x0A)
TX_ADDR = const(0x10)
RX_PW_P0 = const(0x11)
FIFO_STATUS = const(0x17)
DYNPD = const(0x1C)
# CONFIG register
EN_CRC = const(0x08) # enable CRC
CRCO = const(0x04) # CRC encoding scheme; 0=1 byte, 1=2 bytes
PWR_UP = const(0x02) # 1=power up, 0=power down
PRIM_RX = const(0x01) # RX/TX control; 0=PTX, 1=PRX
# RF_SETUP register
POWER_0 = const(0x00) # -18 dBm
POWER_1 = const(0x02) # -12 dBm
POWER_2 = const(0x04) # -6 dBm
POWER_3 = const(0x06) # 0 dBm
SPEED_1M = const(0x00)
SPEED_2M = const(0x08)
SPEED_250K = const(0x20)
# STATUS register
RX_DR = const(0x40) # RX data ready; write 1 to clear
TX_DS = const(0x20) # TX data sent; write 1 to clear
MAX_RT = const(0x10) # max retransmits reached; write 1 to clear
# FIFO_STATUS register
RX_EMPTY = const(0x01) # 1 if RX FIFO is empty
# constants for instructions
R_RX_PL_WID = const(0x60) # read RX payload widthx"
R_RX_PAYLOAD = const(0x61) # read RX payload
W_TX_PAYLOAD = const(0xA0) # write TX payload
FLUSH_TX = const(0xE1) # flush TX FIFO
FLUSH_RX = const(0xE2) # flush RX FIFO
NOP = const(0xFF) # use to read STATUS register
**Parameters of lib_nrf24.py library at Raspberry Pi Zero2W:
**
MAX_CHANNEL = 127
MAX_PAYLOAD_SIZE = 32
# PA Levels
PA_MIN = 0
PA_LOW = 1
PA_HIGH = 2
PA_MAX = 3
PA_ERROR = 4
# Bit rates
BR_1MBPS = 0
BR_2MBPS = 1
BR_250KBPS = 2
# CRC
CRC_DISABLED = 0
CRC_8 = 1
CRC_16 = 2
CRC_ENABLED = 3
# Registers
CONFIG = 0x00
EN_AA = 0x01
EN_RXADDR = 0x02
SETUP_AW = 0x03
SETUP_RETR = 0x04
RF_CH = 0x05
RF_SETUP = 0x06
STATUS = 0x07
OBSERVE_TX = 0x08
CD = 0x09
RX_ADDR_P0 = 0x0A
RX_ADDR_P1 = 0x0B
RX_ADDR_P2 = 0x0C
RX_ADDR_P3 = 0x0D
RX_ADDR_P4 = 0x0E
RX_ADDR_P5 = 0x0F
TX_ADDR = 0x10
RX_PW_P0 = 0x11
RX_PW_P1 = 0x12
RX_PW_P2 = 0x13
RX_PW_P3 = 0x14
RX_PW_P4 = 0x15
RX_PW_P5 = 0x16
FIFO_STATUS = 0x17
DYNPD = 0x1C
FEATURE = 0x1D
# Bit Mnemonics */
MASK_RX_DR = 6
MASK_TX_DS = 5
MASK_MAX_RT = 4
EN_CRC = 3
CRCO = 2
PWR_UP = 1
PRIM_RX = 0
ENAA_P5 = 5
ENAA_P4 = 4
ENAA_P3 = 3
ENAA_P2 = 2
ENAA_P1 = 1
ENAA_P0 = 0
ERX_P5 = 5
ERX_P4 = 4
ERX_P3 = 3
ERX_P2 = 2
ERX_P1 = 1
ERX_P0 = 0
AW = 0
ARD = 4
ARC = 0
PLL_LOCK = 4
RF_DR = 3
RF_PWR = 6
RX_DR = 6
TX_DS = 5
MAX_RT = 4
RX_P_NO = 1
TX_FULL = 0
PLOS_CNT = 4
ARC_CNT = 0
TX_REUSE = 6
FIFO_FULL = 5
TX_EMPTY = 4
RX_FULL = 1
RX_EMPTY = 0
DPL_P5 = 5
DPL_P4 = 4
DPL_P3 = 3
DPL_P2 = 2
DPL_P1 = 1
DPL_P0 = 0
EN_DPL = 2
EN_ACK_PAY = 1
EN_DYN_ACK = 0
# Instruction Mnemonics
R_REGISTER = 0x00
W_REGISTER = 0x20
REGISTER_MASK = 0x1F
ACTIVATE = 0x50
R_RX_PL_WID = 0x60
R_RX_PAYLOAD = 0x61
W_TX_PAYLOAD = 0xA0
W_ACK_PAYLOAD = 0xA8
FLUSH_TX = 0xE1
FLUSH_RX = 0xE2
REUSE_TX_PL = 0xE3
NOP = 0xFF
I changed the library parameters to be the same but still could not communicate between the two devices. I used different values with these parameters to understand where the problem is, for example, I changed the receiver and sender pipe values by crossing each other, but it still didn't work. I think the codes work well but my library RF configuration parameters are false.

Related

Obtain decimal netmask from prefix length python 3.x

I created this code because I was not able to find any functional that accomplishes my requirement.
If you can reduce it will be better.
Just enter de prefix lenght from 1 to 32 and you will get the decimal mask.
This code help me with my scripts for cisco.
import math
#Netmask octets
octet1 = [0,0,0,0,0,0,0,0]
octet2 = [0,0,0,0,0,0,0,0]
octet3 = [0,0,0,0,0,0,0,0]
octet4 = [0,0,0,0,0,0,0,0]
#POW list
pow_list = [7,6,5,4,3,2,1,0]
#Introduce prefix lenght
mask = int(input("Introduce the prefix lenght: "))
#According to the number of bits we will change the array elements from 0 to 1
while mask >= 25 and mask <= 32:
octet4[mask-25] = 1
mask -= 1
while mask >= 17 and mask <= 24:
octet3[mask-17] = 1
mask -= 1
while mask >= 9 and mask <= 16:
octet2[mask-9] = 1
mask -= 1
while mask >= 1 and mask <= 8:
octet1[mask-1] = 1
mask -= 1
#Obtain the number of ones
ones1 = octet1.count(1)
ones2 = octet2.count(1)
ones3 = octet3.count(1)
ones4 = octet4.count(1)
#Summary and reuslt of each octet.
sum1 = 0
for i in range(0,ones1):
sum1 = sum1 + math.pow(2,pow_list[i])
sum1 = int(sum1)
sum2 = 0
for i in range(0,ones2):
sum2 = sum2 + math.pow(2,pow_list[i])
sum2 = int(sum2)
sum3 = 0
for i in range(0,ones3):
sum3 = sum3 + math.pow(2,pow_list[i])
sum3 = int(sum3)
sum4 = 0
for i in range(0,ones4):
sum4 = sum4 + math.pow(2,pow_list[i])
sum4 = int(sum4)
#Join the results with a "."
decimal_netmask = str(sum1) + "." + str(sum2) + "." + str(sum3) + "." + str(sum4)
#Result
print("Decimal netmask is: "+ decimal_netmask)
Result:
Introduce the prefix lenght: 23
Decimal netmask is: 255.255.254.0
As you are probably doing more than just converting CIDR to netmask, I recommend checking out the built-in library ipaddress
from ipaddress import ip_network
cidr = input("Introduce the prefix length: ")
decimal_netmask = str(ip_network(f'0.0.0.0/{cidr}').netmask)
You can simplify your code by computing the overall mask value as an integer using the formula:
mask = 2**32 - 2**(32-prefix_length)
Then you can compute the 4 8-bit parts of the mask (by shifting and masking), appending the results to a list and then finally joining each element of the list with .:
def decimal_netmask(prefix_length):
mask = 2**32 - 2**(32-prefix_length)
octets = []
for _ in range(4):
octets.append(str(mask & 255))
mask >>= 8
return '.'.join(reversed(octets))
for pl in range(33):
print(f'{pl:3d}\t{decimal_netmask(pl)}')
Output:
0 0.0.0.0
1 128.0.0.0
2 192.0.0.0
3 224.0.0.0
4 240.0.0.0
5 248.0.0.0
6 252.0.0.0
7 254.0.0.0
8 255.0.0.0
9 255.128.0.0
10 255.192.0.0
11 255.224.0.0
12 255.240.0.0
13 255.248.0.0
14 255.252.0.0
15 255.254.0.0
16 255.255.0.0
17 255.255.128.0
18 255.255.192.0
19 255.255.224.0
20 255.255.240.0
21 255.255.248.0
22 255.255.252.0
23 255.255.254.0
24 255.255.255.0
25 255.255.255.128
26 255.255.255.192
27 255.255.255.224
28 255.255.255.240
29 255.255.255.248
30 255.255.255.252
31 255.255.255.254
32 255.255.255.255

Reading a sensor register using SMBus / I2C

I have a problem while reading the my lsm9ds1 accelerator sensor registers. It always displays the same values.
My setup is a Raspberry Pi 4 and the Sense HAT which has this sensor integrated. I don't want to use the Sense HAT library but use the python3-smbus library to better understand I2C.
The registers I want to read from are OUT_X_XL, OUT_Y_XL and OUT_Z_XL which return linear values expressed as a 16-bit word in two's complement. Here is the Datasheet. I tried to convert them with two different functions I found, but got both times an error so I just wanted to see if there just would be a change if I move the sensor around.
Here is my output:
Complements Register 1 X: 221 Y: 59 Z: 254
Complements Register 2 X: 104 Y: 146 Z: 112
Complements Register 1 X: 221 Y: 59 Z: 254
Complements Register 2 X: 104 Y: 146 Z: 112
Do I have to do something different with the values or should I read the register differently? Preferably I would also like the values to be something close to float values what you would expect from an acceleration sensor. Any help is very appreciated.
Here is my code:
from smbus import SMBus
import time
i2c_adress = 0x1c # DEVICE ACCELEROMETER
# DEFINITION OF REGISTERS
OUT_X_XL1 = 0x28 # linear acceleration sensor output registers
OUT_X_XL2 = 0x29
OUT_Y_XL1 = 0x2A
OUT_Y_XL2 = 0x2B
OUT_Z_XL1 = 0x2C
OUT_Z_XL2 = 0x2D
def main():
while (True):
i2cbus = SMBus(1) # Create new I2C bus
comp_acc_x2 = i2cbus.read_byte_data(i2c_adress, OUT_X_XL2)
comp_acc_y2 = i2cbus.read_byte_data(i2c_adress, OUT_Y_XL2)
comp_acc_z2 = i2cbus.read_byte_data(i2c_adress, OUT_Z_XL2)
comp_acc_x1 = i2cbus.read_byte_data(i2c_adress, OUT_X_XL1)
comp_acc_y1 = i2cbus.read_byte_data(i2c_adress, OUT_Y_XL1)
comp_acc_z1 = i2cbus.read_byte_data(i2c_adress, OUT_Z_XL1)
print(f" Complements Register 1 X: {comp_acc_x1} Y: {comp_acc_y1} Z: {comp_acc_z1}")
print(f" Complements Register 2 X: {comp_acc_x2} Y: {comp_acc_y2} Z: {comp_acc_z2}")
time.sleep(0.5)
if __name__ == "__main__":
main()
Other code using pigpio library:
import pigpio
import time
i2c_adress = 0x1c # DEVICE ACCELEROMETER
#DEFINITION OF REGISTERS
OUT_X_XL1 = 0x28 # linear acceleration sensor output registers
OUT_X_XL2 = 0x29
OUT_Y_XL1 = 0x2A
OUT_Y_XL2 = 0x2B
OUT_Z_XL1 = 0x2C
OUT_Z_XL2 = 0x2D
def main():
pi = pigpio.pi()
acc_sensor = pi.i2c_open(1, i2c_adress)
while (True):
comp_acc_x2 = pi.i2c_read_byte_data(acc_sensor, OUT_X_XL2)
comp_acc_y2 = pi.i2c_read_byte_data(acc_sensor, OUT_Y_XL2)
comp_acc_z2 = pi.i2c_read_byte_data(acc_sensor, OUT_Z_XL2)
comp_acc_x1 = pi.i2c_read_byte_data(acc_sensor, OUT_X_XL1)
comp_acc_y1 = pi.i2c_read_byte_data(acc_sensor, OUT_Y_XL1)
comp_acc_z1 = pi.i2c_read_byte_data(acc_sensor, OUT_Z_XL1)
print(f" Complements Register 1 X: {comp_acc_x1} Y: {comp_acc_y1} Z: {comp_acc_z1}")
print(f" Complements Register 2 X: {comp_acc_x2} Y: {comp_acc_y2} Z: {comp_acc_z2}")
time.sleep(0.5)
if __name__ == "__main__":
main()

How to solve issue of maximum iteration getting exceeded in python gekko in this case (explained in the body)?

I am trying to track multiple set-points in the case of interacting quadruple tank system process. Here, the upper limits of tanks are 25 and lower limits are 0. I want to track the set-point values of 5,12,7 and 5. Although, I am able to track the initial 3 set-points (i.e. 5,12 and 7), I am not able to track the last set-point due to solver exceeding max. iterations. I have attached the code below->
#MHE+MPC model
#to measure computational time of the code
start=time.time()
#Process Model
p = GEKKO(remote=False)
process=0
p.time = [0,0.5]
noise = 0.25
#Constants
g = 981
g1 = .9
g2 = .9
A1=32
A3=32
A2=32
A4=32
a1=0.057
a3=0.057
a2=0.057
a4=0.057
init_h=5
#Controlled process variables
p.h1=p.SV(lb=0,ub=25)
p.h2=p.SV(lb=0,ub=25)
p.h3=p.SV(lb=0,ub=25)
p.h4=p.SV(lb=0,ub=25)
#Manipulated process variables
p.v1=p.MV(value=3.15,lb=0.1,ub=8)
p.v2=p.MV(value=3.15,lb=0.1,ub=8)
#Parameters of process
p.k1=p.Param(value=3.14,lb=0,ub=10)
p.k2=p.Param(value=3.14,lb=0,ub=10)
#Equations process
p.Equation(A1*p.h1.dt()==a3*((2*g*p.h3)**0.5)-(a1*((2*g*p.h1)**0.5))+(g1*p.k1*p.v1))
p.Equation(A2*p.h2.dt()==a4*((2*g*p.h4)**0.5)-(a2*((2*g*p.h2)**0.5))+(g2*p.k2*p.v2))
p.Equation(A3*p.h3.dt()==-a3*((2*g*p.h3)**0.5)+((1-g2)*p.k2*p.v2))
p.Equation(A4*p.h4.dt()==-a4*((2*g*p.h4)**0.5)+((1-g1)*p.k1*p.v1))
#options
p.options.IMODE = 4
#p.h1.TAU=-10^10
#p.h2.TAU=-10^10
#%% MHE Model
m = GEKKO(remote=False)
#prediction horizon
m.time = np.linspace(0,40,41) #0-20 by 0.5 -- discretization must match simulation
#MHE control, manipulated variables and parameters
m.h1=m.CV(lb=0,ub=25)
m.h2=m.CV(lb=0,ub=25)
m.h3=m.SV(lb=0,ub=25)
m.h4=m.SV(lb=0,ub=25)
m.v1=m.MV(value=3.15,lb=0.10,ub=8)
m.v2=m.MV(value=3.15,lb=0.10,ub=8)
m.k1=m.FV(value=3.14,lb=0,ub=10)
m.k2=m.FV(value=3.14,lb=0,ub=10)
#m.h1.TAU=0
#m.h2.TAU=0
#Equations
m.Equation(A1*m.h1.dt()==a3*((2*g*m.h3)**0.5)-(a1*((2*g*m.h1)**0.5))+(g1*m.k1*m.v1))
m.Equation(A2*m.h2.dt()==a4*((2*g*m.h4)**0.5)-(a2*((2*g*m.h2)**0.5))+(g2*m.k2*m.v2))
m.Equation(A3*m.h3.dt()==-a3*((2*g*m.h3)**0.5)+((1-g2)*m.k2*m.v2))
m.Equation(A4*m.h4.dt()==-a4*((2*g*m.h4)**0.5)+((1-g1)*m.k1*m.v1))
#Options
m.options.IMODE = 5 #MHE
m.options.EV_TYPE = 2
# STATUS = 0, optimizer doesn't adjust value
# STATUS = 1, optimizer can adjust
m.v1.STATUS = 0
m.v2.STATUS = 0
m.k1.STATUS=1
m.k2.STATUS=1
m.h1.STATUS = 1
m.h2.STATUS = 1
#m.h3.STATUS = 0
#m.h4.STATUS = 0
# FSTATUS = 0, no measurement
# FSTATUS = 1, measurement used to update model
m.v1.FSTATUS = 1
m.v2.FSTATUS = 1
m.k1.FSTATUS=0
m.k2.FSTATUS=0
m.h1.FSTATUS = 1
m.h2.FSTATUS = 1
m.h3.FSTATUS = 1
m.h4.FSTATUS = 1
#m.options.MAX_ITER=1000
m.options.SOLVER=3
m.options.NODES=3
#%% MPC Model
c = GEKKO(remote=False)
c.time = np.linspace(0,10,11) #0-5 by 0.5 -- discretization must match simulation
c.v1=c.MV(value=3.15,lb=0.10,ub=8)
c.v2=c.MV(value=3.15,lb=0.10,ub=8)
c.k1=c.FV(value=3.14,lb=0,ub=10)
c.k2=c.FV(value=3.14,lb=0,ub=10)
#Variables
c.h1=c.CV(lb=0,ub=25)
c.h2=c.CV(lb=0,ub=25)
c.h3=c.SV(lb=0,ub=25)
c.h4=c.SV(lb=0,ub=25)
#Equations
c.Equation(A1*c.h1.dt()==a3*((2*g*c.h3)**0.5)-(a1*((2*g*c.h1)**0.5))+(g1*c.k1*c.v1))
c.Equation(A2*c.h2.dt()==a4*((2*g*c.h4)**0.5)-(a2*((2*g*c.h2)**0.5))+(g2*c.k2*c.v2))
c.Equation(A3*c.h3.dt()==-a3*((2*g*c.h3)**0.5)+((1-g2)*c.k2*c.v2))
c.Equation(A4*c.h4.dt()==-a4*((2*g*c.h4)**0.5)+((1-g1)*c.k1*c.v1))
#Options
c.options.IMODE = 6 #MPC
c.options.CV_TYPE = 2
# STATUS = 0, optimizer doesn't adjust value
# STATUS = 1, optimizer can adjust
c.v1.STATUS = 1
c.v2.STATUS = 1
c.k1.STATUS=0
c.k2.STATUS=0
c.h1.STATUS = 1
c.h2.STATUS = 1
#c.h3.STATUS = 0
#c.h4.STATUS = 0
# FSTATUS = 0, no measurement
# FSTATUS = 1, measurement used to update model
c.v1.FSTATUS = 0
c.v2.FSTATUS = 0
c.k1.FSTATUS=1
c.k2.FSTATUS=1
c.h1.FSTATUS = 1
c.h2.FSTATUS = 1
c.h3.FSTATUS = 1
c.h4.FSTATUS = 1
sp=5
c.h1.SP=sp
c.h2.SP=sp
p1 = GEKKO(remote=False)
p1.time = [0,0.5]
#Parameters
p1.h1=p1.CV(lb=0,ub=25)
p1.h2=p1.CV(lb=0,ub=25)
p1.h3=p1.CV(lb=0,ub=25)
p1.h4=p1.CV(lb=0,ub=25)
p1.v1=p1.MV(value=3.15,lb=0.1,ub=8)
p1.v2=p1.MV(value=3.15,lb=0.1,ub=8)
p1.k1=p1.Param(lb=0,ub=10,value=3.14)
p1.k2=p1.Param(lb=0,ub=10,value=3.14)
#Equations
p1.Equation(A1*p1.h1.dt()==a3*((2*g*p1.h3)**0.5)-a1*((2*g*p1.h1)**0.5)+g1*p1.k1*p1.v1)
p1.Equation(A2*p1.h2.dt()==a4*((2*g*p1.h4)**0.5)-a2*((2*g*p1.h2)**0.5)+g2*p1.k2*p1.v2)
p1.Equation(A3*p1.h3.dt()==-a3*((2*g*p1.h3)**0.5)+(1-g2)*p1.k2*p1.v2)
p1.Equation(A4*p1.h4.dt()==-a4*((2*g*p1.h4)**0.5)+(1-g1)*p1.k1*p1.v1)
#options
p1.options.IMODE = 4
#%% problem configuration
# number of cycles
cycles = 480
# noise level
#%% run process, estimator and control for cycles
h1_meas = np.empty(cycles)
h2_meas =np.empty(cycles)
h3_meas =np.empty(cycles)
h4_meas=np.empty(cycles)
h1_est = np.empty(cycles)
h2_est = np.empty(cycles)
h3_est = np.empty(cycles)
h4_est = np.empty(cycles)
h1_plant=np.empty(cycles)
h2_plant=np.empty(cycles)
h3_plant=np.empty(cycles)
h4_plant=np.empty(cycles)
h1_measured=np.empty(cycles)
h2_measured=np.empty(cycles)
h3_measured=np.empty(cycles)
h4_measured=np.empty(cycles)
v1_est = np.empty(cycles)
v2_est = np.empty(cycles)
k1_est = np.empty(cycles)
k2_est = np.empty(cycles)
u_cont_k1 = np.empty(cycles)
u_cont_k2 = np.empty(cycles)
sp_store = np.empty(cycles)
sum_est=np.empty(cycles)
sum_model=np.empty(cycles)
# Create plot
plt.figure(figsize=(10,7))
plt.ion()
plt.show()
p.MAX_ITER=20
c.MAX_ITER=20
m.MAX_ITER=20
p1.MAX_ITER=20
for i in range(cycles):
print(i)
# set point changes
if i==cycles/4:
sp = 12
elif i==2*cycles/4:
sp = 7
elif i==3*cycles/4:
sp = 5
sp_store[i] = sp
c.h1.SP=sp
c.h2.SP=sp
c.k1.MEAS = m.k1.NEWVAL
c.k2.MEAS = m.k2.NEWVAL
if p.options.SOLVESTATUS == 1:
# print("going:",i)
c.h1.MEAS = p.h1.MODEL
c.h2.MEAS = p.h2.MODEL
c.h3.MEAS = p.h3.MODEL
c.h4.MEAS = p.h4.MODEL
print(i,'Plant Model:',p.h1.MODEL,p.h2.MODEL,p.h3.MODEL,p.h4.MODEL)
c.solve(disp=False,debug=0)
#print("NEWVAL:",i,c.u,c.u.NEWVAL)
u_cont_k1[i] = c.v1.NEWVAL
u_cont_k2[i] = c.v2.NEWVAL
#print("Horizon:",i,c.h1[0:],c.h2[0:])
#print("Move:",i,c.v1.NEWVAL,c.v2.NEWVAL)
## process simulator
#load control move
p.v1.MEAS = u_cont_k1[i]
p.v2.MEAS = u_cont_k2[i]
#simulate
p.solve(disp=False,debug=0)
#plant model
p1.k1=3.14
p1.k2=3.14
p1.v1.MEAS = u_cont_k1[i]
p1.v2.MEAS = u_cont_k2[i]
p1.solve(disp=False,debug=0)
h1_plant[i]=p1.h1.MODEL
h2_plant[i]=p1.h2.MODEL
h3_plant[i]=p1.h3.MODEL
h4_plant[i]=p1.h4.MODEL
h1_measured[i]=p1.h1.MODEL+(random()*2)*noise
h2_measured[i]=p1.h2.MODEL+(random()*2)*noise
h3_measured[i]=p1.h3.MODEL+(random()*2)*noise
h4_measured[i]=p1.h4.MODEL+(random()*2)*noise
#print("Model process output:",i,p.h1.MODEL,p.h2.MODEL,p.h3.MODEL,p.h4.MODEL)
#load output with white noise
h1_meas[i] = p.h1.MODEL+(random()-0.5)*noise
h2_meas[i] = p.h2.MODEL+(random()-0.5)*noise
h3_meas[i] = p.h3.MODEL+(random()-0.5)*noise
h4_meas[i] = p.h4.MODEL+(random()-0.5)*noise
#Only MPC
## estimator
#load input and measured output
m.v1.MEAS = u_cont_k1[i]
m.v2.MEAS = u_cont_k2[i]
#m.h1.MEAS = h1_meas[i]+(random()*2)*noise
#m.h2.MEAS = h2_meas[i]+(random()*2)*noise
#m.h3.MEAS = h3_meas[i]+(random()*2)*noise
#m.h4.MEAS = h4_meas[i]+(random()*2)*noise
m.h1.MEAS = h1_meas[i]
m.h2.MEAS = h2_meas[i]
m.h3.MEAS = h3_meas[i]
m.h4.MEAS = h4_meas[i]
#m.COLDSTART=2
#optimize parameters
m.solve(disp=False,debug=0)
#store results
if i>=process:
h1_est[i] = m.h1.MODEL
h2_est[i] = m.h2.MODEL
h3_est[i] = m.h3.MODEL
h4_est[i] = m.h4.MODEL
v1_est[i] = m.v1.NEWVAL
v2_est[i] = m.v2.NEWVAL
k1_est[i]= m.k1.NEWVAL
k2_est[i] = m.k2.NEWVAL
print("Estimated h:",i,h1_est[i],h2_est[i],h3_est[i],h4_est[i])
print("Estimated k:",i,k1_est[i],k2_est[i],p.k1[0],p.k2[0])
print("Estimated v:",i,v1_est[i],v2_est[i])
print("dh1/dt:",(a3*((2*g*h3_est[i])**0.5)-(a1*((2*g*h3_est[i])**0.5))+(g1*k1_est[i]*v1_est[i]))/A3)
print("dh2/dt:",(a4*((2*g*h4_est[i])**0.5)-(a2*((2*g*h2_est[i])**0.5))+(g2*k2_est[i]*v2_est[i]))/A2)
print("dh3/dt:",(-a3*((2*g*h3_est[i])**0.5)+((1-g2)*k2_est[i]*v2_est[i]))/A3)
print("dh4/dt:",(-a4*((2*g*h4_est[i])**0.5)+((1-g1)*k1_est[i]*v1_est[i]))/A4)
if i%1==0:
plt.clf()
plt.subplot(4,1,1)
#plt.plot(h1_meas[0:i])
#plt.plot(h2_meas[0:i])
#plt.plot(h3_meas[0:i])
#plt.plot(h4_meas[0:i])
plt.plot(h1_est[0:i])
plt.plot(h2_est[0:i])
plt.plot(sp_store[0:i])
plt.subplot(4,1,2)
plt.plot(h3_est[0:i])
plt.plot(h4_est[0:i])
#plt.legend(('h1_pred','h2_pred','h3_pred','h4_pred'))
plt.subplot(4,1,3)
plt.plot(k1_est[0:i])
plt.plot(k2_est[0:i])
plt.subplot(4,1,4)
plt.plot(v1_est[0:i])
plt.plot(v2_est[0:i])
plt.draw()
plt.pause(0.05)
end=time.time()
print("total time:",end-start)
I feel there is some issue with my MHE+MPC code. However, I am not able to realize the mistake?
Nice application. I needed a few imports to make the script work. These may be loaded automatically for you.
from gekko import GEKKO
import time
import numpy as np
import matplotlib.pyplot as plt
from random import random
The script solves successfully if a lower bound is included on all the level variables (1e-6). There is a problem when the level goes below zero or is at zero when using m.sqrt(). This small adjustment helps it solve successfully so it doesn't get into a region where it is undefined. Gekko solvers can't deal with imaginary numbers.
Although the solution is successful, it appears that the control performance oscillates. There may need to be some tuning of the application.

How to set up optional parameter in LDP Layer using scapy

I am trying to build LDPHello packets, but I am not able to add optional parameter like IPv4 Transport layer using scapy.
I have done this:
ip = IP(src=src_ipv4, dst= '224.0.0.2', proto=17, ttl=1)
udp = UDP(sport=646, dport=646)
hello = LDPHello(params=[180,0,0,0,0,"2.2.2.2",0])
packet = ip / udp / hello
Which gives me output like:
###[ IP ]###
version = 4
ihl = 5
tos = 0x0
len = 54
id = 1
flags =
frag = 0
ttl = 1
proto = udp
chksum = 0x6c44
src = 10.110.99.2
dst = 224.0.0.2
\options \
###[ UDP ]###
sport = 646
dport = 646
len = 34
chksum = 0xa34c
###[ LDP ]###
version = 1
len = 22
id = 2.2.2.2
space = 0
###[ LDPHello ]###
u = 0
type = 256
len = 12
id = 0
params = [180, 0, 0]
By LDPHello Definition from scapy:
class LDPHello(_LDP_Packet):
name = "LDPHello"
fields_desc = [BitField("u", 0, 1),
BitField("type", 0x0100, 15),
ShortField("len", None),
IntField("id", 0),
CommonHelloTLVField("params", [180, 0, 0])]
After CommonHelloTLVField there is no field where we can add optional parameter like IPv4 transport Address.
While by RFC the total data structure is like:
0 1 2 3
0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
|0| Hello (0x0100) | Message Length |
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
| Message ID |
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
| Common Hello Parameters TLV |
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
| Optional Parameters |
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
I don't know how to do get output like:Contains IPv4 Transport Layer

Cent OS - sysctl.conf not working

The settings i have applied in my sysctl.conf are not working. Not on reboot or after applying it using sysctl -p
Below are my sysctl.conf settings. Can someone take a look and tell me what may be causing the issue?
# Controls IP packet forwarding
net.ipv4.ip_forward = 0
# Controls source route verification
net.ipv4.conf.default.rp_filter = 1
# Do not accept source routing
net.ipv4.conf.default.accept_source_route = 0
# Controls the System Request debugging functionality of the kernel
kernel.sysrq = 0
# Controls whether core dumps will append the PID to the core filename.
# Useful for debugging multi-threaded applications.
kernel.core_uses_pid = 1
# Controls the use of TCP syncookies
net.ipv4.tcp_syncookies = 1
# Controls the default maxmimum size of a mesage queue
kernel.msgmnb = 65536
# Controls the maximum size of a message, in bytes
kernel.msgmax = 65536
# Controls the maximum shared segment size, in bytes
kernel.shmmax = 68719476736
# Controls the maximum number of shared memory segments, in pages
kernel.shmall = 4294967296
net.ipv4.tcp_keepalive_time = 4
net.ipv4.tcp_keepalive_probes = 1
net.ipv4.tcp_keepalive_intvl = 2
net.ipv4.tcp_fin_timeout = 4
net.ipv4.tcp_no_metrics_save = 1
net.ipv4.tcp_window_scaling = 1
net.ipv4.tcp_rfc1337 = 1
net.ipv4.tcp_congestion_control= cubic
net.ipv4.tcp_tw_recycle = 1
net.ipv4.tcp_tw_reuse = 1
net.ipv4.route.flush = 1
net.ipv4.tcp_orphan_retries = 0
net.core.netdev_max_backlog = 400000
net.core.optmem_max = 10000000
net.core.rmem_default = 10000000
net.core.rmem_max = 10000000
net.core.somaxconn = 100000
net.core.wmem_default = 10000000
net.core.wmem_max = 10000000
net.ipv4.conf.all.rp_filter = 1
net.ipv4.ip_local_port_range = 1024 65535
net.ipv4.tcp_ecn = 0
net.ipv4.tcp_max_syn_backlog = 12000
net.ipv4.tcp_max_tw_buckets = 2000000
net.ipv4.tcp_mem = 10240 8738000 825829120
net.ipv4.tcp_rmem = 10240 8738000 825829120
net.ipv4.tcp_sack = 1
net.ipv4.tcp_timestamps = 1
net.ipv4.tcp_wmem = 10240 8738000 825829120
net.netfilter.nf_conntrack_max = 768000
net.netfilter.nf_conntrack_generic_timeout = 4
net.netfilter.nf_conntrack_tcp_timeout_established = 4
net.netfilter.nf_conntrack_tcp_timeout_time_wait = 4
net.netfilter.nf_conntrack_tcp_timeout_fin_wait = 4
net.netfilter.nf_conntrack_tcp_timeout_close_wait = 4
net.netfilter.nf_conntrack_tcp_timeout_last_ack = 4
net.netfilter.nf_conntrack_tcp_timeout_syn_sent = 4
net.netfilter.nf_conntrack_tcp_timeout_syn_recv = 4
net.netfilter.nf_conntrack_tcp_timeout_close = 4

Resources