2

只是为了在展示代码之前提供一些我正在从事的项目的背景知识。我目前正在开发一个 Python 脚本,该脚本将在 Raspberry Pi 上运行,以监控地下室污水泵的浮子开关。此代码将检查污水泵是否不符合以下两个标准:

  1. 如果开关打开超过三分钟
  2. 如果开关在三分钟内开关超过 10 次

我还没有完成其余的代码,但这是我所拥有的:

import time

import RPi.GPIO as GPIO
GPIO.setmode(GPIO.BCM)
GPIO.setup(17, GPIO.IN)
floatSwitch = GPIO.input(17)

import smtplib

running = True
log = open("sumpPumpLog.txt", "r+")
startTime = time.time()


def elapsedTime():
    """This function checks how much time
    has elapsed since the timer has started"""
    endtime = time.time()
    elapsed = endtime - starttime
    return elapsed


def sendEmail(*msg):
    """This function sends an email to selected recipients with a custom
    message as well as the log file attached."""
    #enter the code that sends an email to the family with the log attached

    fromaddr = 'from@email.com'
    toaddrs = [to@email.com']
    msg = """Please see the Pi and the data log file for more details."""

    # Credentials (if needed)
    username = 'my_username'
    password = 'my_password'

    msg.attached()

    # The actual mail send
    server = smtplib.SMTP('smtp.gmail.com:587')
    server.starttls()
    server.login(username, password)
    server.sendmail(fromaddr, toaddrs, msg)
    server.quit()


if running is True:
    if floatSwitch is True:
        #Write the time and what happened to the file
        log.write(str(time.time() + "Float switch turned on")
        #Wait until switch is turned off

        while floatSwitch is True:
            startTime = time.time()
            if floatSwitch is False:
                log.write(str(now) + "Float switch turned off")
                break
        #if elapsedTime > 3 min (in the form of 180 seconds)
        elif elapsedTime() > 180:
            log.write(str(now) + "Sump Pump has been deemed broaken")
            sendEmail("The sump pump is now broken.")

else:
    log.write(str(time.time() + "The sctipt has stopped.")
    sendEmail("The script has been stopped.")

我的问题是在第 52 行,当它说

while floatSwitch is True:

代码中有一个错误,它所说的只是“无效的语法”。我对 Python 很陌生,这是我第一个真正使用它的项目。我不熟悉很多语法,所以这可能是一个非常基本的错误。任何人都可以帮我修复此语句的语法,以便我可以让我的代码正常工作。我知道在没有其余代码的情况下还有许多其他错误,但我计划在找到这些错误时解决它们。我四处搜寻,但找不到另一个这样的例子。非常感谢任何和所有帮助!

4

2 回答 2

5

实际上,您的问题在于while 循环上方的行。您缺少括号:

log.write(str(time.time() + "Float switch turned on"))
                                               here--^

另外,只是对未来的提示,而不是这样做:

while floatSwitch is True:

这样做更干净:

while floatSwitch:
于 2013-09-29T19:30:43.680 回答
2

您的前一行有一个不平衡的括号:

log.write(str(time.time() + "Float switch turned on"))  # Last parenthesis is missing

而且在sendEmail()方法中,您缺少开场白:

toaddrs = [to@email.com']  # Opening quote missing
于 2013-09-29T19:30:16.530 回答