Pico W server stops after a while loop

RP2040 based microcontroller boards running MicroPython.
Target audience: MicroPython users with an RP2040 boards.
This does not include conventional Linux-based Raspberry Pi boards.
Post Reply
hero04
Posts: 4
Joined: Wed Aug 24, 2022 12:29 pm

Pico W server stops after a while loop

Post by hero04 » Wed Aug 24, 2022 12:38 pm

Hi all! Fairly a newbie here:). I am doing a project where I want to control bunch of neopixels from Pico W via making requests from an android app. It works well for some basic neopixel lighting modes such as fixed single color or some sweep effects. However I want to add some modes that loops until I send a request to Pico w to say stop, off or another mode. Currently there are 4 modes and the request/response logic works well.

But when I add something like =>

Code: Select all

while currentMode is continuousFlashing:
	continuousFlashing()
it resets/removes connection between the pico w server and the clients. From this point on i am no longer able to send requests to change modes or stop it. Any help will be appreciated.

User avatar
jimmo
Posts: 2754
Joined: Tue Aug 08, 2017 1:57 am
Location: Sydney, Australia
Contact:

Re: Pico W server stops after a while loop

Post by jimmo » Wed Aug 24, 2022 1:58 pm

hero04 wrote:
Wed Aug 24, 2022 12:38 pm
it resets/removes connection between the pico w server and the clients. From this point on i am no longer able to send requests to change modes or stop it. Any help will be appreciated.
Can you try adding a short sleep between each frame (maybe time.sleep_ms(10)) and see if the problem goes away.

hero04
Posts: 4
Joined: Wed Aug 24, 2022 12:29 pm

Re: Pico W server stops after a while loop

Post by hero04 » Mon Aug 29, 2022 12:24 pm

Thanks Jimmo for the response. I saw this very late:(. By the frame you mean at the end of the loop that I want it to continue until I say not to do so? I remember I have tried that but not sure 100%. Will try that and post an update.

User avatar
jimmo
Posts: 2754
Joined: Tue Aug 08, 2017 1:57 am
Location: Sydney, Australia
Contact:

Re: Pico W server stops after a while loop

Post by jimmo » Mon Aug 29, 2022 1:38 pm

hero04 wrote:
Mon Aug 29, 2022 12:24 pm
Thanks Jimmo for the response. I saw this very late:(. By the frame you mean at the end of the loop that I want it to continue until I say not to do so? I remember I have tried that but not sure 100%. Will try that and post an update.
I think I would need to see your code... can you post it here?

BUt conceptually I imagine that you have a loop that does a non-blocking read from the socket to get the next command (or cancel the current operation). And then it draws the next frame of the current animation.

i.e.

Code: Select all

while True:
  msg = socket.read()
  if msg:
    change_mode(msg)
  draw_next_frame()
So in this case you'd either add a short timeout to the socket read, or a time.sleep() in draw_next_frame (essentially to limit the frame rate).

hero04
Posts: 4
Joined: Wed Aug 24, 2022 12:29 pm

Re: Pico W server stops after a while loop

Post by hero04 » Sun Sep 04, 2022 11:31 am

here is the script that i cannot find a way to fix it.

Code: Select all

while True:
    try:
        cl, addr = s.accept()
        print('Client connected from', addr)
        r = cl.recv(1024)
        r = str(r)
        print('request', r)
            
        strip = Neopixel(numpix, 0, 10, "GRB")
        brown = strip.colorHSV(165, 42, 42)
        orange = strip.colorHSV(255, 165, 0)
        pink = strip.colorHSV(255, 192, 203)
        yellow = strip.colorHSV(255, 255, 0)
        purple = strip.colorHSV(128, 0, 128)
        red = strip.colorHSV(0,255,122)
        green = strip.colorHSV(21845, 255, 122)
        blue = strip.colorHSV(43691, 255, 122)
        
        #Turn OFF all pixels
        if r.find('ledStatus=off') > -1:
            currentMode = 'off'
            status = 'Off'
            print('LED OFF')
            led.value(0)
            ledStatus = '{"ledStatus": "Off"}'
            cl.send('HTTP/1.0 200 OK\r\nContent-type: application/json\r\nAccess-Control-Allow-Origin: *\r\n\r\n')
            cl.send(ledStatus)
            cl.close()
            stop_all()
        
        #CHASE mode
        if r.find('ledStatus=chase') > -1:
            currentMode = 'chase'
            stop_all()
            status = 'on'
            print('LED ON')
            led.value(1)
            ledStatus = '{"ledStatus": "chase"}'
            cl.send('HTTP/1.0 200 OK\r\nContent-type: application/json\r\nAccess-Control-Allow-Origin: *\r\n\r\n')
            cl.send(ledStatus)
            cl.close()
            #color_chase(strip, red, blue, 0.1, numpix)
            while currentMode is 'chase':
                if currentMode is not 'chase':
                    break
                for i in range(numpix):
                    strip.set_pixel(i-1, (0,0,0))
                    strip.set_pixel(i, blue)
                    strip.show()
                    time.sleep(0.1)
                time.sleep(0.1)
                for j in range(numpix - 1, -1,-1):
                    if j < (numpix -1):
                        strip.set_pixel(j+1, (0,0,0))
                    strip.set_pixel(j, red)
                    strip.show()
                    time.sleep(0.1)

I want it to loop in the chase mode until I send a different request to turn off or change the mode.

User avatar
dhylands
Posts: 3821
Joined: Mon Jan 06, 2014 6:08 pm
Location: Peachland, BC, Canada
Contact:

Re: Pico W server stops after a while loop

Post by dhylands » Tue Sep 06, 2022 5:33 pm

If you use a try/except, make sure that your except prints out the reason (except perhaps for expected exceptions).

Otherwise if you have a simple typo or other error, it will get "eaten" by your exception handler and your code isn't actually running.

hero04
Posts: 4
Joined: Wed Aug 24, 2022 12:29 pm

Re: Pico W server stops after a while loop

Post by hero04 » Sat Sep 10, 2022 10:58 am

thanks for the tip Dave. It does have an except block, however I dont have enough experience in python especially with the server stuff.

Here is the except block:

Code: Select all

    except OSError as e:
        cl.close()
        print('Connection closed')
And here is the whole script file for webserver:

Code: Select all

import rp2
import network
import ubinascii
import machine
import urequests as requests
import time
from secrets import secrets
import socket
from neopixel import Neopixel
from neo_sweep import color_chase
from fixed_colors import fixed_color
from stop_neopixel import stop_all


# Set country to avoid possible errors
rp2.country('NL')
wlan = network.WLAN(network.STA_IF)
wlan.active(True)
# If you need to disable powersaving mode
wlan.config(pm = 0xa11140)
# See the MAC address in the wireless chip OTP
mac = ubinascii.hexlify(network.WLAN().config('mac'),':').decode()
print('mac = ' + mac)

# Load login data from different file for safety reasons
ssid = secrets['ssid']
pw = secrets['pw']
wlan.connect(ssid, pw)
# Wait for connection with 10 second timeout
timeout = 10
while timeout > 0:
    if wlan.status() < 0 or wlan.status() >= 3:
        break
    timeout -= 1
    print('Waiting for connection...')
    time.sleep(1)

# Define blinking function for onboard LED to indicate error codes    
def blink_onboard_led(num_blinks):
    led = machine.Pin('LED', machine.Pin.OUT)
    for i in range(num_blinks):
        led.on()
        time.sleep(.2)
        led.off()
        time.sleep(.2)
    
wlan_status = wlan.status()
blink_onboard_led(wlan_status)

if wlan_status != 3:
    raise RuntimeError('Wi-Fi connection failed')
else:
    print('Connected')
    status = wlan.ifconfig()
    print('ip = ' + status[0])
    
# HTTP server with socket
addr = socket.getaddrinfo('0.0.0.0', 80)[0][-1]

s = socket.socket()
s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
s.bind(addr)
s.listen(1)
print('Listening on', addr)

led = machine.Pin('LED', machine.Pin.OUT)

numpix = 30
brightness = 125
currentMode = 'off'
ledStatus = 'off'

# Listen for connections
while True:
    try:
        cl, addr = s.accept()
        print('Client connected from', addr)
        r = cl.recv(1024)
        r = str(r)
        print('request', r)
        

        
        if r.find('update') > -1:
            cl.send('HTTP/1.0 200 OK\r\nContent-type: application/json\r\nAccess-Control-Allow-Origin: *\r\n\r\n')
            #cl.send(ledStatus)
            cl.send('{"numpix":' + str(numpix) + ','+ '"currentMode":'+ '"'+str(currentMode)+'"' + ',' +'"brightness":'+ str(brightness) +'}')
            print('from update', ledStatus)
            print('{"ledStatus":' + str(numpix) + ','+ '"currentMode":"'+ str(ledStatus) +'"}')
            #print('{"currentMode":' + str(currentMode) +',' + '"numpix":'+ str(numpix) +'}')
            cl.close()
        time.sleep(0.1)
        
        #adjust number of pixels if requested
        if r.find('numpix') > -1:
            pixelnum = r[r.index('numpix=') + len('numpix='):-1]
            numpix = int(pixelnum)
            cl.send('HTTP/1.0 200 OK\r\nContent-type: application/json\r\nAccess-Control-Allow-Origin: *\r\n\r\n')
            cl.send('{"ledStatus":' + pixelnum + '}')
            cl.close()
            print('{"ledStatus":' + pixelnum + '}')
        time.sleep(0.1)
        
        if r.find('brightness') > -1:
            brightness = r[r.index('brightness=')+ len('brightness='):-1]
            brightness = int(brightness)
            print(brightness)
            #stop_all()
            strip.brightness(int(brightness))
            strip.show()
            cl.send('HTTP/1.0 200 OK\r\nContent-type: application/json\r\nAccess-Control-Allow-Origin: *\r\n\r\n')
            cl.send('{"ledStatus":' + '"brightness"}')
            cl.close()
            
        strip = Neopixel(numpix, 0, 10, "GRB")
        strip.brightness(brightness)
        brown = strip.colorHSV(165, 42, 42)
        orange = strip.colorHSV(255, 165, 0)
        pink = strip.colorHSV(255, 192, 203)
        yellow = strip.colorHSV(255, 255, 0)
        purple = strip.colorHSV(128, 0, 128)
        red = strip.colorHSV(0,255,122)
        green = strip.colorHSV(21845, 255, 122)
        blue = strip.colorHSV(43691, 255, 122)
        time.sleep(0.1)
        
        #Turn OFF all pixels
        if r.find('ledStatus=off') > -1:
            currentMode = 'off'
            status = 'Off'
            print('LED OFF')
            led.value(0)
            ledStatus = '{"ledStatus": "Off"}'
            cl.send('HTTP/1.0 200 OK\r\nContent-type: application/json\r\nAccess-Control-Allow-Origin: *\r\n\r\n')
            cl.send(ledStatus)
            cl.close()
            stop_all()
        time.sleep(0.1)
        
        #CHASE mode
        if r.find('ledStatus=chase') > -1:
            currentMode = 'chase'
            stop_all()
            status = 'on'
            print('LED ON')
            led.value(1)
            ledStatus = '{"ledStatus": "chase"}'
            cl.send('HTTP/1.0 200 OK\r\nContent-type: application/json\r\nAccess-Control-Allow-Origin: *\r\n\r\n')
            cl.send(ledStatus)
            cl.close()
            #color_chase(strip, red, blue, 0.1, numpix)
            while currentMode is 'chase':
                if currentMode is not 'chase':
                    break
                for i in range(numpix):
                    strip.set_pixel(i-1, (0,0,0))
                    strip.set_pixel(i, blue)
                    strip.show()
                    time.sleep(0.1)
                time.sleep(0.1)
                for j in range(numpix - 1, -1,-1):
                    if j < (numpix -1):
                        strip.set_pixel(j+1, (0,0,0))
                    strip.set_pixel(j, red)
                    strip.show()
                    time.sleep(0.1)
        time.sleep(0.1)
        
        if r.find('ledStatus=section') > -1:
            unSplitted = r.split('section&')[1].split(',')
            startIndex = int(unSplitted[0])
            endIndex = int(unSplitted[1])
            color = unSplitted[2].split('-')
            print(color)
            hue =  color[0]
            sat = color[1]
            val = color[2][:-1]
            color = strip.colorHSV(int(hue),int(sat),int(val))
            #strip.fill(color)
            strip.set_pixel_line(startIndex, endIndex, (int(hue),int(sat),int(val)))
            strip.show()
            print(color)
        time.sleep(0.1)
            #currentMode = '{"ledStatus":' + '"fixedColor"' + ','+ '"r":' + str(red) + ','+ '"g":'+ str(green) + "," + '"b":' + str(blue) + '}'
        
        if r.find('line-gradient') > -1:
            currentMode = 'line-gradient'
            stop_all()
            strip.set_pixel_line_gradient(0, (numpix - 1), blue, red)
            strip.show()
            cl.send('HTTP/1.0 200 OK\r\nContent-type: application/json\r\nAccess-Control-Allow-Origin: *\r\n\r\n')
            cl.send('{"ledStatus":' + '"line-gradient"}')
            cl.close()
            
        #fixedcolor test
        if r.find('fixed_color') > -1:
            
            stop_all()
            rgb = r.split('fixed_color&')[1].split(',')
            print(rgb)
            red = rgb[0]
            red = int(red)
            
            green = rgb[1]
            green = int(green)
            print(green)
            
            blue = rgb[2]
            blue = blue[:-1]
            print(blue)
            blue = int(blue)
            currentMode= 'fixed'
            #currentMode = '{"ledStatus":' + '"fixedColor"' + ','+ '"r":' + str(red) + ','+ '"g":'+ str(green) + "," + '"b":' + str(blue) + '}'
            cl.send('HTTP/1.0 200 OK\r\nContent-type: application/json\r\nAccess-Control-Allow-Origin: *\r\n\r\n')
            cl.send('{"ledStatus":' + '"fixedColor"' + ','+ '"r":' + str(red) + ','+ '"g":'+ str(green) + "," + '"b":' + str(blue) + '}')
            cl.close()
            ledStatus = '{"ledStatus": "fixed"}'
            fixed_color(strip, red,green,blue)
            print('test fixed color')
            print('{"ledStatus":'  + str(red) + ','+ str(green)+ ',' + str(blue) + '}')
        time.sleep(0.1)
            
            
        #response = get_html('index.html')
        #cl.send('HTTP/1.0 200 OK\r\nContent-type: application/json\r\n')
        #cl.send('HTTP/1.0 200 OK\r\nContent-type: application/json\r\nAccess-Control-Allow-Origin: *\r\n\r\n')
        #cl.send(ledStatus)
        print(ledStatus)
        #cl.close()
        
    except OSError as e:
        cl.close()
        print('Connection closed')

Post Reply