Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[Bug] Cityhub refuses to turn off #692

Closed
BatteryPoweredBricks opened this issue Jul 28, 2022 · 16 comments
Closed

[Bug] Cityhub refuses to turn off #692

BatteryPoweredBricks opened this issue Jul 28, 2022 · 16 comments
Assignees
Labels
bug Something isn't working hub: cityhub Issues related to the LEGO Powered Up Smart hub (Hub No. 4) software: pybricks-micropython Issues with Pybricks MicroPython firmware (or EV3 runtime)

Comments

@BatteryPoweredBricks
Copy link

I am having an issue where my Cityhubs refuse to power off. After running my trains I press the button on the hub to stop the program (hub LED is then blinking blue). Then I hold down the button to try to power it off but most often it just starts blinking again.

I am currently using the Beta version of Pybricks but I had the same issue before using the Beta version.

Bellow is a YouTube link to see what I'm experiencing.
https://youtu.be/cPMWrLPp1WQ

@BatteryPoweredBricks BatteryPoweredBricks added the triage Issues that have not been triaged yet label Jul 28, 2022
@BatteryPoweredBricks BatteryPoweredBricks changed the title [Bug] [Bug] Cityhub refuses to turn off Jul 28, 2022
@dlech dlech added bug Something isn't working hub: cityhub Issues related to the LEGO Powered Up Smart hub (Hub No. 4) software: pybricks-micropython Issues with Pybricks MicroPython firmware (or EV3 runtime) and removed triage Issues that have not been triaged yet labels Jul 28, 2022
@dlech
Copy link
Member

dlech commented Jul 28, 2022

Thanks for the bug report. I've observed the same thing on Move hub before, but not on the City hub.

Maybe we need to enable this hack for City hub too?

Or maybe we need to switch the gpio to input mode instead of output low?

@laurensvalk
Copy link
Member

Hi @BatteryPoweredBricks 👋 - thanks for coming over from the forums . It really helps :)

Does your code do anything with the button? If so, it would be great if you want to share your code here.

Which motors and sensors are connected in the video? This might help us reproduce the issue.

Could you also run the following script after the bug happens, and share what you see?

from pybricks.hubs import CityHub

hub = CityHub()

print("Voltage:", hub.battery.voltage())
print("Reset reason:", hub.system.reset_reason())

but not on the City hub.

We did have this related issue on City Hub before: #385

@BatteryPoweredBricks
Copy link
Author

BatteryPoweredBricks commented Jul 29, 2022

It's the program that was shared in the forum, I've only changed some of the settings. I'll attach it below.

Voltage: 7812
Reset reason: 0

Is the voltage low enough to cause issues? It certainly drives the train just fine. Is there a general rule for a minimum voltage to eliminate it as an factor when having issues?

I have 2 train motors attached to the hub.

# -----------------------------------------------
# MotorControl
#
# uses https://beta.pybricks.com/ , LEGO City hub, LEGO remote control
# connect 1 or 2 motors of any kind to Port A and/or B
#
# Version 2.7  
# -----------------------------------------------/
from pybricks.parameters import * # Color

# -----------------------------------------------
#  Set user defined values
# -----------------------------------------------

# define the two profiles
# profil_x = (minimun speed,maximum Speed,accelerate in steps of ..., wait for next acceleration(in ms)

Profil_A = (20,100,10,100)  #min,max,step,acc
Profil_B = (10,500,5,200)   #min,max,step,acc

# define direction of motors

dirMotorA = 1       # Direction 1 or -1
dirMotorB = -1       # Direction 1 or -1

autoacc = True      # accelarate continously when holding butten 

# -----------------------------------------------
#  Set general values
# -----------------------------------------------

# assign buttons to function1 
# syntax: function = "name"
# name may  be "A+","A-","A0","B+","B-","B0","CENTER"

UP = "A+"
DOWN = "A-"
STOP = "A0"
SWITCH = "CENTER"

mode=1              # start with function number...
watchdog = True    # "True" or "False": Stop motors when loosing remote connection
remoteTimeout =10   # hub waits x seconds for remote connect after starting hub
remoteName = "Blue"     # connect this remote only

# Color and brightness of Hub LEDs
LEDconn = Color.BLUE*0.5       # if Hub connected, color * brightness
LEDnotconn = Color.RED*0.5      # if Hub is not connect, color * brightness

LED_A = Color.BLUE*0.5       # Remote Profil_A, color * brightness
LED_B = Color.RED*0.5      # Remote Profil_B, color * brightness

# -----------------------------------------------
#  Import classes and functions
# -----------------------------------------------

from pybricks.pupdevices import DCMotor, Motor, Remote
from pybricks.parameters import Port, Stop, Button, Color
from pybricks.hubs import CityHub
from pybricks.tools import wait, StopWatch
from pybricks.iodevices import PUPDevice
from uerrno import ENODEV

# -----------------------------------------------
#  function 1 / drive motors
# -----------------------------------------------

def function1():

    vmax = profile[mode].vmax
    vmin = profile[mode].vmin
    accdelay =  profile[mode].acc
    step = profile[mode].step
  
    global v
   
    if CheckButton(UP) and not CheckButton(STOP) : 
        for x in range (1, step + 1):
            v = v + 1
            if v > vmax :
                v = vmax
            if v > 0 and v < vmin:    
                v = vmin
            if abs(v) < vmin:
                v = 0
            drive()
            wait (accdelay)  
            if v==0: 
                break 
        # further acceleration if button keeps pressed
        while autoacc == False and CheckButton(UP) :    
            wait (100)
        # avoid changing direction when reaching "0"     
        while v == 0 and  CheckButton(UP):  
            wait (100)

    if CheckButton(DOWN) and not CheckButton(STOP):
        for x in range (1, step + 1):
            v = v-1
            if v < vmax*-1 :
                v = vmax*-1
            if v < 0 and v > vmin*-1:    
                v = vmin*-1
            if abs(v) < vmin :
                v = 0   
            drive()
            wait (accdelay)  
            if v==0: 
                break 
        # further acceleration if button keeps pressed
        while autoacc == False and CheckButton(DOWN) :    
            wait (100)
        # avoid changing direction when reaching "0"
        while v == 0 and  CheckButton(DOWN) :    
            wait (100)
  
    if CheckButton(STOP): 
        v = 0
        drive()
        wait (100)    
        
class setprofile():
    def __init__(self,pr):
        self.vmin=pr[0]
        self.vmax=pr[1]
        self.step=pr[2]
        self.acc=pr[3]

profile = [0,0,0]
profile[1] = setprofile(Profil_A)
profile[2] = setprofile(Profil_B)

# -----------------------------------------------
#  function 2
# -----------------------------------------------
           
'''
def function2():
    if CheckButton(UP):
        timer[1].set(3000)
    if timer[1].check(): 
        print("Do something")
'''

# -----------------------------------------------
# general program routines and classes
# -----------------------------------------------

# ----CheckButton -------------------------------------------

def CheckButton(x):
    try:
        button = remote.buttons.pressed()
        if x == "A+"  : x = Button.LEFT_PLUS
        if x == "A-" : x = Button.LEFT_MINUS
        if x == "A0"  : x = Button.LEFT

        if x == "B+"  : x = Button.RIGHT_PLUS
        if x == "B-" : x = Button.RIGHT_MINUS
        if x == "B0"  : x = Button.RIGHT
    
        if x == "CENTER"  : x = Button.CENTER
        
        if x in button:
            return True
        else:
            return False
    except:
        return()

# ----delay -------------------------------------------

class delay:
    def __init__(self,id,time=0,watch=StopWatch(),busy=False):
        self.id=id
        self.time=time
        self.watch=watch
        self.busy=busy
        print ("Init Timer",id)
    # set a timer        
    def set(self,x):
        if  self.busy == False:
            self.busy = True
            self.watch.reset()
            self.time = x
            print("Timer",timer[1].id, "set to",x)
    #check if timer is reached, then return "True"
    def check(self):
        if self.busy == True:
            if self.watch.time() > self.time:
                self.busy = False
                self.time=0 
                print("Timer",timer[1].id, "stopped")
                return(True)
        else:
            return(False)

# ----drive -------------------------------------------

def drive():
    global vold
    global v
    print (v)
    if vold != v:
        # for each motor 1,2 
        for x in range(1,3):
            # set speed and direction
            s = v*round(motor[x].getDir())
            # real motor commands depending on motor type
            if motor[x].getDir() != 0 and motor[x].getType() == "Motor" : motor[x].obj.run(s*motor[x].getSpeed()) #  in 2.7
            if motor[x].getDir() != 0 and motor[x].getType() == "DCMotor" : motor[x].obj.dc(s) 
        vold = v
            
# ----portcheck -------------------------------------------

def portcheck(i):
    # list of motors, 1 +2 contain string "DC"
    devices = {
    1: "Wedo 2.0 DC Motor",
    2: "Train DC Motor",
    38: "BOOST Interactive Motor",
    46: "Technic Large Motor",
    47: "Technic Extra Large Motor",
    48: "SPIKE Medium Angular Motor",
    49: "SPIKE Large Angular Motor",
    75: "Technic Medium Angular Motor",
    76: "Technic Large Angular Motor",
}
    port = motor[i].getPort()
    # Try to get the device, if it is attached.
    try:
        device = PUPDevice(port)
    except OSError as ex:
        if ex.args[0] == ENODEV:
            # No device found on this port.
            motor[i].setType("---")
            print(port, ": not connected")
            return ("---")
        else:
            raise

    # Get the device id
    id = device.info()['id']
    
    # Look up the name.
    try:
        # get the attributes for tacho motors
        if "Motor" in devices[id] and not("DC" in devices[id]): 
            motor[i].setType("Motor")
            motor[i].obj = Motor(port)

            #new in 2.7
            devs_max_speed = {38:1530,46:1890,47:1980,48:1367,49:1278,75:1367,76:1278 }
            dspeed = devs_max_speed.get(PUPDevice(port).info()['id'], 1000)
            Motor(port).control.limits(speed=dspeed,acceleration=10000)
            motor[i].setSpeed(dspeed/100*0.9)

        # and set type for simple DC Motors    
        if "DC" in devices[id]:
            motor[i].setType("DCMotor")
            motor[i].obj = DCMotor(port)
            
    except KeyError:
        motor[i].stype("unkown")
        print(port, ":", "Unknown device with ID", id)
    wait(100)    
    print ("--")
    print(port, ":", devices[id], motor[i].getType(),motor[i].getSpeed(),motor[i].getAcc())

# ---- device  -------------------------------------------
    
class device():
    # store the device infos for each motor
    def __init__(self,port,dir):
        self.port = port
        self.dir = dir
        self.type=""
        self.speed=99
        self.acc=99
        self.obj=""
                
    def setType(self,x) : self.type = x
    def setSpeed(self,x): self.speed = x
    def setAcc(self,x)  : self.acc = x
    
    def getType(self)   : return self.type
    def getPort(self)   : return self.port
    def getDir(self)    : return self.dir
    def getSpeed(self)  : return self.speed
    def getAcc(self)    : return self.acc

# -----------------------------------------------
# globals
# -----------------------------------------------

v = 0
vold = 0
#remoteConnected = False

# -----------------------------------------------
# Ininitialize
# -----------------------------------------------

hub = CityHub()

#define timers
timer = [0,0,0]
timer[1] = delay(1)
timer[2] = delay(2)
           
#define motors
motor = [0,0,0]
motor[1] = device(Port.A,dirMotorA)
motor[2] = device(Port.B,dirMotorB)

# get the port properties
portcheck(1)
portcheck(2)    

# -----------------------------------------------
# remote connect
# -----------------------------------------------

hub.light.on(Color.RED)
print (hub.system.name())
try:
    remote = Remote(name=remoteName,timeout=remoteTimeout*1000)
except OSError as ex:
    hub.system.shutdown()

# -----------------------------------------------
# main loop
# -----------------------------------------------

while True:
   
    # --check if remote is connected ---------------------------------
    
    try:
        button = remote.buttons.pressed()
        hub.light.on(LEDconn)
        remoteConnected = True
    except OSError as ex:
        hub.light.on(LEDnotconn)
        print("Remote not connected")
        remoteConnected = False
       
        if watchdog == True:
            v=0
            drive()
        try:
            # reconnect remote
            remote = Remote(timeout=1000)
            wait(100)
            print("Remote reconnected")
            remoteConnected = True
        except OSError as ex:
            print("Remote not connected")

            
    if CheckButton(SWITCH):
        mode = mode+1
        if mode > 2: 
            mode = 1
        print (mode)
        if mode == 1 : remote.light.on(LED_A)
        if mode == 2 : remote.light.on(LED_B)    
   
        while CheckButton(SWITCH):
            button = remote.buttons.pressed()
            wait (100)

    if mode == 1 : function1()     
    if mode == 2 : function1()
    
    wait(10)
    

@laurensvalk
Copy link
Member

Thanks for sharing. The reset reason looks normal and the voltage is totally fine as well. The hub automatically shuts down at low voltage (5V), so I just wanted to rule that out. But this seems unrelated.

Does this also happen with smaller programs? For example like the small test snippet I just gave you.

Does it make a difference if you run the program as stand-alone (saved on the hub) or from the Pybricks Code app?

@BatteryPoweredBricks
Copy link
Author

I just tried with the program in stand-alone mode with the train program and the test program. Tried without a program loaded before and after playing a program from the app. Same result for all of them, just keeps blinking

@dlech
Copy link
Member

dlech commented Aug 1, 2022

Can we make a simpler test case to reproduce the problem? With the given program, I get:

Init Timer 1
Init Timer 2
Traceback (most recent call last):
  File "main.py", line 317, in <module>
  File "main.py", line 255, in portcheck
OSError: [Errno 16] EBUSY: Device or resource busy

So I am not able to reproduce the issue.

@laurensvalk
Copy link
Member

Can we make a simpler test case to reproduce the problem?

See:

I just tried with the program in stand-alone mode with the train program and the test program. Tried without a program loaded before and after playing a program from the app. Same result for all of them, just keeps blinking

@dlech
Copy link
Member

dlech commented Aug 1, 2022

Or maybe we need to switch the gpio to input mode instead of output low?

I tried this on the Move Hub and it seems to fix the issue (instead of the previous hack of leaving VCC on). But since I can't reproduce the issue on the City Hub, I will need someone who can to confirm on that hub using this firmware:

https://github.com/pybricks/pybricks-micropython/suites/7616058926/artifacts/316138802

@BatteryPoweredBricks
Copy link
Author

I can try it out, I'm not sure how to select the firmware file to download it to the hub though.

@dlech
Copy link
Member

dlech commented Aug 1, 2022

https://pybricks.com/install/technic-boost-city/#installing-the-latest-build-advanced

Once you download the firmware .zip file, you can drag and drop it on the flash firmware button at https://code.pybricks.com.

(Note, you will need to use https://code.pybricks.com since the button was removed in the beta version).

@BatteryPoweredBricks
Copy link
Author

I tried it on Ubuntu with Chromium and didn't get an error but it didn't load from the zip. In Windows / Chrome it says

"The firmware.metadata.py file contains missing or invalid entries. Fix it then try again."

@dlech
Copy link
Member

dlech commented Aug 1, 2022

Darn, I forgot the new firmware isn't compatible with the old Pybricks Code. There currently isn't a way to do it on Pybricks Beta. But if you have an Ubuntu machine, you can try this:

sudo apt update
sudo apt install pipx
pipx run pybricksdev flash ~/Downloads/cityhub-firmware.zip

@BatteryPoweredBricks
Copy link
Author

I knew this dual boot would come in handy, yeah that worked like a charm. The hub shuts down without issue. I replaced the main.py in the zip with the train program I'm using and that worked as well :).

@dlech
Copy link
Member

dlech commented Aug 1, 2022

Great, thanks for testing!

@BatteryPoweredBricks
Copy link
Author

Follow-up and a quick question. It seems my issue has to do with having a motor on port b, without it the hub turns off as it should. I plan to make a video soon that will feature this program and a dual motor setup, I was wondering when the firmware would be released with this fix implemented. It's no rush but I'm trying to schedule my next few videos out and didn't want to have to tell people to use Linux :)

@laurensvalk
Copy link
Member

didn't want to have to tell people to use Linux

I forgot the new firmware isn't compatible with the old Pybricks Code. There currently isn't a way to do it on Pybricks Beta.

Maybe we could allow dragging it into the settings pane.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
bug Something isn't working hub: cityhub Issues related to the LEGO Powered Up Smart hub (Hub No. 4) software: pybricks-micropython Issues with Pybricks MicroPython firmware (or EV3 runtime)
Projects
None yet
Development

No branches or pull requests

3 participants