def open_serial(self, config, baud, timeout):
     self.close_bg_serial()
     if self.ser is None:
         self.ser = util.setupSerial(config, baud, timeout)
         if self.ser is None:
             return False
     return True
示例#2
0
 def open_serial(self, config, baud, timeout):
     if self.ser:
         self.ser.close()
     self.ser = None
     self.ser = util.setupSerial(config, baud, timeout, 1.0, True)
     if self.ser is None:
         return False
     return True
示例#3
0
 def open_serial(self, config, baud, timeout):
     if self.ser:
         self.ser.close()
     self.ser = None
     self.ser = util.setupSerial(config, baud, timeout)
     if self.ser is None:
         return False
     return True
示例#4
0
        return {'status': 0, 'statusMessage': "Successfully paused logging."}
    else:
        return {'status': 1, 'statusMessage': "Logging already paused or stopped."}


def resumeLogging():
    global config
    logMessage("Continued logging data, as requested in web interface.")
    if config['dataLogging'] == 'paused':
        config = util.configSet(configFile, 'dataLogging', 'active')
        return {'status': 0, 'statusMessage': "Successfully continued logging."}
    else:
        return {'status': 1, 'statusMessage': "Logging was not paused."}

# bytes are read from nonblocking serial into this buffer and processed when the buffer contains a full line.
ser = util.setupSerial(config, time_out=0)

if not ser:
    exit(1)

logMessage("Notification: Script started for beer '" + urllib.unquote(config['beerName']) + "'")
# wait for 10 seconds to allow an Uno to reboot (in case an Uno is being used)
time.sleep(float(config.get('startupDelay', 10)))


logMessage("Checking software version on controller... ")
hwVersion = brewpiVersion.getVersionFromSerial(ser)
if hwVersion is None:
    logMessage("Warning: Cannot receive version number from controller. " +
               "Your controller is either not programmed or running a very old version of BrewPi. " +
               "Please upload a new version of BrewPi to your controller.")
示例#5
0
else:
    configFile = sys.argv[1]

if not os.path.exists(configFile):
    sys.exit('ERROR: Config file "%s" was not found!' % configFile)

config = util.readCfgWithDefaults(configFile)

print "***** BrewPi Windows Test Terminal ****"
print "This simple Python script lets you send commands to the Arduino."
print "It also echoes everything the Arduino returns."
print "On known debug ID's in JSON format, it expands the messages to the full message"
print "press 's' to send a string to the Arduino, press 'q' to quit"

# open serial port
ser = util.setupSerial(config)

if not ser:
    exit(1)

while 1:
    if msvcrt.kbhit():
        received = msvcrt.getch()
        if received == 's':
            print "type the string you want to send to the Arduino: "
            userInput = raw_input()
            print "sending: " + userInput
            ser.write(userInput)
        elif received == 'q':
            ser.close()
            exit()
                return self.__asciiToUnicode(lines[0])

    # remove extended ascii characters from string, because they can raise UnicodeDecodeError later
    def __asciiToUnicode(self, s):
        s = s.replace(chr(0xB0), '&deg')
        return unicode(s, 'ascii', 'ignore')

if __name__ == '__main__':
    # some test code that requests data from serial and processes the response json
    import simplejson
    import time
    import BrewPiUtil as util

    config_file = util.addSlash(sys.path[0]) + 'settings/config.cfg'
    config = util.readCfgWithDefaults(config_file)
    ser = util.setupSerial(config, time_out=0)
    if not ser:
        printStdErr("Could not open Serial Port")
        exit()

    bg_ser = BackGroundSerial(ser)
    bg_ser.start()

    success = 0
    fail = 0
    for i in range(1, 5):
        # request control variables 4 times. This would overrun buffer if it was not read in a background thread
        # the json decode will then fail, because the message is clipped
        bg_ser.write('v')
        bg_ser.write('v')
        bg_ser.write('v')
示例#7
0
def updateFromGitHub(userInput, beta, useDfu, restoreSettings=True, restoreDevices=True):
    import BrewPiUtil as util
    from gitHubReleases import gitHubReleases
    import brewpiVersion
    import programController as programmer

    configFile = util.scriptPath() + "/settings/config.cfg"
    config = util.readCfgWithDefaults(configFile)

    printStdErr("Stopping any running instances of BrewPi to check/update controller...")
    quitBrewPi(config["wwwPath"])

    hwVersion = None
    shield = None
    board = None
    family = None
    ser = None

    ### Get version number
    printStdErr("\nChecking current firmware version...")
    try:
        ser = util.setupSerial(config)
        hwVersion = brewpiVersion.getVersionFromSerial(ser)
        family = hwVersion.family
        shield = hwVersion.shield
        board = hwVersion.board

        printStdErr("Found " + hwVersion.toExtendedString() + " on port " + ser.name + "\n")
    except:
        if hwVersion is None:
            printStdErr(
                "Unable to receive version from controller.\n"
                "Is your controller unresponsive and do you wish to try restoring your firmware? [y/N]: "
            )
            choice = raw_input()
            if not any(choice == x for x in ["yes", "Yes", "YES", "yes", "y", "Y"]):
                printStdErr("Please make sure your controller is connected properly and try again.")
                return 0
            port, name = autoSerial.detect_port()
            if not port:
                printStdErr("Could not find compatible device in available serial ports.")
                return 0
            if "Particle" in name:
                family = "Particle"
                if "Photon" in name:
                    board = "photon"
                elif "Core" in name:
                    board = "core"
            elif "Arduino" in name:
                family = "Arduino"
                if "Leonardo" in name:
                    board = "leonardo"
                elif "Uno" in name:
                    board = "uno"

            if board is None:
                printStdErr("Unable to connect to controller, perhaps it is disconnected or otherwise unavailable.")
                return -1
            else:
                printStdErr("Will try to restore the firmware on your %s" % name)
                if family == "Arduino":
                    printStdErr(
                        "Assuming a Rev C shield. If this is not the case, please program your Arduino manually"
                    )
                    shield = "RevC"
                else:
                    printStdErr(
                        "Please put your controller in DFU mode now by holding the setup button during reset, until the LED blinks yellow."
                    )
                    printStdErr("Press Enter when ready.")
                    choice = raw_input()
                    useDfu = True  # use dfu mode when board is not responding to serial

    if ser:
        ser.close()  # close serial port
        ser = None

    if hwVersion:
        printStdErr("Current firmware version on controller: " + hwVersion.toString())
    else:
        restoreDevices = False
        restoreSettings = False

    printStdErr("\nChecking GitHub for available release...")
    releases = gitHubReleases("https://api.github.com/repos/BrewPi/firmware")

    availableTags = releases.getTags(beta)
    stableTags = releases.getTags(False)
    compatibleTags = []
    for tag in availableTags:
        url = None
        if family == "Arduino":
            url = releases.getBinUrl(tag, [board, shield, ".hex"])
        elif family == "Spark" or family == "Particle":
            url = releases.getBinUrl(tag, [board, "brewpi", ".bin"])
        if url is not None:
            compatibleTags.append(tag)

    if len(compatibleTags) == 0:
        printStdErr("No compatible releases found for %s %s" % (family, board))
        return -1

    # default tag is latest stable tag, or latest unstable tag if no stable tag is found
    default_choice = next((i for i, t in enumerate(compatibleTags) if t in stableTags), compatibleTags[0])
    tag = compatibleTags[default_choice]

    if userInput:
        print("\nAvailable releases:\n")
        for i, menu_tag in enumerate(compatibleTags):
            print("[%d] %s" % (i, menu_tag))
        print("[" + str(len(compatibleTags)) + "] Cancel firmware update")
        num_choices = len(compatibleTags)
        while 1:
            try:
                choice = raw_input(
                    "Enter the number [0-%d] of the version you want to program [default = %d (%s)]: "
                    % (num_choices, default_choice, tag)
                )
                if choice == "":
                    break
                else:
                    selection = int(choice)
            except ValueError:
                print("Use the number! [0-%d]" % num_choices)
                continue
            if selection == num_choices:
                return False  # choice = skip updating
            try:
                tag = compatibleTags[selection]
            except IndexError:
                print("Not a valid choice. Try again")
                continue
            break
    else:
        printStdErr("Latest version on GitHub: " + tag)

    if hwVersion is not None and not hwVersion.isNewer(tag):
        if hwVersion.isEqual(tag):
            printStdErr("You are already running version %s." % tag)
        else:
            printStdErr("Your current version is newer than %s." % tag)

        if userInput:
            printStdErr(
                "If you are encountering problems, you can reprogram anyway."
                " Would you like to do this?"
                "\nType yes to reprogram or just press enter to keep your current firmware: "
            )
            choice = raw_input()
            if not any(choice == x for x in ["yes", "Yes", "YES", "yes", "y", "Y"]):
                return 0
        else:
            printStdErr("No update needed. Exiting.")
            exit(0)

    if hwVersion is not None and userInput:
        printStdErr("Would you like me to try to restore you settings after programming? [Y/n]: ")
        choice = raw_input()
        if not any(choice == x for x in ["", "yes", "Yes", "YES", "yes", "y", "Y"]):
            restoreSettings = False
        printStdErr("Would you like me to try to restore your configured devices after programming? [Y/n]: ")
        choice = raw_input()
        if not any(choice == x for x in ["", "yes", "Yes", "YES", "yes", "y", "Y"]):
            restoreDevices = False

    printStdErr("Downloading firmware...")
    localFileName = None
    system1 = None
    system2 = None

    if family == "Arduino":
        localFileName = releases.getBin(tag, [board, shield, ".hex"])
    elif family == "Spark" or family == "Particle":
        localFileName = releases.getBin(tag, [board, "brewpi", ".bin"])
    else:
        printStdErr("Error: Device family {0} not recognized".format(family))
        return -1

    if board == "photon":
        if hwVersion:
            oldVersion = hwVersion.version.vstring
        else:
            oldVersion = "0.0.0"
        latestSystemTag = releases.getLatestTagForSystem(prerelease=beta, since=oldVersion)
        if latestSystemTag is not None:
            printStdErr("Updated system firmware for the photon found in release {0}".format(latestSystemTag))
            system1 = releases.getBin(latestSystemTag, ["photon", "system-part1", ".bin"])
            system2 = releases.getBin(latestSystemTag, ["photon", "system-part2", ".bin"])
            if system1:
                printStdErr("Downloaded new system firmware to:\n")
                printStdErr("{0}\nand\n".format(system1))
                if system2:
                    printStdErr("{0}\n".format(system2))
                else:
                    printStdErr("Error: system firmware part2 not found in release")
                    return -1
        else:
            printStdErr("Photon system firmware is up to date.\n")

    if localFileName:
        printStdErr("Latest firmware downloaded to:\n" + localFileName)
    else:
        printStdErr("Downloading firmware failed")
        return -1

    printStdErr("\nUpdating firmware...\n")
    result = programmer.programController(
        config, board, localFileName, system1, system2, useDfu, {"settings": restoreSettings, "devices": restoreDevices}
    )
    util.removeDontRunFile(config["wwwPath"] + "/do_not_run_brewpi")
    return result
def updateFromGitHub(userInput = False, restoreSettings = True, restoreDevices = True):
    import BrewPiUtil as util
    from gitHubReleases import gitHubReleases
    import brewpiVersion
    import programController as programmer

    configFile = util.scriptPath() + '/settings/config.cfg'
    config = util.readCfgWithDefaults(configFile)

    printStdErr("Stopping any running instances of BrewPi to check/update controller...")
    quitBrewPi(config['wwwPath'])

    hwVersion = None
    shield = None
    board = None
    boardName = None
    family = None
    ser = None

    ### Get version number
    printStdErr("\nChecking current firmware version...")
    try:
        ser = util.setupSerial(config)
        hwVersion = brewpiVersion.getVersionFromSerial(ser)
        family = hwVersion.family
        shield = hwVersion.shield
        board = hwVersion.board
        boardName = hwVersion.boardName()
    except:
        printStdErr("Unable to connect to controller, perhaps it is disconnected or otherwise unavailable.")
        return -1

    if ser:
        ser.close()  # close serial port
        ser = None

    if not hwVersion:
        printStdErr("Unable to retrieve firmware version from controller")
        printStdErr("If your controller has not been programmed with an earlier version of BrewPi,"
                    " follow these instructions:")
        printStdErr("\n If you have an Arduino:")
        printStdErr("Please go to https://github.com/BrewPi/firmware/releases to download"
                    "the firmware and upload via the BrewPi web interface")
        printStdErr("\n If you have a Spark Core:")
        printStdErr("Put it in DFU mode and run: sudo /home/brewpi/utils/flashDfu.py")
    else:
        printStdErr("Current firmware version on controller: " + hwVersion.toString())

    printStdErr("\nChecking GitHub for latest release...")
    releases = gitHubReleases("https://api.github.com/repos/BrewPi/firmware")
    latest = releases.getLatestTag()
    printStdErr("Latest version on GitHub: " + latest)
    if hwVersion.isNewer(latest):
        printStdErr("\nVersion on GitHub is newer than your current version, downloading new version...")
    else:

        printStdErr("\nYour current firmware version is up-to-date. There is no need to update.")
        if userInput:
            printStdErr("If you are encountering problems, you can reprogram anyway."
                        " Would you like to do this?"
                        "\nType yes to reprogram or just press enter to keep your current firmware: ")
            choice = raw_input()
            if not any(choice == x for x in ["yes", "Yes", "YES", "yes", "y", "Y"]):
                return 0
            printStdErr("Would you like me to try to restore you settings after programming? [Y/n]: ")
            choice = raw_input()
            if not any(choice == x for x in ["", "yes", "Yes", "YES", "yes", "y", "Y"]):
                restoreSettings = False
            printStdErr("Would you like me to try to restore your configured devices after programming? [Y/n]: ")
            choice = raw_input()
            if not any(choice == x for x in ["", "yes", "Yes", "YES", "yes", "y", "Y"]):
                restoreDevices = False
        else:
            return 0

    printStdErr("Downloading latest firmware...")
    localFileName = None
    if family == "Arduino":
        localFileName = releases.getBin(latest, [boardName, shield, ".hex"])
    elif family == "Spark":
        localFileName = releases.getBin(latest, [boardName, ".bin"])

    if localFileName:
        printStdErr("Latest firmware downloaded to " + localFileName)
    else:
        printStdErr("Downloading firmware failed")
        return -1

    result = programmer.programController(config, board, localFileName,
                                          {'settings': restoreSettings, 'devices': restoreDevices})
    util.removeDontRunFile(config['wwwPath'] + "/do_not_run_brewpi")
    return result
示例#9
0
else:
    configFile = sys.argv[1]

if not os.path.exists(configFile):
    sys.exit('ERROR: Config file "%s" was not found!' % configFile)

config = util.readCfgWithDefaults(configFile)

print "***** BrewPi Windows Test Terminal ****"
print "This simple Python script lets you send commands to the Arduino."
print "It also echoes everything the Arduino returns."
print "On known debug ID's in JSON format, it expands the messages to the full message"
print "press 's' to send a string to the Arduino, press 'q' to quit"

# open serial port
ser = util.setupSerial(config)

if not ser:
    exit(1)

while 1:
    if msvcrt.kbhit():
        received = msvcrt.getch()
        if received == 's':
            print "type the string you want to send to the Arduino: "
            userInput = raw_input()
            print "sending: " + userInput
            ser.write(userInput)
        elif received == 'q':
            ser.close()
            exit()
示例#10
0
else:
    configFile = sys.argv[1]

if not os.path.exists(configFile):
    sys.exit('ERROR: Config file "%s" was not found!' % configFile)

config = util.readCfgWithDefaults(configFile)

print "***** BrewPi Windows Test Terminal ****"
print "This simple Python script lets you send commands to the Arduino."
print "It also echoes everything the Arduino returns."
print "On known debug ID's in JSON format, it expands the messages to the full message"
print "press 's' to send a string to the Arduino, press 'q' to quit"

# open serial port
ser = util.setupSerial(config, timeOut=1)

if not ser:
    exit(1)

while 1:
    if msvcrt.kbhit():
        received = msvcrt.getch()
        if received == 's':
            print "type the string you want to send to the Arduino: "
            userInput = raw_input()
            print "sending: " + userInput
            ser.write(userInput)
        elif received == 'q':
            ser.close()
            exit()
示例#11
0
    quitBrewPi(webPath)

    ### Check arduino hex file version against current brewpi version
    print "\nChecking Arduino hex file version..."
    try:
        import BrewPiUtil as util
    except:
        print "Error reading config util path"

    configFile = scriptPath + '/settings/config.cfg'
    config = util.readCfgWithDefaults(configFile)

    ### Get version number
    try:
        import brewpiVersion
        ser, conn = util.setupSerial(config)
        hwVersion = brewpiVersion.getVersionFromSerial(ser)
        shield = hwVersion.shield
        board = hwVersion.board
        if "standard" in board:
            board = "uno"
        with open(scriptPath + '/brewpi.py', 'r') as versionFile:
            for line in versionFile:
                if 'compatibleHwVersion =' in line:
                    bpVersion = line.split("= ")[1].replace("\"", "")
                    break
        if hwVersion is None:
            print "Unable to retrieve version number from Arduino, skipping"
        else:
            print "Current Arduino version number: "+hwVersion.toString()
            print "Arduino version number compatible with script:  "+bpVersion
示例#12
0
def updateFromGitHub(userInput,
                     beta,
                     useDfu,
                     restoreSettings=True,
                     restoreDevices=True):
    import BrewPiUtil as util
    from gitHubReleases import gitHubReleases
    import brewpiVersion
    import programController as programmer

    configFile = util.scriptPath() + '/settings/config.cfg'
    config = util.readCfgWithDefaults(configFile)

    printStdErr(
        "Stopping any running instances of BrewPi to check/update controller..."
    )
    quitBrewPi(config['wwwPath'])

    hwVersion = None
    shield = None
    board = None
    family = None
    ser = None

    ### Get version number
    printStdErr("\nChecking current firmware version...")
    try:
        ser = util.setupSerial(config)
        hwVersion = brewpiVersion.getVersionFromSerial(ser)
        family = hwVersion.family
        shield = hwVersion.shield
        board = hwVersion.board

        printStdErr("Found " + hwVersion.toExtendedString() + \
               " on port " + ser.name + "\n")
    except:
        if hwVersion is None:
            printStdErr(
                "Unable to receive version from controller.\n"
                "Is your controller unresponsive and do you wish to try restoring your firmware? [y/N]: "
            )
            choice = raw_input()
            if not any(choice == x
                       for x in ["yes", "Yes", "YES", "yes", "y", "Y"]):
                printStdErr(
                    "Please make sure your controller is connected properly and try again."
                )
                return 0
            port, name = autoSerial.detect_port()
            if not port:
                printStdErr(
                    "Could not find compatible device in available serial ports."
                )
                return 0
            if "Particle" in name:
                family = "Particle"
                if "Photon" in name:
                    board = 'photon'
                elif "Core" in name:
                    board = 'core'
            elif "Arduino" in name:
                family = "Arduino"
                if "Leonardo" in name:
                    board = 'leonardo'
                elif "Uno" in name:
                    board = 'uno'

            if board is None:
                printStdErr(
                    "Unable to connect to controller, perhaps it is disconnected or otherwise unavailable."
                )
                return -1
            else:
                printStdErr("Will try to restore the firmware on your %s" %
                            name)
                if family == "Arduino":
                    printStdErr(
                        "Assuming a Rev C shield. If this is not the case, please program your Arduino manually"
                    )
                    shield = 'RevC'
                else:
                    printStdErr(
                        "Please put your controller in DFU mode now by holding the setup button during reset, until the LED blinks yellow."
                    )
                    printStdErr("Press Enter when ready.")
                    choice = raw_input()
                    useDfu = True  # use dfu mode when board is not responding to serial

    if ser:
        ser.close()  # close serial port
        ser = None

    if hwVersion:
        printStdErr("Current firmware version on controller: " +
                    hwVersion.toString())
    else:
        restoreDevices = False
        restoreSettings = False

    printStdErr("\nChecking GitHub for available release...")
    releases = gitHubReleases("https://api.github.com/repos/BrewPi/firmware")

    availableTags = releases.getTags(beta)
    stableTags = releases.getTags(False)
    compatibleTags = []
    for tag in availableTags:
        url = None
        if family == "Arduino":
            url = releases.getBinUrl(tag, [board, shield, ".hex"])
        elif family == "Spark" or family == "Particle":
            url = releases.getBinUrl(tag, [board, 'brewpi', '.bin'])
        if url is not None:
            compatibleTags.append(tag)

    if len(compatibleTags) == 0:
        printStdErr("No compatible releases found for %s %s" % (family, board))
        return -1

    # default tag is latest stable tag, or latest unstable tag if no stable tag is found
    default_choice = next(
        (i for i, t in enumerate(compatibleTags) if t in stableTags),
        compatibleTags[0])
    tag = compatibleTags[default_choice]

    if userInput:
        print("\nAvailable releases:\n")
        for i, menu_tag in enumerate(compatibleTags):
            print("[%d] %s" % (i, menu_tag))
        print("[" + str(len(compatibleTags)) + "] Cancel firmware update")
        num_choices = len(compatibleTags)
        while 1:
            try:
                choice = raw_input(
                    "Enter the number [0-%d] of the version you want to program [default = %d (%s)]: "
                    % (num_choices, default_choice, tag))
                if choice == "":
                    break
                else:
                    selection = int(choice)
            except ValueError:
                print("Use the number! [0-%d]" % num_choices)
                continue
            if selection == num_choices:
                return False  # choice = skip updating
            try:
                tag = compatibleTags[selection]
            except IndexError:
                print("Not a valid choice. Try again")
                continue
            break
    else:
        printStdErr("Latest version on GitHub: " + tag)

    if hwVersion is not None and not hwVersion.isNewer(tag):
        if hwVersion.isEqual(tag):
            printStdErr("You are already running version %s." % tag)
        else:
            printStdErr("Your current version is newer than %s." % tag)

        if userInput:
            printStdErr(
                "If you are encountering problems, you can reprogram anyway."
                " Would you like to do this?"
                "\nType yes to reprogram or just press enter to keep your current firmware: "
            )
            choice = raw_input()
            if not any(choice == x
                       for x in ["yes", "Yes", "YES", "yes", "y", "Y"]):
                return 0
        else:
            printStdErr("No update needed. Exiting.")
            exit(0)

    if hwVersion is not None and userInput:
        printStdErr(
            "Would you like me to try to restore you settings after programming? [Y/n]: "
        )
        choice = raw_input()
        if not any(choice == x
                   for x in ["", "yes", "Yes", "YES", "yes", "y", "Y"]):
            restoreSettings = False
        printStdErr(
            "Would you like me to try to restore your configured devices after programming? [Y/n]: "
        )
        choice = raw_input()
        if not any(choice == x
                   for x in ["", "yes", "Yes", "YES", "yes", "y", "Y"]):
            restoreDevices = False

    printStdErr("Downloading firmware...")
    localFileName = None
    system1 = None
    system2 = None

    if family == "Arduino":
        localFileName = releases.getBin(tag, [board, shield, ".hex"])
    elif family == "Spark" or family == "Particle":
        localFileName = releases.getBin(tag, [board, 'brewpi', '.bin'])
    else:
        printStdErr("Error: Device family {0} not recognized".format(family))
        return -1

    if board == "photon":
        if hwVersion:
            oldVersion = hwVersion.version.vstring
        else:
            oldVersion = "0.0.0"
        latestSystemTag = releases.getLatestTagForSystem(prerelease=beta,
                                                         since=oldVersion)
        if latestSystemTag is not None:
            printStdErr(
                "Updated system firmware for the photon found in release {0}".
                format(latestSystemTag))
            system1 = releases.getBin(latestSystemTag,
                                      ['photon', 'system-part1', '.bin'])
            system2 = releases.getBin(latestSystemTag,
                                      ['photon', 'system-part2', '.bin'])
            if system1:
                printStdErr("Downloaded new system firmware to:\n")
                printStdErr("{0}\nand\n".format(system1))
                if system2:
                    printStdErr("{0}\n".format(system2))
                else:
                    printStdErr(
                        "Error: system firmware part2 not found in release")
                    return -1
        else:
            printStdErr("Photon system firmware is up to date.\n")

    if localFileName:
        printStdErr("Latest firmware downloaded to:\n" + localFileName)
    else:
        printStdErr("Downloading firmware failed")
        return -1

    printStdErr("\nUpdating firmware...\n")
    result = programmer.programController(config, board, localFileName,
                                          system1, system2, useDfu, {
                                              'settings': restoreSettings,
                                              'devices': restoreDevices
                                          })
    util.removeDontRunFile(config['wwwPath'] + "/do_not_run_brewpi")
    return result
示例#13
0
    print "\nChecking Arduino hex file version..."
    try:
        import BrewPiUtil as util
    except:
        print "Error reading config util path"

    configFile = scriptPath + '/settings/config.cfg'
    config = util.readCfgWithDefaults(configFile)

    hwVersion = None
    shield = None
    board = None
    ### Get version number
    try:
        import brewpiVersion
        ser, conn = util.setupSerial(config)
        hwVersion = brewpiVersion.getVersionFromSerial(ser)
        shield = hwVersion.shield
        board = hwVersion.board
        if "standard" in board:
            board = "uno"
        with open(scriptPath + '/brewpi.py', 'r') as versionFile:
            for line in versionFile:
                if 'compatibleHwVersion =' in line:
                    bpVersion = line.split("= ")[1].replace("\"", "")
                    break
        if hwVersion is None:
            print "Unable to retrieve version number from Arduino, skipping"
        else:
            print "Current Arduino version number: " + hwVersion.toString()
            print "Arduino version number compatible with script:  " + bpVersion
示例#14
0
def updateFromGitHub(userInput=False,
                     restoreSettings=True,
                     restoreDevices=True):
    import BrewPiUtil as util
    from gitHubReleases import gitHubReleases
    import brewpiVersion
    import programController as programmer

    configFile = util.scriptPath() + '/settings/config.cfg'
    config = util.readCfgWithDefaults(configFile)

    printStdErr(
        "Stopping any running instances of BrewPi to check/update controller..."
    )
    quitBrewPi(config['wwwPath'])

    hwVersion = None
    shield = None
    board = None
    boardName = None
    family = None
    ser = None

    ### Get version number
    printStdErr("\nChecking current firmware version...")
    try:
        ser = util.setupSerial(config)
        hwVersion = brewpiVersion.getVersionFromSerial(ser)
        family = hwVersion.family
        shield = hwVersion.shield
        board = hwVersion.board
        boardName = hwVersion.boardName()

        printStdErr("Found " + hwVersion.toExtendedString() + \
               " on port " + ser.name + "\n")
    except:
        printStdErr(
            "Unable to connect to controller, perhaps it is disconnected or otherwise unavailable."
        )
        return -1

    if ser:
        ser.close()  # close serial port
        ser = None

    if not hwVersion:
        printStdErr("Unable to retrieve firmware version from controller")
        printStdErr(
            "If your controller has not been programmed with an earlier version of BrewPi,"
            " follow these instructions:")
        printStdErr("\n If you have an Arduino:")
        printStdErr(
            "Please go to https://github.com/BrewPi/firmware/releases to download"
            "the firmware and upload via the BrewPi web interface")
        printStdErr("\n If you have a Spark Core:")
        printStdErr(
            "Put it in DFU mode and run: sudo /home/brewpi/utils/flashDfu.py")
    else:
        printStdErr("Current firmware version on controller: " +
                    hwVersion.toString())

    printStdErr("\nChecking GitHub for latest release...")
    releases = gitHubReleases("https://api.github.com/repos/BrewPi/firmware")
    tag = releases.getLatestTag()
    printStdErr("Latest version on GitHub: " + tag)

    if hwVersion.isNewer(tag):
        printStdErr(
            "\nVersion on GitHub is newer than your current version, downloading new version..."
        )
    else:
        printStdErr(
            "\nYour current firmware version is up-to-date. There is no need to update."
        )
        if userInput:
            printStdErr(
                "If you are encountering problems, you can reprogram anyway."
                " Would you like to do this?"
                "\nType yes to reprogram or just press enter to keep your current firmware: "
            )
            choice = raw_input()
            if not any(choice == x
                       for x in ["yes", "Yes", "YES", "yes", "y", "Y"]):
                return 0
            printStdErr(
                "Would you like me to try to restore you settings after programming? [Y/n]: "
            )
            choice = raw_input()
            if not any(choice == x
                       for x in ["", "yes", "Yes", "YES", "yes", "y", "Y"]):
                restoreSettings = False
            printStdErr(
                "Would you like me to try to restore your configured devices after programming? [Y/n]: "
            )
            choice = raw_input()
            if not any(choice == x
                       for x in ["", "yes", "Yes", "YES", "yes", "y", "Y"]):
                restoreDevices = False
        else:
            return 0

    printStdErr("Downloading latest firmware...")
    localFileName = None
    system1 = None
    system2 = None

    if family == "Arduino":
        localFileName = releases.getBin(tag, [boardName, shield, ".hex"])
    elif family == "Spark" or family == "Particle":
        localFileName = releases.getBin(tag, [boardName, 'brewpi', '.bin'])
    else:
        printStdErr("Error: Device family {0} not recognized".format(family))
        return -1

    if boardName == "Photon":
        latestSystemTag = releases.getLatestTagForSystem()
        if hwVersion.isNewer(latestSystemTag):
            printStdErr(
                "Updated system firmware for the photon found in release {0}".
                format(latestSystemTag))
            system1 = releases.getBin(latestSystemTag,
                                      ['photon', 'system-part1', '.bin'])
            system2 = releases.getBin(latestSystemTag,
                                      ['photon', 'system-part2', '.bin'])
            if system1:
                printStdErr("Downloaded new system firmware to:\n")
                printStdErr("{0} and\n".format(system1))
                if not system2:
                    printStdErr("{0}\n".format(system2))
                    printStdErr(
                        "Error: system firmware part2 not found in release")
                    return -1

    if localFileName:
        printStdErr("Latest firmware downloaded to " + localFileName)
    else:
        printStdErr("Downloading firmware failed")
        return -1

    printStdErr("\nUpdating firmware over Serial...\n")
    result = programmer.programController(config, board, localFileName,
                                          system1, system2, {
                                              'settings': restoreSettings,
                                              'devices': restoreDevices
                                          })
    util.removeDontRunFile(config['wwwPath'] + "/do_not_run_brewpi")
    return result