def takePicture(source): try: f = open("/home/pi/ProjectCuracao/main/state/exposure.txt", "r") tempString = f.read() f.close() lowername = tempString except IOError as e: lowername = "auto" exposuremode = lowername # take picture print "taking picture" cameracommand = "raspistill -o /home/pi/RasPiConnectServer/static/picameraraw.jpg -rot 180 -t 750 -ex " + exposuremode print cameracommand output = subprocess.check_output(cameracommand, shell=True, stderr=subprocess.STDOUT) output = subprocess.check_output( "convert '/home/pi/RasPiConnectServer/static/picameraraw.jpg' -pointsize 72 -fill white -gravity SouthWest -annotate +50+100 'ProjectCuracao %[exif:DateTimeOriginal]' '/home/pi/RasPiConnectServer/static/picamera.jpg'", shell=True, stderr=subprocess.STDOUT) pclogging.log(pclogging.INFO, __name__, source) print "finished taking picture" return
def initialPowerState(): # Air Quality Sensor Off myPowerSaveAirQuality.setPowerSave(False) config.AirQuality_Power = False pclogging.log(pclogging.INFO, __name__, "Power: AirQuality Turned: %s" % "OFF") # LoRa Reciever On myPowerSaveLoRa.setPowerSave(True) config.LORA_Power = True pclogging.log(pclogging.INFO, __name__, "Power: LoRa Turned: %s" % "ON") # OLED Display On myPowerSaveOLED.setPowerSave(True) config.OLED_Power = True pclogging.log(pclogging.INFO, __name__, "Power: OLED Turned: %s" % "ON") # Fan Off myPowerDriveFan.setPowerDrive(1, False) config.Fan_Drive_Power = False pclogging.log(pclogging.INFO, __name__, "Power: Fan Turned: %s" % "OFF") # turn on USBPowerControl Controlling WiFi Dongle GPIO.output(USBPowerControl_Enable, True) GPIO.output(USBPowerControl_Control, True) config.WiFi_Power = True pclogging.log(pclogging.INFO, __name__, "Power: WiFi Turned: %s" % "ON") print "Initial Power State Set"
def getTime(source, delay): print("getTime source:%s" % source) time.sleep(delay) # blink GPIO LED when it's run GPIO.setmode(GPIO.BOARD) GPIO.setup(22, GPIO.OUT) GPIO.output(22, False) time.sleep(0.5) GPIO.output(22, True) time.sleep(0.5) # setup serial port to Arduino # interrupt Arduino to start listening GPIO.setmode(GPIO.BOARD) GPIO.setup(7, GPIO.OUT, pull_up_down=GPIO.PUD_DOWN) GPIO.output(7, False) GPIO.output(7, True) GPIO.output(7, False) # Send the GD (Get Data) Command ser = serial.Serial('/dev/ttyAMA0', 9600, timeout=1) #ser.open() time.sleep(7.0) # send the first "are you there? command - RD - return from Arduino OK" response = util.sendCommandAndRecieve(ser, "RD") print("response=", response); if (response == "OK\n"): print "Good RD Response" else: print "bad response from RD" pclogging.log(pclogging.ERROR, __name__, "RD failed from Pi to BatteryWatchDog") ser.close() return # Read the value response = util.sendCommandAndRecieve(ser, "RT") print("response=", response); datecommand = "date -s '" + response + "'" print datecommand output = subprocess.check_output (datecommand,shell=True, stderr=subprocess.STDOUT ) # say goodby response = util.sendCommandAndRecieve(ser, "GB") print("response=", response); pclogging.log(pclogging.INFO, __name__, "RT - Time Set on Pi to Arduino Time ") ser.close()
def RFIDDetect(source, delay, queue): time.sleep(delay) # setup serial port to ID-3LA print("RFID Thread Starting") ser = serial.Serial('/dev/ttyUSB0', 9600, timeout=1) while True: response = RFIDrecieveLine(ser) if (len(response) != 16): t =0 #print("No response=", response) else: print("Found RFID Card. response=", response) pclogging.log(pclogging.INFO, __name__, "RFID Card Detected:%s" % response) queue.put(True) return True
def WLAN_check(): ''' This function checks if the WLAN is still up by pinging the router. If there is no return, we'll reset the WLAN connection. If the resetting of the WLAN does not work, we need to reset the Pi. source http://www.raspberrypi.org/forums/viewtopic.php?t=54001&p=413095 ''' global WLAN_check_flg ping_ret = subprocess.call(['ping -c 2 -w 1 -q 192.168.1.1 |grep "1 received" > /dev/null 2> /dev/null'], shell=True) if ping_ret: # we lost the WLAN connection. # did we try a recovery already? if (WLAN_check_flg>2): # we have a serious problem and need to reboot the Pi to recover the WLAN connection print "logger WLAN Down, Pi cannot forcing a reboot" pclogging.log(pclogging.ERROR, __name__, "WLAN Down, Pi is forcing a reboot") WLAN_check_flg = 0 # rebootPi("WLAN Down") #subprocess.call(['sudo shutdown -r now'], shell=True) else: # try to recover the connection by resetting the LAN #subprocess.call(['logger "WLAN is down, Pi is resetting WLAN connection"'], shell=True) print "WLAN Down, Pi is trying resetting WLAN connection" pclogging.log(pclogging.WARNING, __name__, "WLAN Down, Pi is resetting WLAN connection" ) WLAN_check_flg = WLAN_check_flg + 1 # try to recover subprocess.call(['sudo /sbin/ifdown wlan0 && sleep 10 && sudo /sbin/ifup --force wlan0'], shell=True) else: WLAN_check_flg = 0 print "WLAN is OK"
def shutdownPi(why): """Shutdown Pi.""" pclogging.log(pclogging.INFO, __name__, "Pi Shutting Down: %s" % why) sendemail.sendEmail("test", "WeatherPi Shutting down:" + why, "The WeatherPi Raspberry Pi shutting down.", conf.notifyAddress, conf.fromAddress, "") sys.stdout.flush() time.sleep(10.0) os.system("sudo shutdown -h now")
def takePicture(source): try: f = open("/home/pi/ProjectCuracao/main/state/exposure.txt", "r") tempString = f.read() f.close() lowername = tempString except IOError as e: lowername = "auto" exposuremode = lowername # take picture print "taking picture" cameracommand = "raspistill -o /home/pi/RasPiConnectServer/static/picameraraw.jpg -rot 180 -t 750 -ex " + exposuremode print cameracommand output = subprocess.check_output (cameracommand,shell=True, stderr=subprocess.STDOUT ) output = subprocess.check_output("convert '/home/pi/RasPiConnectServer/static/picameraraw.jpg' -pointsize 72 -fill white -gravity SouthWest -annotate +50+100 'ProjectCuracao %[exif:DateTimeOriginal]' '/home/pi/RasPiConnectServer/static/picamera.jpg'", shell=True, stderr=subprocess.STDOUT) pclogging.log(pclogging.INFO, __name__, source ) print "finished taking picture" return
def WLAN_check(): ''' This function checks if the WLAN is still up by pinging the router. If there is no return, we'll reset the WLAN connection. If the resetting of the WLAN does not work, we need to reset the Pi. source http://www.raspberrypi.org/forums/viewtopic.php?t=54001&p=413095 ''' global WLAN_check_flg ping_ret = subprocess.call(['ping -c 2 -w 1 -q 192.168.100.1 |grep "1 received" > /dev/null 2> /dev/null'], shell=True) if ping_ret: # we lost the WLAN connection. # did we try a recovery already? if (WLAN_check_flg>2): # we have a serious problem and need to reboot the Pi to recover the WLAN connection print "logger WLAN Down, Pi is forcing a reboot" pclogging.log(pclogging.ERROR, __name__, "WLAN Down, Pi is forcing a reboot") WLAN_check_flg = 0 rebootPi("WLAN Down") #subprocess.call(['sudo shutdown -r now'], shell=True) else: # try to recover the connection by resetting the LAN #subprocess.call(['logger "WLAN is down, Pi is resetting WLAN connection"'], shell=True) print "WLAN Down, Pi is trying resetting WLAN connection" pclogging.log(pclogging.WARNING, __name__, "WLAN Down, Pi is resetting WLAN connection" ) WLAN_check_flg = WLAN_check_flg + 1 # try to recover subprocess.call(['sudo /sbin/ifdown wlan0 && sleep 10 && sudo /sbin/ifup --force wlan0'], shell=True) else: WLAN_check_flg = 0 print "WLAN is OK"
def shutdownPi(why): pclogging.log(pclogging.INFO, __name__, "Pi Shutting Down: %s" % why) sendemail.sendEmail("test", "WeatherPi Shutting down:"+ why, "The WeatherPi Raspberry Pi shutting down.", conf.notifyAddress, conf.fromAddress, ""); sys.stdout.flush() time.sleep(10.0) os.system("sudo shutdown -h now")
def setWiFiOn(reason): # turn on USBPowerControl Controlling WiFi Dongle GPIO.output(USBPowerControl_Enable, True) GPIO.output(USBPowerControl_Control, True) config.WiFi_Power = True pclogging.log(pclogging.INFO, __name__, "Power: %s WiFi Turned: %s" % (reason, "ON"))
def readTime(source, delay): print("readTime source:%s" % source) time.sleep(delay) # blink GPIO LED when it's run GPIO.setmode(GPIO.BOARD) GPIO.setup(22, GPIO.OUT) GPIO.output(22, False) time.sleep(0.5) GPIO.output(22, True) time.sleep(0.5) # setup serial port to Arduino # interrupt Arduino to start listening GPIO.setmode(GPIO.BOARD) GPIO.setup(7, GPIO.OUT, pull_up_down=GPIO.PUD_DOWN) GPIO.output(7, False) GPIO.output(7, True) GPIO.output(7, False) # Send the GD (Get Data) Command ser = serial.Serial('/dev/ttyAMA0', 9600, timeout=1) #ser.open() time.sleep(3.0) # send the first "are you there? command - RD - return from Arduino OK" response = util.sendCommandAndRecieve(ser, "RD") print("response=", response) if (response == "OK\n"): print "Good RD Response" else: print "bad response from RD" pclogging.log(pclogging.ERROR, __name__, "RD failed from Pi to BatteryWatchDog") ser.close() return # Read the value response = util.sendCommandAndRecieve(ser, "RT") print("Arduino readtime response=", response) myTime = response # say goodby response = util.sendCommandAndRecieve(ser, "GB") print("response=", response) pclogging.log(pclogging.INFO, __name__, "RT - Arduino Time Read " + myTime) ser.close()
def initUltrasonic(): # get range finder working try: lastrange = rr.get_range_inch() print ("initUltrasonic rangeinch=%f" % rr.get_range_inch()) except ValueError: print ("ultrasonic reading error") pclogging.log(pclogging.INFO, __name__, "Ultrasonic Initialized") return True
def resetWXLink(): print "reset the LoRa reciever" # LoRa Reciever Off myPowerSaveLoRa.setPowerSave(False) config.LORA_Power = False pclogging.log(pclogging.INFO, __name__, "Power: LoRa Turned: %s" % "OFF") time.sleep(5.0) myPowerSaveLoRa.setPowerSave(True) config.LORA_Power = True pclogging.log(pclogging.INFO, __name__, "Power: LoRa Turned: %s" % "ON")
def WLAN_check(): ''' This function checks if the WLAN is still up by pinging the router. If there is no return, we'll reset the WLAN connection. If the resetting of the WLAN does not work, we need to reset the Pi. source http://www.raspberrypi.org/forums/viewtopic.php?t=54001&p=413095 ''' global WLAN_check_flg if (config.enable_WLAN_Detection == True): ping_ret = subprocess.call([ 'ping -c 2 -w 1 -q ' + config.PingableRouterAddress + ' |grep "1 received" > /dev/null 2> /dev/null' ], shell=True) print "checking WLAN: ping_ret=%i WLAN_check_flg=%i" % ( ping_ret, WLAN_check_flg) if ping_ret: # we lost the WLAN connection. # did we try a recovery already? if (WLAN_check_flg > 2): # we have a serious problem and need to reboot the Pi to recover the WLAN connection print "logger WLAN Down, Pi is forcing a reboot" pclogging.log(pclogging.ERROR, __name__, "WLAN Down, Pi is forcing a reboot") WLAN_check_flg = 0 time.sleep(5) print "time to Reboot Pi from WLAN_check" rebootPi("WLAN Down reboot") #print "logger WLAN Down, Pi is forcing a Shutdown" #shutdownPi("WLAN Down halt") # halt pi and let the watchdog restart it #subprocess.call(['sudo shutdown -r now'], shell=True) else: # try to recover the connection by resetting the LAN #subprocess.call(['logger "WLAN is down, Pi is resetting WLAN connection"'], shell=True) print "WLAN Down, Pi is trying resetting WLAN connection" pclogging.log(pclogging.WARNING, __name__, "WLAN Down, Pi is resetting WLAN connection") WLAN_check_flg = WLAN_check_flg + 1 # try to recover subprocess.call([ 'sudo /sbin/ifdown wlan0 && sleep 10 && sudo /sbin/ifup --force wlan0' ], shell=True) else: WLAN_check_flg = 0 print "WLAN is OK" else: # enable_WLAN_Detection is off WLAN_check_flg = 0 print "WLAN Detection is OFF"
def setLoRaPower(value): if (value == True): myLoRaSaveOLED.setPowerSave(True) config.LORA_Power = True pclogging.log(pclogging.INFO, __name__, "Power: LoRa Turned: %s" % "ON") if (value == False): config.LORA_Power = False myPowerSaveLoRa.setPowerSave(False) pclogging.log(pclogging.INFO, __name__, "Power: LoRa Turned: %s" % "OFF")
def setOLEDDisplayPower(value): if (value == True): myPowerSaveOLED.setPowerSave(True) config.OLED_Power = True pclogging.log(pclogging.INFO, __name__, "Power: OLED Turned: %s" % "ON") if (value == False): config.OLED_Power = False myPowerSaveOLED.setPowerSave(False) pclogging.log(pclogging.INFO, __name__, "Power: OLED Turned: %s" % "OFF")
def checkForRFID(source, delay): time.sleep(delay) # setup serial port to ID-3LA ser = serial.Serial('/dev/ttyUSB0', 9600, timeout=1) while True: response = recieveLine(ser) if (len(response) != 16): print("No response=", response) else: print("Found RFID Card. response=", response) pclogging.log(pclogging.INFO, __name__, "Mouse Air Startup")
def sweepShutter(source, delay): print("sweepShutter source:%s" % source) GPIO.setmode(GPIO.BOARD) time.sleep(delay) # blink GPIO LED when it's run GPIO.setup(22, GPIO.OUT) GPIO.output(22, False) time.sleep(0.5) GPIO.output(22, True) time.sleep(0.5) hardwareactions.sweepshutter() time.sleep(3.0) pclogging.log(pclogging.INFO, __name__, "Sweep Shutter")
def sendWatchDogTimer(source, delay,ser): print("sendWatchDogTimer source:%s" % source) time.sleep(delay) response = util.sendCommandAndRecieve(ser, "WD") print("response=", response); if (len(response) > 0): print("WD success") # pclogging.log(pclogging.INFO, __name__, "Watchdog Timer Reset on Arduino" ) else: # system setup pclogging.log(pclogging.ERROR, __name__, "WD failed from Pi to BatteryWatchDog")
def sendWatchDogTimer(source, delay, ser): print("sendWatchDogTimer source:%s" % source) time.sleep(delay) response = util.sendCommandAndRecieve(ser, "WD") print("response=", response) if (len(response) > 0): print("WD success") # pclogging.log(pclogging.INFO, __name__, "Watchdog Timer Reset on Arduino" ) else: # system setup pclogging.log(pclogging.ERROR, __name__, "WD failed from Pi to BatteryWatchDog")
def process_as3935_interrupt(): global as3935Interrupt global as3935, as3935LastInterrupt, as3935LastDistance, as3935LastStatus as3935Interrupt = False print "processing Interrupt from as3935" # turn I2CBus 0 on #tca9545.write_control_register(TCA9545_CONFIG_BUS0) # turn I2CBus 2 on tca9545.write_control_register(TCA9545_CONFIG_BUS2) time.sleep(0.003) reason = as3935.get_interrupt() as3935LastInterrupt = reason if reason == 0x00: as3935LastStatus = "Spurious Interrupt" elif reason == 0x01: as3935LastStatus = "Noise Floor too low. Adjusting" as3935.raise_noise_floor() elif reason == 0x04: as3935LastStatus = "Disturber detected - masking" as3935.set_mask_disturber(True) elif reason == 0x08: now = datetime.now().strftime('%H:%M:%S - %Y/%m/%d') distance = as3935.get_distance() as3935LastDistance = distance as3935LastStatus = "Lightning Detected " + str( distance) + "km away. (%s)" % now pclogging.log( pclogging.INFO, __name__, "Lightning Detected " + str(distance) + "km away. (%s)" % now) sendemail.sendEmail("test", "WeatherPi Lightning Detected\n", as3935LastStatus, conf.textnotifyAddress, conf.textfromAddress, "") print "Last Interrupt = 0x%x: %s" % (as3935LastInterrupt, as3935LastStatus) tca9545.write_control_register(TCA9545_CONFIG_BUS0) time.sleep(0.003)
def processCommand(): f = open("/home/pi/WeatherPi/state/WeatherCommand.txt", "r") command = f.read() f.close() if (command == "") or (command == "DONE"): # Nothing to do return False # Check for our commands pclogging.log(pclogging.INFO, __name__, "Command %s Recieved" % command) print "Processing Command: ", command if (command == "SAMPLEWEATHER"): sampleWeather() completeCommand() writeWeatherStats() return True
def setWiFiOff(reason): f = open("/home/pi/SDL_Pi_ProjectCuracao2/WIFISHUTOFF", "r") command = f.read() f.close() command = command.replace("\n", "") print "command='%s'" % command if (command == "False"): pclogging.log(pclogging.INFO, __name__, "Power: %s WiFi !: %s DISABLED" % (reason, "OFF")) # Nothing to do return # turn off USBPowerControl Controlling WiFi Dongle GPIO.output(USBPowerControl_Enable, True) GPIO.output(USBPowerControl_Control, False) config.WiFi_Power = False pclogging.log(pclogging.INFO, __name__, "Power: %s WiFi Turned: %s" % (reason, "OFF"))
def process_as3935_interrupt(): global as3935Interrupt global as3935, as3935LastInterrupt, as3935LastDistance, as3935LastStatus as3935Interrupt = False print "processing Interrupt from as3935" # turn I2CBus 1 on tca9545.write_control_register(TCA9545_CONFIG_BUS1) time.sleep(0.020) reason = as3935.get_interrupt() as3935LastInterrupt = reason if reason == 0x00: as3935LastStatus = "Spurious Interrupt" elif reason == 0x01: as3935LastStatus = "Noise Floor too low. Adjusting" as3935.raise_noise_floor() elif reason == 0x04: as3935LastStatus = "Disturber detected - masking" as3935.set_mask_disturber(True) elif reason == 0x08: now = datetime.now().strftime('%H:%M:%S - %m/%d/%Y') distance = as3935.get_distance() as3935LastStatus = "Lightning Detected " + str( distance) + "km away. (%s)" % now tweet = "DANGER!: " + str(as3935LastStatus) twitter = Twython(config.consumer_key, config.consumer_secret, config.access_key, config.access_secret) twitter.update_status(status=tweet) print("Tweeted: {}".format(tweet)) pclogging.log( pclogging.INFO, __name__, "Lightning Detected " + str(distance) + "km away. (%s)" % now) print "Last Interrupt = 0x%x: %s" % (as3935LastInterrupt, as3935LastStatus) tca9545.write_control_register(TCA9545_CONFIG_BUS0) time.sleep(0.003)
def WLAN_check(): """Check to see if WLAN is still up by pinging router.""" global WLAN_check_flg ping_ret = subprocess.call(['ping -c 2 -w 1 -q 192.168.1.1 |grep "1 received" > /dev/null 2> /dev/null'], shell=True) if ping_ret: # we lost the WLAN connection. # did we try a recovery already? if (WLAN_check_flg > 2): # we have a serious problem and need to reboot the Pi to recover the WLAN connection print "logger WLAN Down, Pi is forcing a reboot" pclogging.log(pclogging.ERROR, __name__, "WLAN Down, Pi is forcing a reboot") WLAN_check_flg = 0 rebootPi("WLAN Down") elif (WLAN_check_flg == 1): # try to recover the connection by resetting the LAN print "WLAN Down, Pi is trying resetting WLAN connection" pclogging.log(pclogging.WARNING, __name__, "WLAN Down, Pi is resetting WLAN connection") WLAN_check_flg = WLAN_check_flg + 1 # try to recover subprocess.call(['sudo /sbin/ifdown wlan0 && sleep 10 && sudo /sbin/ifup --force wlan0'], shell=True) else: WLAN_check_flg = 0 print "WLAN is OK"
def process_as3935_interrupt(): global as3935Interrupt global as3935, as3935LastInterrupt, as3935LastDistance, as3935LastStatus as3935Interrupt = False print "processing Interrupt from as3935" # turn I2CBus 0 on #tca9545.write_control_register(TCA9545_CONFIG_BUS0) # turn I2CBus 2 on tca9545.write_control_register(TCA9545_CONFIG_BUS2) time.sleep(0.003) reason = as3935.get_interrupt() as3935LastInterrupt = reason if reason == 0x00: as3935LastStatus = "Spurious Interrupt" elif reason == 0x01: as3935LastStatus = "Noise Floor too low. Adjusting" as3935.raise_noise_floor() elif reason == 0x04: as3935LastStatus = "Disturber detected - masking" as3935.set_mask_disturber(True) elif reason == 0x08: now = datetime.now().strftime('%H:%M:%S - %Y/%m/%d') distance = as3935.get_distance() as3935LastDistance = distance as3935LastStatus = "Lightning Detected " + str(distance) + "km away. (%s)" % now pclogging.log(pclogging.INFO, __name__, "Lightning Detected " + str(distance) + "km away. (%s)" % now) sendemail.sendEmail("test", "WeatherPi Lightning Detected\n", as3935LastStatus, conf.textnotifyAddress, conf.textfromAddress, ""); print "Last Interrupt = 0x%x: %s" % (as3935LastInterrupt, as3935LastStatus) tca9545.write_control_register(TCA9545_CONFIG_BUS0) time.sleep(0.003)
def takeRaspiStill(source, pwm, pan, tilt): setTiltServo(pwm, tilt) time.sleep(1.0) setPanServo(pwm, pan) time.sleep(1.0) try: f = open("/home/pi/SDL_Pi_ProjectCuracao2/state/exposure.txt", "r") tempString = f.read() f.close() lowername = tempString except IOError as e: lowername = "auto" #lowername = "auto" #filename = "/home/pi/RasPiConnectServer/static/picameraraw.jpg" filename = "/home/pi/SDL_Pi_ProjectCuracao2/static/picameraraw.jpg" filenameout = "/home/pi/SDL_Pi_ProjectCuracao2/static/picamera.jpg" exposuremode = lowername # take picture print "taking picture" #cameracommand = "raspistill -o " + filename + " -rot 180 -t 750 -ex " + exposuremode cameracommand = "raspistill -o " + filename + " -t 750 -ex " + exposuremode print cameracommand output = subprocess.check_output (cameracommand,shell=True, stderr=subprocess.STDOUT ) output = subprocess.check_output("convert '"+ filename + "' -pointsize 72 -fill white -gravity SouthWest -annotate +50+100 'ProjectCuracao2 %[exif:DateTimeOriginal]' '" + filenameout +"'", shell=True, stderr=subprocess.STDOUT) pclogging.log(pclogging.INFO, __name__, source ) shutOffPanTilt(pwm) print "finished taking picture" return lowername
def process_as3935_interrupt(): """Process the AS3935 Interrupt to determine type.""" global as3935Interrupt global as3935, as3935LastInterrupt, as3935LastDistance, as3935LastStatus as3935Interrupt = False print "processing Interrupt from as3935" reason = as3935.get_interrupt() as3935LastInterrupt = reason if reason == 0x00: as3935LastStatus = "Spurious Interrupt" if reason == 0x01: as3935LastStatus = "Noise Floor too low. Adjusting" as3935.raise_noise_floor() if reason == 0x04: as3935LastStatus = "Disturber detected - masking" as3935.set_mask_disturber(True) if reason == 0x08: now = datetime.now().strftime('%H:%M:%S - %Y/%m/%d') distance = as3935.get_distance() as3935LastDistance = distance as3935LastStatus = "Lightning Detected " + str(distance) + "km away. (%s)" % now pclogging.log(pclogging.INFO, __name__, "Lightning Detected " + str(distance) + "km away. (%s)" % now) sendemail.sendEmail("test", "WeatherPi Lightning Detected\n", as3935LastStatus, conf.textnotifyAddress, conf.textfromAddress, "") print "Last Interrupt = 0x%x: %s" % (as3935LastInterrupt, as3935LastStatus)
print "Error %d: %s" % (e.args[0],e.args[1]) con.rollback() #sys.exit(1) finally: cur.close() con.close() del cur del con else: print "bad response from SL" # system setup pclogging.log(pclogging.ERROR, __name__, "SL failed from Pi to BatteryWatchDog") # say goodby response = util.sendCommandAndRecieve(ser, "GB") print("response=", response); ser.close() return print("ArInputCurrent =", ArInputCurrent) # say goodby response = util.sendCommandAndRecieve(ser, "GB") print("response=", response); ser.close()
def processCommand(): f = open("/home/pi/MouseAir/state/MouseCommand.txt", "r") command = f.read() f.close() if (command == "") or (command == "DONE"): # Nothing to do return False # Check for our commands pclogging.log(pclogging.INFO, __name__, "Command %s Recieved" % command) print "Processing Command: ", command if (command == "FIREMOUSE"): fireMouse() completeCommand() return True if (command == "TAKEPICTURE"): utils.threadTakePicture("Picture Taken -RasPiConnect Command") completeCommand() return True if (command == "SHOOTSOLENOID"): GPIO.output(SOLENOID_LEFT, 0) GPIO.output(SOLENOID_RIGHT, 1) time.sleep(SOLENOID_ON_TIME) GPIO.output(SOLENOID_LEFT, 0) GPIO.output(SOLENOID_RIGHT, 0) completeCommand() return True if (command == "PANTOMOUSE"): servo.setServo(pwm, servo.SERVO_TILT, 430) servo.setServo(pwm, servo.SERVO_PAN, 450) completeCommand() return True if (command == "PANTOCAT"): servo.setServo(pwm, servo.SERVO_TILT, 340) servo.setServo(pwm, servo.SERVO_PAN, 300) completeCommand() return True if (command == "PANLEFT"): servo.servoIncrement(pwm, servo.SERVO_PAN, 10) completeCommand() return True if (command == "PANRIGHT"): servo.servoIncrement(pwm, servo.SERVO_PAN, -10) completeCommand() return True if (command == "TILTUP"): servo.servoIncrement(pwm, servo.SERVO_TILT, 10) completeCommand() return True if (command == "TILTDOWN"): servo.servoIncrement(pwm, servo.SERVO_TILT, -10) completeCommand() return True if (command == "TOPSERVOOPEN"): pwm.setPWM(servo.SERVO_CHAMBER, 0, servo.servoMin) completeCommand() return True if (command == "TOPSERVOCLOSE"): pwm.setPWM(servo.SERVO_CHAMBER, 0, servo.servoMax) completeCommand() return True if (command == "BOTTOMSERVOOPEN"): pwm.setPWM(servo.SERVO_LOAD, 0, servo.servoMin) completeCommand() return True if (command == "BOTTOMSERVOCLOSE"): pwm.setPWM(servo.SERVO_LOAD, 0, servo.servoMax) completeCommand() return True if (command == "MOTORSON"): GPIO.output(RIGHT_MOTOR, RIGHT_ON) time.sleep(0.5) GPIO.output(LEFT_MOTOR, LEFT_ON) completeCommand() return True if (command == "MOTORSOFF"): GPIO.output(RIGHT_MOTOR, RIGHT_OFF) GPIO.output(LEFT_MOTOR, LEFT_OFF) completeCommand() return True if (command == "ULTRASONICON"): utils.writeState(True, ultrasonicsRange, RFIDUse, useCameraMotion, fireMouseNow) completeCommand() return True if (command == "ULTRASONICOFF"): utils.writeState(False, ultrasonicsRange, RFIDUse, useCameraMotion, fireMouseNow) completeCommand() return True if (command == "RFIDON"): utils.writeState(ultrasonicsUse, ultrasonicsRange, True, useCameraMotion, fireMouseNow) completeCommand() return True if (command == "RFIDOFF"): utils.writeState(ultrasonicsUse, ultrasonicsRange, False, useCameraMotion, fireMouseNow) completeCommand() return True if (command == "CAMERAMOTIONON"): utils.writeState(ultrasonicsUse, ultrasonicsRange, RFIDUse, True, fireMouseNow) completeCommand() return True if (command == "CAMERAMOTIONOFF"): utils.writeState(ultrasonicsUse, ultrasonicsRange, RFIDUse, False, fireMouseNow) completeCommand() return True completeCommand() return False
print "WLAN Down, Pi is trying resetting WLAN connection" pclogging.log(pclogging.WARNING, __name__, "WLAN Down, Pi is resetting WLAN connection") WLAN_check_flg = WLAN_check_flg + 1 # try to recover subprocess.call(['sudo /sbin/ifdown wlan0 && sleep 10 && sudo /sbin/ifup --force wlan0'], shell=True) else: WLAN_check_flg = 0 print "WLAN is OK" print "" print "WeatherPi Solar Powered Weather Station Version 2.0" print "Updated by Cameron Rex (camrex) - Original code by SwitchDoc Labs" print "" print "Program Started at:" + time.strftime("%Y-%m-%d %H:%M:%S") print "" pclogging.log(pclogging.INFO, __name__, "WeatherPi Startup Version 2.0") sendemail.sendEmail("test", "WeatherPi Startup \n", "The WeatherPi Raspberry Pi has rebooted.", conf.notifyAddress, conf.fromAddress, "") secondCount = 1 while True: # process Interrupts from Lightning if (as3935Interrupt is True): try: process_as3935_interrupt() except: print "exception - as3935 I2C did not work" # print every 10 seconds if ((secondCount % 10) == 0): sampleWeather() sampleSunAirPlus()
# fan is off, look at turning on # fan is not on, so let's look to see if we should turn it on # check to see if solar voltage is > 4.0 on pi if (solarvoltage > 4.0): print "solar voltage > 4.0" #if temp inside is too hot and outside is cooler, turn fan on if ((insidetemperature > conf.FAN_ON_TEMPERATURE) and (insidetemperature >= outsidetemperature)): hardwareactions.setfan(True) pclogging.log(pclogging.INFO, __name__, "fanON insidetemp> FAN_ON_TEMPERATURE and inside > outside") # send an email that the fan turned on message = "Fan turning ON: State: ot:%3.2f it:%3.2f oh:%3.2f ih:%3.2f sv:%3.2f" % (outsidetemperature, insidetemperature, outsidehumidity, insidehumidity, solarvoltage) util.sendEmail("test", message, "ProjectCuracao Fan ON(TMP)", conf.notifyAddress, conf.fromAddress, ""); print "monitorSystems Turning FAN ON" #if humidity inside is too high and outside is less, turn fan on if ((insidehumidity > conf.FAN_ON_HUMIDITY) and (insidehumidity > outsidehumidity)): hardwareactions.setfan(True) pclogging.log(pclogging.INFO, __name__, "fanON insidehumid> FAN_ON_HUMIDITY and inside > outside") message = "Fan turning ON: State: ot:%3.2f it:%3.2f oh:%3.2f ih:%3.2f sv:%3.2f" % (outsidetemperature, insidetemperature, outsidehumidity, insidehumidity, solarvoltage) util.sendEmail("test",message, "ProjectCuracao Fan ON(HUM)", conf.notifyAddress, conf.fromAddress, ""); print "monitorSystems Turning FAN ON" else:
# interrupt callback def arduino_callback(channel): global hasBWInterrupted print('Edge detected on channel %s'%channel) hasBWInterrupted = True print("hasBWSet-2=", hasBWInterrupted) if __name__ == '__main__': # system setup # log system startup pclogging.log(pclogging.INFO, __name__, "Project Curacao Startup") util.sendEmail("test", "ProjectCuracao Pi Startup", "The Raspberry Pi has rebooted.", conf.notifyAddress, conf.fromAddress, ""); GPIO.setwarnings(False) GPIO.setmode(GPIO.BOARD) GPIO.setup(7, GPIO.OUT, pull_up_down=GPIO.PUD_DOWN) # set initial hardware actions hardwareactions.setfan(False) # arudino interrupt - from battery watchdog hasBWInterrupted = False # interrupt state variable #GPIO.setup(11, GPIO.IN ) GPIO.setup(11, GPIO.IN, pull_up_down=GPIO.PUD_DOWN) #GPIO.add_event_detect(11, GPIO.RISING, callback=arduino_callback) # add rising edge detection on a channel #GPIO.add_event_detect(11, GPIO.RISING) # add rising edge detection on a channel
print "Error %d: %s" % (e.args[0], e.args[1]) con.rollback() #sys.exit(1) finally: cur.close() con.close() del cur del con else: print "bad response from SLF" # system setup pclogging.log(pclogging.ERROR, __name__, "SLF failed from Pi to BatteryWatchDog") # say goodby response = util.sendCommandAndRecieve(ser, "GB") print("response=", response) ser.close() return 0 # say goodby response = util.sendCommandAndRecieve(ser, "GB") print("response=", response) ser.close() return countEntry
def selectWind(source, delay): print("recieveInterruptFromBW source:%s" % source) time.sleep(delay) # blink GPIO LED when it's run GPIO.setmode(GPIO.BOARD) GPIO.setup(22, GPIO.OUT) GPIO.output(22, False) time.sleep(0.1) GPIO.output(22, True) time.sleep(0.1) GPIO.output(22, False) time.sleep(0.1) GPIO.output(22, True) time.sleep(0.1) GPIO.output(22, False) time.sleep(0.1) GPIO.output(22, True) # setup serial port to Arduino # interrupt Arduino to start listening GPIO.setmode(GPIO.BOARD) GPIO.setup(7, GPIO.OUT, pull_up_down=GPIO.PUD_DOWN) GPIO.output(7, False) GPIO.output(7, True) GPIO.output(7, False) # Send the WA (Get Data) Command ser = serial.Serial('/dev/ttyAMA0', 9600, timeout=1) # ser.open() time.sleep(7.0) # send the first "are you there? command - RD - return from Arduino OK" response = util.sendCommandAndRecieve(ser, "RD") print("response=", response) if (response == "OK\n"): print "Good RD Response" else: print "bad response from RD" pclogging.log(pclogging.ERROR, __name__, "RD failed from Pi to BatteryWatchDog") ser.close() return globalvars.FAILED # Read the value response = util.sendCommandAndRecieve(ser, "SW") print("response=", response) if (len(response) > 0): pclogging.log(pclogging.INFO, __name__, "sent selectWind command to Battery Watchdog ") else: # system setup pclogging.log(pclogging.ERROR, __name__, "SW failed from Pi to BatteryWatchDog") # say goodby response = util.sendCommandAndRecieve(ser, "GB") print("response=", response) ser.close() return globalvars.FAILED response = util.sendCommandAndRecieve(ser, "GB") print("response=", response) ser.close() # now we have the data, dostuff with it return True
def setThresholds(source, delay): print ("setThresholds source:%s" % source) time.sleep(delay) # blink GPIO LED when it's run GPIO.setmode(GPIO.BOARD) GPIO.setup(22, GPIO.OUT) GPIO.output(22, False) time.sleep(0.5) GPIO.output(22, True) time.sleep(0.5) # setup serial port to Arduino # interrupt Arduino to start listening GPIO.setmode(GPIO.BOARD) GPIO.setup(7, GPIO.OUT, pull_up_down=GPIO.PUD_DOWN) GPIO.output(7, False) GPIO.output(7, True) GPIO.output(7, False) # Send the STH (Set Thresholds Data) Command ser = serial.Serial("/dev/ttyAMA0", 9600, timeout=1) ser.open() time.sleep(7.0) # send the first "are you there? command - RD - return from Arduino OK" response = util.sendCommandAndRecieve(ser, "RD") print ("response=", response) if response == "OK\n": print "Good RD Response" else: print "bad response from RD" pclogging.log(pclogging.ERROR, __name__, "RD failed from Pi to BatteryWatchDog") ser.close() return # Read the value response = util.sendCommandAndRecieve(ser, "STH") print ("response=", response) if response == "OK\n": print "Good STH Response" # set up our time string # Dec 26 2009", time = "12:34:56 # myDateString = time.strftime("%b %d %Y", time.gmtime()) # myTimeString = time.strftime("%H:%M:%S", time.gmtime()) PI_BATTERY_SHUTDOWN_THRESHOLD = 3.706 # 20% PI_BATTERY_STARTUP_THRESHOLD = 3.839 # 30% INSIDE_TEMPERATURE_PI_SHUTDOWN_THRESHOLD = 49.33 # 110 INSIDE_TEMPERATURE_PI_STARTUP_THRESHOLD = 37.78 # 100 INSIDE_HUMIDITY_PI_SHUTDOWN_THRESHOLD = 98.0 INSIDE_HUMIDITY_PI_STARTUP_THRESHOLD = 93.0 PI_START_TIME = "10:00:00" # UTC PI_SHUTDOWN_TIME = "22:30:00" # UTC PI_MIDNIGHT_WAKEUP_SECONDS_LENGTH = 3600.0 # one hour PI_MIDNIGHT_WAKEUP_THRESHOLD = 3.971 # 60% mySendString = "%4.3f, %4.3f, %4.3f, %4.3f, %4.3f, %4.3f,%s,%s, %4.3f, %4.3f, %i\n" % ( conf.PI_BATTERY_SHUTDOWN_THRESHOLD, conf.PI_BATTERY_STARTUP_THRESHOLD, conf.INSIDE_TEMPERATURE_PI_SHUTDOWN_THRESHOLD, conf.INSIDE_TEMPERATURE_PI_STARTUP_THRESHOLD, conf.INSIDE_HUMIDITY_PI_SHUTDOWN_THRESHOLD, conf.INSIDE_HUMIDITY_PI_STARTUP_THRESHOLD, conf.PI_START_TIME, conf.PI_SHUTDOWN_TIME, conf.PI_MIDNIGHT_WAKEUP_SECONDS_LENGTH, conf.PI_MIDNIGHT_WAKEUP_THRESHOLD, conf.enableShutdowns, ) response = util.sendCommandAndRecieve(ser, mySendString) if response == "OK\n": print "Good STH Response" else: print "bad response from STH second line" pclogging.log(pclogging.ERROR, __name__, "STH second line failed from Pi to BatteryWatchDog") ser.close() return else: print "bad response from STH" pclogging.log(pclogging.ERROR, __name__, "STH failed from Pi to BatteryWatchDog") ser.close() return # say goodbye response = util.sendCommandAndRecieve(ser, "GB") print ("response=", response) pclogging.log(pclogging.INFO, __name__, "STH - Thresholds set on Arduino") ser.close()
def getFramArduinoLog(source, delay): print("Fram Log datacollect source:%s" % source) time.sleep(delay) # blink GPIO LED when it's run GPIO.setmode(GPIO.BOARD) GPIO.setup(22, GPIO.OUT) GPIO.output(22, False) time.sleep(0.5) GPIO.output(22, True) time.sleep(0.5) GPIO.output(22, False) time.sleep(0.5) GPIO.output(22, True) time.sleep(0.5) GPIO.output(22, False) time.sleep(0.5) GPIO.output(22, True) # setup serial port to Arduino # interrupt Arduino to start listening GPIO.setmode(GPIO.BOARD) GPIO.setup(7, GPIO.OUT, pull_up_down=GPIO.PUD_DOWN) GPIO.output(7, False) GPIO.output(7, True) GPIO.output(7, False) ser = serial.Serial('/dev/ttyAMA0', 9600, timeout=1) #ser.open() ser.flushInput() ser.flushOutput() time.sleep(7.0) # send the first "are you there? command - RD - return from Arduino OK" response = util.sendCommandAndRecieve(ser, "RD") print("response=", response); if (response == "OK\n"): print "Good RD Response" else: print "bad response from RD" pclogging.log(pclogging.ERROR, __name__, "RD failed from Pi to BatteryWatchDog") ser.close() return 0 # Read the value # get the unread log from the Arduino response = util.sendCommandAndRecieve(ser, "SLF") print("response=", response) try: countEntry = int(response) except ValueError: countEntry = 0 print("countEntry=", countEntry) pclogging.log(pclogging.INFO, __name__, "FRAM records read: %i " % countEntry) if (countEntry > 0): # read all unread entries for i in range(countEntry): logEntry = util.recieveLine(ser) print("recievedLogEntry =", logEntry) # parse and then stuff in log database # stuff the values into variables splitList = logEntry.split(',') print(splitList) if (len(splitList) == 11): WeatherLogTime = splitList[0] WeatherLogCWS = float(splitList[1]) WeatherLogCWG = float(splitList[2]) WeatherLogCWD = float(splitList[3]) WeatherLogCWDV = float(splitList[4]) WeatherLogCR = float(splitList[5]) WeatherLogURWV = float(splitList[6]) WeatherLogRWV = float(splitList[7]) WeatherLogPIS = float(splitList[8]) WeatherLogWSCUR = float(splitList[9]) WeatherLogSolarOrWind = int(splitList[10]) # now we have the data, stuff it in the database try: print("trying database") con = mdb.connect('localhost', 'root', conf.databasePassword, 'ProjectCuracao'); cur = con.cursor() print "before query" query = "INSERT INTO weatherdata(TimeStamp, CWS, CWG, CWD, CWDV, CR, URWV, RWV, PIS,WSCUR, SolarOrWind) VALUES('%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', %i)" % (WeatherLogTime, WeatherLogCWS, WeatherLogCWG, WeatherLogCWD, WeatherLogCWDV, WeatherLogCR,WeatherLogURWV, WeatherLogRWV, WeatherLogPIS, WeatherLogWSCUR, WeatherLogSolarOrWind) print("query=%s" % query) cur.execute(query) con.commit() except mdb.Error, e: print "Error %d: %s" % (e.args[0],e.args[1]) con.rollback() #sys.exit(1) finally: cur.close() con.close() del cur del con
def setTime(source, delay): print("setTime source:%s" % source) time.sleep(delay) # blink GPIO LED when it's run GPIO.setmode(GPIO.BOARD) GPIO.setup(22, GPIO.OUT) GPIO.output(22, False) time.sleep(0.5) GPIO.output(22, True) time.sleep(0.5) # setup serial port to Arduino # interrupt Arduino to start listening GPIO.setmode(GPIO.BOARD) GPIO.setup(7, GPIO.OUT, pull_up_down=GPIO.PUD_DOWN) GPIO.output(7, False) GPIO.output(7, True) GPIO.output(7, False) # Send the GD (Get Data) Command ser = serial.Serial('/dev/ttyAMA0', 9600, timeout=1) #ser.open() time.sleep(7.0) # send the first "are you there? command - RD - return from Arduino OK" response = util.sendCommandAndRecieve(ser, "RD") print("response=", response) if (response == "OK\n"): print "Good RD Response" else: print "bad response from RD" pclogging.log(pclogging.ERROR, __name__, "RD failed from Pi to BatteryWatchDog") ser.close() return # Read the value response = util.sendCommandAndRecieve(ser, "ST") print("response=", response) if (response == "OK\n"): print "Good ST Response" # set up our time string #Dec 26 2009", time = "12:34:56 myDateString = time.strftime("%b %d %Y", time.gmtime()) myTimeString = time.strftime("%H:%M:%S", time.gmtime()) #myTimeString = time.strftime("%Y/%m/%d %H:%M:%S", time.gmtime()) response = util.sendCommandAndRecieve(ser, myDateString) response = util.sendCommandAndRecieve(ser, myTimeString) if (response == "OK\n"): print "Good ST-2 Response" else: print "bad response from ST-2 third line" pclogging.log( pclogging.ERROR, __name__, "ST-2 second line failed from Pi to BatteryWatchDog") ser.close() return else: print "bad response from ST" pclogging.log(pclogging.ERROR, __name__, "ST failed from Pi to BatteryWatchDog") ser.close() return # say goodby response = util.sendCommandAndRecieve(ser, "GB") print("response=", response) pclogging.log(pclogging.INFO, __name__, "ST - Time Set on Arduino to Pi Time ") ser.close()
def watchdogdatacollect(source, delay): print("watchdogdatacollect source:%s" % source) time.sleep(delay) # blink GPIO LED when it's run GPIO.setmode(GPIO.BOARD) GPIO.setup(22, GPIO.OUT) GPIO.output(22, False) time.sleep(0.5) GPIO.output(22, True) time.sleep(0.5) GPIO.output(22, False) time.sleep(0.5) GPIO.output(22, True) time.sleep(0.5) GPIO.output(22, False) time.sleep(0.5) GPIO.output(22, True) # setup serial port to Arduino # interrupt Arduino to start listening GPIO.setmode(GPIO.BOARD) GPIO.setup(7, GPIO.OUT, pull_up_down=GPIO.PUD_DOWN) GPIO.output(7, False) GPIO.output(7, True) GPIO.output(7, False) ser = serial.Serial('/dev/ttyAMA0', 9600, timeout=1) #ser.open() #time.sleep(7.0) time.sleep(9.0) # send the first "are you there? command - RD - return from Arduino OK" response = util.sendCommandAndRecieve(ser, "RD") print("response=", response); if (response == "OK\n"): print "Good RD Response" else: print "bad response from RD" pclogging.log(pclogging.ERROR, __name__, "RD failed from Pi to BatteryWatchDog") ser.close() return # Read the value # send the watchdog timer first sendWatchDogTimer.sendWatchDogTimer("watchdogdatacollect", 0,ser) # Send the GD (Get Data) Command response = util.sendCommandAndRecieve(ser, "GD") print("response=", response); # stuff the values into variables splitList = response.split(',') print(splitList) for item in range(len(splitList)): splitList[item] = splitList[item].replace('NAN', "0.0") print(splitList) if (len(splitList) == 15): ArInputVoltage = float(splitList[0]) ArInputCurrent = float(splitList[1]) SolarCellVoltage = float(splitList[2]) SolarCellCurrent = float(splitList[3]) BatteryVoltage = float(splitList[4]) BatteryCurrent = float(splitList[5]) OutsideHumidity = float(splitList[6]) OutsideTemperature = float(splitList[7]) LastReboot = splitList[8] BatteryTemperature = float(splitList[9]) FreeMemory = float(splitList[10]) UnregulatedWindVoltage = float(splitList[11]) RegulatedWindVoltage = float(splitList[12]) SolarWind = int(splitList[13]) ArduinoPiBatteryVoltage = float(splitList[14]) else: print "bad response from GD" # system setup pclogging.log(pclogging.ERROR, __name__, "GD failed from Pi to BatteryWatchDog") # say goodby response = util.sendCommandAndRecieve(ser, "GB") print("response=", response); ser.close() return print("ArInputCurrent =", ArInputCurrent) # power efficiency if ( (SolarCellCurrent*SolarCellVoltage+BatteryCurrent*BatteryVoltage) == 0): powerEfficiency = 10000.0; else: powerEfficiency = (ArInputCurrent*ArInputVoltage/(SolarCellCurrent*SolarCellVoltage+BatteryCurrent*BatteryVoltage))*100 # if power Efficiency < 0, then must be plugged in so add 500ma @ 5V if (powerEfficiency < 0.0): if ((SolarCellCurrent*SolarCellVoltage+BatteryCurrent*BatteryVoltage+5.0*500.0) == 0.0): powerEfficiency = 10000.0; else: powerEfficiency = (ArInputCurrent*ArInputVoltage/(SolarCellCurrent*SolarCellVoltage+BatteryCurrent*BatteryVoltage+5.0*500.0))*100 # get the unread log from the Arduino response = util.sendCommandAndRecieve(ser, "SL") print("response=", response) try: countEntry = int(response) except ValueError: countEntry = 0 if (countEntry > 0): # read all unread entries for i in range(countEntry): logEntry = util.recieveLine(ser) print("recievedLogEntry =", logEntry) # parse and then stuff in log database # stuff the values into variables splitList = logEntry.split(',') print(splitList) if (len(splitList) == 4): ArduinoTime = splitList[0] ArduinoLevel = int(splitList[1]) ArduinoData0 = int(splitList[2]) ArduinoData1 = splitList[3] # now we have the data, stuff it in the database entryValue = util.convertArduinoEntry01ToText(ArduinoData0, ArduinoData1) if (ArduinoData0 == 9): # LOGAlarmTriggered entryValue = util.convertAlarmToText(int(ArduinoData1)) try: print("trying database") con = mdb.connect('localhost', 'root', conf.databasePassword, 'ProjectCuracao'); cur = con.cursor() print "before query" query = "INSERT INTO systemlog(TimeStamp, Level, Source, Message) VALUES('%s', '%s', '%s', '%s')" % (ArduinoTime, ArduinoLevel, 'Ardinuo BatteryWatchDog', entryValue) print("query=%s" % query) cur.execute(query) con.commit() except mdb.Error, e: print "Error %d: %s" % (e.args[0],e.args[1]) con.rollback() #sys.exit(1) finally: cur.close() con.close() del cur del con
def selectWind(source, delay): print("recieveInterruptFromBW source:%s" % source) time.sleep(delay) # blink GPIO LED when it's run GPIO.setmode(GPIO.BOARD) GPIO.setup(22, GPIO.OUT) GPIO.output(22, False) time.sleep(0.1) GPIO.output(22, True) time.sleep(0.1) GPIO.output(22, False) time.sleep(0.1) GPIO.output(22, True) time.sleep(0.1) GPIO.output(22, False) time.sleep(0.1) GPIO.output(22, True) # setup serial port to Arduino # interrupt Arduino to start listening GPIO.setmode(GPIO.BOARD) GPIO.setup(7, GPIO.OUT, pull_up_down=GPIO.PUD_DOWN) GPIO.output(7, False) GPIO.output(7, True) GPIO.output(7, False) # Send the WA (Get Data) Command ser = serial.Serial('/dev/ttyAMA0', 9600, timeout=1) ser.open() time.sleep(7.0) # send the first "are you there? command - RD - return from Arduino OK" response = util.sendCommandAndRecieve(ser, "RD") print("response=", response); if (response == "OK\n"): print "Good RD Response" else: print "bad response from RD" pclogging.log(pclogging.ERROR, __name__, "RD failed from Pi to BatteryWatchDog") ser.close() return globalvars.FAILED # Read the value response = util.sendCommandAndRecieve(ser, "SW") print("response=", response); if (len(response) > 0): pclogging.log(pclogging.INFO, __name__, "sent selectWind command to Battery Watchdog " ) else: # system setup pclogging.log(pclogging.ERROR, __name__, "SW failed from Pi to BatteryWatchDog") # say goodby response = util.sendCommandAndRecieve(ser, "GB") print("response=", response); ser.close() return globalvars.FAILED response = util.sendCommandAndRecieve(ser, "GB") print("response=", response); ser.close() # now we have the data, dostuff with it return True;
def environdatacollect(source, delay): print("environdatacollect source:%s" % source) # delay to not "everything happen at once" time.sleep(delay) # blink GPIO LED when it's run # double blink GPIO.setmode(GPIO.BOARD) GPIO.setup(22, GPIO.OUT) GPIO.output(22, False) time.sleep(0.5) GPIO.output(22, True) time.sleep(0.5) GPIO.output(22, False) time.sleep(0.5) GPIO.output(22, True) # now read in all the required data # Inside Temperature # Barometric Pressure # Initialise the BMP085 and use STANDARD mode (default value) # bmp = BMP085(0x77, debug=True) # bmp = BMP085(0x77) # To specify a different operating mode, uncomment one of the following: # bmp = BMP085(0x77, 0) # ULTRALOWPOWER Mode # bmp = BMP085(0x77, 1) # STANDARD Mode # bmp = BMP085(0x77, 2) # HIRES Mode bmp = BMP085(0x77, 3) # ULTRAHIRES Mode pressure = -1000.0 # bad data insidetemperature =-1000.0 try: pressure = bmp.readPressure()/100.0 insidetemperature = bmp.readTemperature() except IOError as e: print "I/O error({0}): {1}".format(e.errno, e.strerror) except: print "Unexpected error:", sys.exc_info()[0] raise # Inside Humidity Oldinsidehumidity = -1000.0 # bad data insidehumidity = -1000.0 # bad data try: maxCount = 20 count = 0 while (count < maxCount): output = subprocess.check_output(["/home/pi/ProjectCuracao/main/hardware/Adafruit_DHT_MOD", "22", "23"]); print "count=", count print output # search for humidity printout matches = re.search("Hum =\s+([0-9.]+)", output) if (not matches): count = count + 1 time.sleep(3.0) continue Oldinsidehumidity = float(matches.group(1)) count = maxCount # now do it again. Throw out the higher value (get rid of high spikes) time.sleep(1.0) maxCount = 20 count = 0 while (count < maxCount): output = subprocess.check_output(["/home/pi/ProjectCuracao/main/hardware/Adafruit_DHT_MOD", "22", "23"]); print "count=", count print output # search for humidity printout matches = re.search("Hum =\s+([0-9.]+)", output) if (not matches): count = count + 1 time.sleep(3.0) continue insidehumidity = float(matches.group(1)) count = maxCount if (Oldinsidehumidity < insidehumidity): insidehumidity = Oldinsidehumidity except IOError as e: print "I/O error({0}): {1}".format(e.errno, e.strerror) except: print "Unexpected error:", sys.exc_info()[0] raise # setup serial port to Arduino # interrupt Arduino to start listening GPIO.setmode(GPIO.BOARD) GPIO.setup(7, GPIO.OUT, pull_up_down=GPIO.PUD_DOWN) GPIO.output(7, False) GPIO.output(7, True) GPIO.output(7, False) # Outside Temperature # read the latest value from the Arduino # Send the GD (Get Data) Command ser = serial.Serial('/dev/ttyAMA0', 9600, timeout=1) #ser.open() time.sleep(7.0) # send the first "are you there? command - RD - return from Arduino OK" response = util.sendCommandAndRecieve(ser, "RD") print("response=", response); if (response == "OK\n"): print "Good RD Response" else: print "bad response from RD" pclogging.log(pclogging.ERROR, __name__, "RD failed from Pi to BatteryWatchDog") ser.close() return # Read the value response = util.sendCommandAndRecieve(ser, "GTH") print("response=", response); # stuff the values into variables splitList = response.split(',') print(splitList) if (len(splitList) == 2): outsidetemperature = float(splitList[0]) outsidehumidity = float(splitList[1]) else: print "bad response from GTH" # system setup pclogging.log(pclogging.ERROR, __name__, "GTH failed from Pi to BatteryWatchDog") # say goodby response = util.sendCommandAndRecieve(ser, "GB") print("response=", response); ser.close() return print("response=", response); # say goodby response = util.sendCommandAndRecieve(ser, "GB") print("response=", response); ser.close() # Luminosity luminosity = -1000.0 # bad data try: oLuxmeter=Luxmeter() luminosity = oLuxmeter.getLux() except IOError as e: print "I/O error({0}): {1}".format(e.errno, e.strerror) except: print "Unexpected error:", sys.exc_info()[0] raise # Fan State # read from fan state file try: f = open("./state/fanstate.txt", "r") tempString = f.read() f.close() fanstate = int(tempString) except IOError as e: fanstate = 0 print "fanstate=", fanstate # now find our colors bm017 = BM017(True) red_color = 0 blue_color = 0 green_color = 0 clear_color = 0 Gain = 0x00 IntegrationTime = 0xC0 bm017.disableDevice() bm017.setIntegrationTimeAndGain(IntegrationTime, Gain) if (bm017.isBM017There()): bm017.getColors() red_color = bm017.red_color blue_color = bm017.blue_color green_color = bm017.green_color clear_color = bm017.clear_color # now we have the data, stuff it in the database try: print("trying database") con = mdb.connect('localhost', 'root', conf.databasePassword, 'ProjectCuracao'); cur = con.cursor() print "before query" query = 'INSERT INTO environmentaldata(TimeStamp, InsideTemperature, InsideHumidity, OutsideTemperature, OutsideHumidity, BarometricPressure, Luminosity, FanState, Red_Color, Blue_Color, Green_Color, Clear_Color, Gain, IntegrationTime) VALUES(UTC_TIMESTAMP(), %.3f, %.3f, %.3f, %.3f, %.3f, %.3f, %i, %i, %i, %i, %i, %i, %i)' % (insidetemperature, insidehumidity, outsidetemperature, outsidehumidity, pressure, luminosity, fanstate, red_color, blue_color, green_color, clear_color, Gain, IntegrationTime) print("query=%s" % query) cur.execute(query) con.commit() except mdb.Error, e: print "Error %d: %s" % (e.args[0],e.args[1]) con.rollback()
# interrupt callback def arduino_callback(channel): global hasBWInterrupted print('Edge detected on channel %s'%channel) hasBWInterrupted = True print("hasBWSet-2=", hasBWInterrupted) if __name__ == '__main__': # system setup # log system startup pclogging.log(pclogging.INFO, __name__, "Project Curacao Startup") try: myIP = util.track_ip() util.sendEmail("test", "ProjectCuracao Pi Startup\n" + str(myIP), "The Raspberry Pi has rebooted.", conf.notifyAddress, conf.fromAddress, ""); util.sendEmail("test", "ProjectCuracao Pi Startup\n" + str(myIP), "The Raspberry Pi has rebooted.", conf.secondaryNotifyAddress, conf.fromAddress, ""); except: pclogging.log(pclogging.INFO, __name__, "Email / IP fetch failed (Internet down)") GPIO.setwarnings(False) GPIO.setmode(GPIO.BOARD) GPIO.setup(7, GPIO.OUT, pull_up_down=GPIO.PUD_DOWN) # set initial hardware actions hardwareactions.setfan(False)
def handleInterrupt(reason): if (reason == globalvars.NOINTERRUPT): return if (reason == globalvars.NOREASON): return if (reason == globalvars.SHUTDOWN): pclogging.log(pclogging.CRITICAL, __name__, "Project Curacao Pi Shutdown") util.shutdownPi("Interrupt from BatteryWatchdog") return if (reason == globalvars.GETLOG): pclogging.log(pclogging.INFO, __name__, "Fetch Battery Watchdog Log ") return if (reason == globalvars.ALARM1): pclogging.log(pclogging.INFO, __name__, "Battery Watchdog Alarm 1") return if (reason == globalvars.ALARM2): pclogging.log(pclogging.INFO, __name__, "Battery Watchdog Alarm 2") return if (reason == globalvars.ALARM3): pclogging.log(pclogging.INFO, __name__, "Battery Watchdog Alarm 3") return if (reason == globalvars.REBOOT): pclogging.log(pclogging.CRITICAL, __name__, "Project Curacao Pi Reboot") util.rebootPi("Interrupt from BatteryWatchdog") return
def recieveInterruptFromBW(source, delay): print("recieveInterruptFromBW source:%s" % source) time.sleep(delay) # blink GPIO LED when it's run GPIO.setmode(GPIO.BOARD) GPIO.setup(22, GPIO.OUT) GPIO.output(22, False) time.sleep(0.1) GPIO.output(22, True) time.sleep(0.1) GPIO.output(22, False) time.sleep(0.1) GPIO.output(22, True) time.sleep(0.1) GPIO.output(22, False) time.sleep(0.1) GPIO.output(22, True) # setup serial port to Arduino # interrupt Arduino to start listening GPIO.setmode(GPIO.BOARD) GPIO.setup(7, GPIO.OUT, pull_up_down=GPIO.PUD_DOWN) GPIO.output(7, False) GPIO.output(7, True) GPIO.output(7, False) # Send the WA (Get Data) Command ser = serial.Serial('/dev/ttyAMA0', 9600, timeout=1) #ser.open() time.sleep(7.0) # send the first "are you there? command - RD - return from Arduino OK" response = util.sendCommandAndRecieve(ser, "RD") print("response=", response); if (response == "OK\n"): print "Good RD Response" else: print "bad response from RD" pclogging.log(pclogging.ERROR, __name__, "RD failed from Pi to BatteryWatchDog") ser.close() return globalvars.FAILED # Read the value response = util.sendCommandAndRecieve(ser, "WA") print("response=", response); AWAState = 100 #UNKNOWNINTERRUPT AWAState = 101 #BAD INTERRUPT if (len(response) > 0): try: AWAState = int(response) except: AWAState = 101 pclogging.log(pclogging.INFO, __name__, "Recieved Interrupt %s from BatteryWatchDog to Pi" % returnNameFromInterrupt(AWAState)) else: # system setup pclogging.log(pclogging.ERROR, __name__, "WA failed from Pi to BatteryWatchDog") # say goodby response = util.sendCommandAndRecieve(ser, "GB") print("response=", response); ser.close() return globalvars.FAILED # say acknowledge WA response = util.sendCommandAndRecieve(ser, "AWA") print("response=", response); if (response == "OK\n"): print "Good AWA Response" pclogging.log(pclogging.INFO, __name__, "Acknowledged Interrupt %s from BatteryWatchDog to Pi" % returnNameFromInterrupt(AWAState)) else: print "bad response from AWA" pclogging.log(pclogging.ERROR, __name__, "AWA failed from Pi to BatteryWatchDog") ser.close() return globalvars.FAILED response = util.sendCommandAndRecieve(ser, "GB") print("response=", response); ser.close() # now we have the data, dostuff with it return AWAState
# Step 6 - now move solenoid out (pull back) print("Step 6- Rearmed") utils.writeRow(grid,5,__HT16K33_RED) GPIO.output(SOLENOID_LEFT, 1) GPIO.output(SOLENOID_RIGHT, 0) time.sleep(SOLENOID_ON_TIME) GPIO.output(SOLENOID_LEFT, 0) GPIO.output(SOLENOID_RIGHT, 0) grid.clear() # main loop print("Mouse Air Version 1.3") pclogging.log(pclogging.INFO, __name__, "Mouse Air 1.3 Startup") #myIP = util.track_ip() #utils.sendEmail("test", "Mouse Air Pi Startup\n" + str(myIP), "The Raspberry Pi has rebooted.", conf.notifyAddress, conf.fromAddress, ""); detection.initUltrasonic() # start RFID reading detection.initRFID() # set up a communication queue queueRFID = Queue() RFIDThread = Thread(target=detection.RFIDDetect, args=(__name__,0,queueRFID,)) RFIDThread.daemon = True RFIDThread.start()
def rebootPi(why): """Reboot Pi.""" pclogging.log(pclogging.INFO, __name__, "Pi Rebooting: %s" % why) os.system("sudo shutdown -r now")
def fireMouse(): pclogging.log(pclogging.INFO, __name__, "Mouse Launched!") time.sleep(1.0) grid.clear() # Step 1 - Drop Mouse into Chamber # Change speed of continuous servo on channel SERVO_CHAMBER print("Step 1 - Chamber Mouse") pwm.setPWM(servo.SERVO_CHAMBER, 0, servo.servoMin) time.sleep(1) pwm.setPWM(servo.SERVO_CHAMBER, 0, servo.servoMax) time.sleep(1) pwm.setPWM(servo.SERVO_CHAMBER, 0, servo.servoMin) time.sleep(1) pwm.setPWM(servo.SERVO_CHAMBER, 0, servo.servoMax) time.sleep(1) utils.writeRow(grid,0,__HT16K33_RED) # Step 3 - Drop Mouse into Position # Change speed of continuous servo on channel SERVO_LOAD print("Step 2 - Load Mouse") pwm.setPWM(servo.SERVO_LOAD, 0, servo.servoMin) time.sleep(1) pwm.setPWM(servo.SERVO_LOAD, 0, servo.servoMax) time.sleep(1) utils.writeRow(grid,1,__HT16K33_RED) # Step 3 - Start Motors print("Step 3 - Motors Starting") GPIO.output(RIGHT_MOTOR, RIGHT_ON) time.sleep(0.5) GPIO.output(LEFT_MOTOR, LEFT_ON) utils.writeRow(grid,2,__HT16K33_RED) # # Step 4 - Launch Mouse # now move solenoid out (launch mouse!) print("Step 4 - Mouse launched") time.sleep(1.0) GPIO.output(SOLENOID_LEFT, 0) GPIO.output(SOLENOID_RIGHT, 1) time.sleep(SOLENOID_ON_TIME) GPIO.output(SOLENOID_LEFT, 0) GPIO.output(SOLENOID_RIGHT, 0) utils.writeRow(grid,3,__HT16K33_RED) backpack.setBlinkRate(__HT16K33_BLINKRATE_2HZ) utils.writeRow(grid,6,__HT16K33_YELLOW) utils.writeRow(grid,7,__HT16K33_YELLOW) utils.writeRow(grid,6,__HT16K33_GREEN) utils.writeRow(grid,7,__HT16K33_GREEN) # Step 5 - Stop Motors print("Step 5 - Motors Stopping") GPIO.output(RIGHT_MOTOR, RIGHT_OFF) GPIO.output(LEFT_MOTOR, LEFT_OFF) time.sleep(2.0) backpack.setBlinkRate(__HT16K33_BLINKRATE_OFF) utils.writeRow(grid,4,__HT16K33_RED) time.sleep(1.0) # Step 6 - now move solenoid out (pull back) print("Step 6- Rearmed") utils.writeRow(grid,5,__HT16K33_RED) GPIO.output(SOLENOID_LEFT, 1) GPIO.output(SOLENOID_RIGHT, 0) time.sleep(SOLENOID_ON_TIME) GPIO.output(SOLENOID_LEFT, 0) GPIO.output(SOLENOID_RIGHT, 0) grid.clear()
def getFramArduinoLog(source, delay): print("Fram Log datacollect source:%s" % source) time.sleep(delay) # blink GPIO LED when it's run GPIO.setmode(GPIO.BOARD) GPIO.setup(22, GPIO.OUT) GPIO.output(22, False) time.sleep(0.5) GPIO.output(22, True) time.sleep(0.5) GPIO.output(22, False) time.sleep(0.5) GPIO.output(22, True) time.sleep(0.5) GPIO.output(22, False) time.sleep(0.5) GPIO.output(22, True) # setup serial port to Arduino # interrupt Arduino to start listening GPIO.setmode(GPIO.BOARD) GPIO.setup(7, GPIO.OUT, pull_up_down=GPIO.PUD_DOWN) GPIO.output(7, False) GPIO.output(7, True) GPIO.output(7, False) ser = serial.Serial('/dev/ttyAMA0', 9600, timeout=1) #ser.open() ser.flushInput() ser.flushOutput() time.sleep(7.0) # send the first "are you there? command - RD - return from Arduino OK" response = util.sendCommandAndRecieve(ser, "RD") print("response=", response) if (response == "OK\n"): print "Good RD Response" else: print "bad response from RD" pclogging.log(pclogging.ERROR, __name__, "RD failed from Pi to BatteryWatchDog") ser.close() return 0 # Read the value # get the unread log from the Arduino response = util.sendCommandAndRecieve(ser, "SLF") print("response=", response) try: countEntry = int(response) except ValueError: countEntry = 0 print("countEntry=", countEntry) pclogging.log(pclogging.INFO, __name__, "FRAM records read: %i " % countEntry) if (countEntry > 0): # read all unread entries for i in range(countEntry): logEntry = util.recieveLine(ser) print("recievedLogEntry =", logEntry) # parse and then stuff in log database # stuff the values into variables splitList = logEntry.split(',') print(splitList) if (len(splitList) == 11): WeatherLogTime = splitList[0] WeatherLogCWS = float(splitList[1]) WeatherLogCWG = float(splitList[2]) WeatherLogCWD = float(splitList[3]) WeatherLogCWDV = float(splitList[4]) WeatherLogCR = float(splitList[5]) WeatherLogURWV = float(splitList[6]) WeatherLogRWV = float(splitList[7]) WeatherLogPIS = float(splitList[8]) WeatherLogWSCUR = float(splitList[9]) WeatherLogSolarOrWind = int(splitList[10]) # now we have the data, stuff it in the database try: print("trying database") con = mdb.connect('localhost', 'root', conf.databasePassword, 'ProjectCuracao') cur = con.cursor() print "before query" query = "INSERT INTO weatherdata(TimeStamp, CWS, CWG, CWD, CWDV, CR, URWV, RWV, PIS,WSCUR, SolarOrWind) VALUES('%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', %i)" % ( WeatherLogTime, WeatherLogCWS, WeatherLogCWG, WeatherLogCWD, WeatherLogCWDV, WeatherLogCR, WeatherLogURWV, WeatherLogRWV, WeatherLogPIS, WeatherLogWSCUR, WeatherLogSolarOrWind) print("query=%s" % query) cur.execute(query) con.commit() except mdb.Error, e: print "Error %d: %s" % (e.args[0], e.args[1]) con.rollback() #sys.exit(1) finally: cur.close() con.close() del cur del con
def getArduinoLog(source, delay): print("watchdogdatacollect source:%s" % source) time.sleep(delay) # blink GPIO LED when it's run GPIO.setmode(GPIO.BOARD) GPIO.setup(22, GPIO.OUT) GPIO.output(22, False) time.sleep(0.5) GPIO.output(22, True) time.sleep(0.5) GPIO.output(22, False) time.sleep(0.5) GPIO.output(22, True) time.sleep(0.5) GPIO.output(22, False) time.sleep(0.5) GPIO.output(22, True) # setup serial port to Arduino # interrupt Arduino to start listening GPIO.setmode(GPIO.BOARD) GPIO.setup(7, GPIO.OUT, pull_up_down=GPIO.PUD_DOWN) GPIO.output(7, False) GPIO.output(7, True) GPIO.output(7, False) ser = serial.Serial('/dev/ttyAMA0', 9600, timeout=1) #ser.open() ser.flushInput() ser.flushOutput() time.sleep(7.0) # send the first "are you there? command - RD - return from Arduino OK" response = util.sendCommandAndRecieve(ser, "RD") print("response=", response); if (response == "OK\n"): print "Good RD Response" else: print "bad response from RD" pclogging.log(pclogging.ERROR, __name__, "RD failed from Pi to BatteryWatchDog") ser.close() return # Read the value # send the watchdog timer first sendWatchDogTimer.sendWatchDogTimer("watchdogdatacollect", 0,ser) # get the unread log from the Arduino response = util.sendCommandAndRecieve(ser, "SL") print("response=", response) try: countEntry = int(response) except ValueError: countEntry = 0 if (countEntry > 0): # read all unread entries for i in range(countEntry): logEntry = util.recieveLine(ser) print("recievedLogEntry =", logEntry) # parse and then stuff in log database # stuff the values into variables splitList = logEntry.split(',') print(splitList) if (len(splitList) == 4): ArduinoTime = splitList[0] ArduinoLevel = int(splitList[1]) ArduinoData0 = int(splitList[2]) ArduinoData1 = splitList[3] # now we have the data, stuff it in the database entryValue = util.convertArduinoEntry01ToText(ArduinoData0, ArduinoData1) if (ArduinoData0 == 9): # LOGAlarmTriggered entryValue = util.convertAlarmToText(int(ArduinoData1)) try: print("trying database") con = mdb.connect('localhost', 'root', conf.databasePassword, 'ProjectCuracao'); cur = con.cursor() print "before query" query = "INSERT INTO systemlog(TimeStamp, Level, Source, Message) VALUES('%s', '%s', '%s', '%s')" % (ArduinoTime, ArduinoLevel, 'Ardinuo BatteryWatchDog', entryValue) print("query=%s" % query) cur.execute(query) con.commit() except mdb.Error, e: print "Error %d: %s" % (e.args[0],e.args[1]) con.rollback() #sys.exit(1) finally: cur.close() con.close() del cur del con
def setTime(source, delay): print("setTime source:%s" % source) time.sleep(delay) # blink GPIO LED when it's run GPIO.setmode(GPIO.BOARD) GPIO.setup(22, GPIO.OUT) GPIO.output(22, False) time.sleep(0.5) GPIO.output(22, True) time.sleep(0.5) # setup serial port to Arduino # interrupt Arduino to start listening GPIO.setmode(GPIO.BOARD) GPIO.setup(7, GPIO.OUT, pull_up_down=GPIO.PUD_DOWN) GPIO.output(7, False) GPIO.output(7, True) GPIO.output(7, False) # Send the GD (Get Data) Command ser = serial.Serial('/dev/ttyAMA0', 9600, timeout=1) ser.open() time.sleep(7.0) # send the first "are you there? command - RD - return from Arduino OK" response = util.sendCommandAndRecieve(ser, "RD") print("response=", response); if (response == "OK\n"): print "Good RD Response" else: print "bad response from RD" pclogging.log(pclogging.ERROR, __name__, "RD failed from Pi to BatteryWatchDog") ser.close() return # Read the value response = util.sendCommandAndRecieve(ser, "ST") print("response=", response); if (response == "OK\n"): print "Good ST Response" # set up our time string #Dec 26 2009", time = "12:34:56 myDateString = time.strftime("%b %d %Y", time.gmtime()) myTimeString = time.strftime("%H:%M:%S", time.gmtime()) #myTimeString = time.strftime("%Y/%m/%d %H:%M:%S", time.gmtime()) response = util.sendCommandAndRecieve(ser, myDateString) response = util.sendCommandAndRecieve(ser, myTimeString) if (response == "OK\n"): print "Good ST-2 Response" else: print "bad response from ST-2 third line" pclogging.log(pclogging.ERROR, __name__, "ST-2 second line failed from Pi to BatteryWatchDog") ser.close() return else: print "bad response from ST" pclogging.log(pclogging.ERROR, __name__, "ST failed from Pi to BatteryWatchDog") ser.close() return # say goodby response = util.sendCommandAndRecieve(ser, "GB") print("response=", response); pclogging.log(pclogging.INFO, __name__, "ST - Time Set on Arduino to Pi Time ") ser.close()
# Step 6 - now move solenoid out (pull back) print("Step 6- Rearmed") utils.writeRow(grid, 5, __HT16K33_RED) GPIO.output(SOLENOID_LEFT, 1) GPIO.output(SOLENOID_RIGHT, 0) time.sleep(SOLENOID_ON_TIME) GPIO.output(SOLENOID_LEFT, 0) GPIO.output(SOLENOID_RIGHT, 0) grid.clear() # main loop print("Mouse Air Version 1.3") pclogging.log(pclogging.INFO, __name__, "Mouse Air 1.3 Startup") #myIP = util.track_ip() #utils.sendEmail("test", "Mouse Air Pi Startup\n" + str(myIP), "The Raspberry Pi has rebooted.", conf.notifyAddress, conf.fromAddress, ""); detection.initUltrasonic() # start RFID reading detection.initRFID() # set up a communication queue queueRFID = Queue() RFIDThread = Thread(target=detection.RFIDDetect, args=( __name__, 0,
], shell=True) else: WLAN_check_flg = 0 print "WLAN is OK" print "" print "WeatherPi Solar Powered Weather Station Version 1.9 - SwitchDoc Labs" print "" print "" print "Program Started at:" + time.strftime("%Y-%m-%d %H:%M:%S") print "" DATABASEPASSWORD = "******" pclogging.log(pclogging.INFO, __name__, "WeatherPi Startup Version 1.9") sendemail.sendEmail("test", "WeatherPi Startup \n", "The WeatherPi Raspberry Pi has rebooted.", conf.notifyAddress, conf.fromAddress, "") secondCount = 1 while True: # process Interrupts from Lightning if (as3935Interrupt == True): try: process_as3935_interrupt()
def fireMouse(): pclogging.log(pclogging.INFO, __name__, "Mouse Launched!") time.sleep(1.0) grid.clear() # Step 1 - Drop Mouse into Chamber # Change speed of continuous servo on channel SERVO_CHAMBER print("Step 1 - Chamber Mouse") pwm.setPWM(servo.SERVO_CHAMBER, 0, servo.servoMin) time.sleep(1) pwm.setPWM(servo.SERVO_CHAMBER, 0, servo.servoMax) time.sleep(1) pwm.setPWM(servo.SERVO_CHAMBER, 0, servo.servoMin) time.sleep(1) pwm.setPWM(servo.SERVO_CHAMBER, 0, servo.servoMax) time.sleep(1) utils.writeRow(grid, 0, __HT16K33_RED) # Step 3 - Drop Mouse into Position # Change speed of continuous servo on channel SERVO_LOAD print("Step 2 - Load Mouse") pwm.setPWM(servo.SERVO_LOAD, 0, servo.servoMin) time.sleep(1) pwm.setPWM(servo.SERVO_LOAD, 0, servo.servoMax) time.sleep(1) utils.writeRow(grid, 1, __HT16K33_RED) # Step 3 - Start Motors print("Step 3 - Motors Starting") GPIO.output(RIGHT_MOTOR, RIGHT_ON) time.sleep(0.5) GPIO.output(LEFT_MOTOR, LEFT_ON) utils.writeRow(grid, 2, __HT16K33_RED) # # Step 4 - Launch Mouse # now move solenoid out (launch mouse!) print("Step 4 - Mouse launched") time.sleep(1.0) GPIO.output(SOLENOID_LEFT, 0) GPIO.output(SOLENOID_RIGHT, 1) time.sleep(SOLENOID_ON_TIME) GPIO.output(SOLENOID_LEFT, 0) GPIO.output(SOLENOID_RIGHT, 0) utils.writeRow(grid, 3, __HT16K33_RED) backpack.setBlinkRate(__HT16K33_BLINKRATE_2HZ) utils.writeRow(grid, 6, __HT16K33_YELLOW) utils.writeRow(grid, 7, __HT16K33_YELLOW) utils.writeRow(grid, 6, __HT16K33_GREEN) utils.writeRow(grid, 7, __HT16K33_GREEN) # Step 5 - Stop Motors print("Step 5 - Motors Stopping") GPIO.output(RIGHT_MOTOR, RIGHT_OFF) GPIO.output(LEFT_MOTOR, LEFT_OFF) time.sleep(2.0) backpack.setBlinkRate(__HT16K33_BLINKRATE_OFF) utils.writeRow(grid, 4, __HT16K33_RED) time.sleep(1.0) # Step 6 - now move solenoid out (pull back) print("Step 6- Rearmed") utils.writeRow(grid, 5, __HT16K33_RED) GPIO.output(SOLENOID_LEFT, 1) GPIO.output(SOLENOID_RIGHT, 0) time.sleep(SOLENOID_ON_TIME) GPIO.output(SOLENOID_LEFT, 0) GPIO.output(SOLENOID_RIGHT, 0) grid.clear()
def rebootPi(why): pclogging.log(pclogging.INFO, __name__, "Pi Rebooting: %s" % why) os.system("sudo shutdown -r now")