def main(): # ------------------------- # main # ------------------------- # lesen der Werte aus der HTML form cgitb.enable(display=0, logdir="/var/log/apache2") form = cgi.FieldStorage() cgi_color = form.getvalue('color') #print(cgi_color) if (cgi_color != None): CaravanPiFiles.writeTestColor(0, 0, cgi_color) # send kill SIGUSR2 to position2file.py urllib.request.urlopen('http://127.0.0.1:8089/ConfigSite/LEDtest') if cgi_color == "-2": strColor = "grün" elif cgi_color == "-1": strColor = "grün blinkend" elif cgi_color == "0": strColor = "rot" elif cgi_color == "1": strColor = "blau blinkend" elif cgi_color == "2": strColor = "blau" elif cgi_color == "99": strColor = "aus" else: strColor = "----" # Ergebnis Website schreiben print("Content-Type: text/html; charset=utf-8\n\n") print("<html>") print("<head>") print("<title>CaravanPi Konfiguration</title>") print("<meta http-equiv='refresh' content='2; URL=ledtest.php'>") print("<link rel='stylesheet' type='text/css' href='css/main.css'>") print("<link rel='stylesheet' type='text/css' href='css/custom.css'>") print("</head>") print("<body>") print('<header class="header">CaravanPi Konfiguration - LED Test</header>') if (cgi_color != None): print("Die Testroutine wurde gestartet. Die LEDs schalten für mindestens 60 Sekunden auf "+strColor) else: print("ES KONNTEN KEINE WERTE AUS DEM FORMULAR GELESEN WERDEN!") print("<br/><br/>Sie werden zur Eingabeseite weitergeleitet") print("</body>") print("</html>")
def main(): # ------------------------- # main # ------------------------- # lesen der Werte aus der HTML form cgitb.enable(display=0, logdir="/var/log/apache2") form = cgi.FieldStorage() cgi_number = form.getvalue('tankNumber') tankNumber = int(cgi_number) cgi_level1 = form.getvalue('level1') cgi_level2 = form.getvalue('level2') cgi_level3 = form.getvalue('level3') cgi_level4 = form.getvalue('level4') # print(cgi_number, cgi_level1, cgi_level2, cgi_level3, cgi_level4) if (cgi_number != None): (level1, level2, level3, level4) = CaravanPiFiles.readFillLevels(tankNumber) if (cgi_number != None and cgi_level1 != None and cgi_level2 != None and cgi_level3 != None and cgi_level4 != None): level1 = float(cgi_level1) level2 = float(cgi_level2) level3 = float(cgi_level3) level4 = float(cgi_level4) CaravanPiFiles.writeFillLevels(tankNumber, 0, 0, level1, level2, level3, level4) # Ergebnis Website schreiben print("Content-Type: text/html; charset=utf-8\n\n") print("<html>") print("<head>") print("<title>CaravanPi Konfiguration</title>") print("<meta http-equiv='refresh' content='2; URL=fill-levels.php'>") print("<link rel='stylesheet' type='text/css' href='css/main.css'>") print("<link rel='stylesheet' type='text/css' href='css/custom.css'>") print("</head>") print("<body>") print('<header class="header">CaravanPi Konfiguration - Füllstände Tanks</header>') if (cgi_number != None and cgi_level1 != None and cgi_level2 != None and cgi_level3 != None and cgi_level4 != None): print("Die eingegebenen Werte wurden erfolgreich gespeichert") else: print("ES KONNTEN KEINE WERTE AUS DEM FORMULAR GELESEN WERDEN!") print("<br/><br/>Sie werden zur Eingabeseite weitergeleitet") print("</body>") print("</html>")
def main(): # ------------------------- # main # ------------------------- global wideLevel025, wideLevel050, wideLevel100 GPIO.setwarnings(False) # ------------------------- # read defaults # ------------------------- (wideLevel025, wideLevel050, wideLevel100) = CaravanPiFiles.readVoltageLevels() (sp3Wide, sp3USB, sp3BAT, sp3BatLevel) = readSerialPort() try: if sp3Wide <= wide_range_volt_min: sp3Wide = 0 if sp3USB <= mUSB_volt_min: sp3USB = 0 if sp3BAT <= battery_volt_min: sp3BAT = 0 write2file(sp3Wide, sp3USB, sp3BAT, sp3BatLevel, 0) except (KeyboardInterrupt, SystemExit): cleanAndExit() cleanAndExit()
def main(): # ------------------------- # main # ------------------------- # lesen der Werte aus der HTML form cgitb.enable(display=0, logdir="/var/log/apache2") form = cgi.FieldStorage() cgi_number = form.getvalue('flasche-nr') cgi_testgewicht = form.getvalue('kal-testgewicht') flasche = float(cgi_number) testgewicht = float(cgi_testgewicht) # verhindern einer Division durch 0 if (testgewicht == 0): testgewicht = 1 #print(cgi_number, cgi_testgewicht) # Lesen der bisherigen Default Werte if (cgi_number != None): (emptyWeight, fullWeight, pin_dout, pin_sck, channel, refUnit) = CaravanPiFiles.readGasScale(flasche) subprocess.run([ "python3", "/home/pi/CaravanPi/gas-weight/gasScaleCalibration.py", "-c", "-e", cgi_testgewicht, "-g", cgi_number, "-w", "5" ])
def main(): # ------------------------- # main # ------------------------- # lesen der Werte aus der HTML form cgitb.enable(display=0, logdir="/var/log/apache2") form = cgi.FieldStorage() cgi_lengthOverAll = form.getvalue('laenge-alles') cgi_width = form.getvalue('breite-alles') cgi_lengthBody = form.getvalue('laenge-aufbau') #print(cgi_lengthOverAll, cgi_width, cgi_lengthBody) if (cgi_lengthOverAll != None and cgi_width != None and cgi_lengthBody != None): lengthOverAll = float(cgi_lengthOverAll) width = float(cgi_width) lengthBody = float(cgi_lengthBody) CaravanPiFiles.writeDimensions(0, 0, lengthOverAll, width, lengthBody) # Ergebnis Website schreiben print("Content-Type: text/html; charset=utf-8\n\n") print("<html>") print("<head>") print("<title>CaravanPi Konfiguration</title>") print("<meta http-equiv='refresh' content='2; URL=dimensions.php'>") print("<link rel='stylesheet' type='text/css' href='css/main.css'>") print("<link rel='stylesheet' type='text/css' href='css/custom.css'>") print("</head>") print("<body>") print( '<header class="header">CaravanPi Konfiguration - Dimensionen Cravan / Wohnmobil</header>' ) if (cgi_lengthOverAll != None and cgi_width != None and cgi_lengthBody != None): print("Die eingegebenen Werte wurden erfolgreich gespeichert") else: print("ES KONNTEN KEINE WERTE AUS DEM FORMULAR GELESEN WERDEN!") print("<br/><br/>Sie werden zur Eingabeseite weitergeleitet") print("</body>") print("</html>")
def main(): # ------------------------- # main # ------------------------- # lesen der Werte aus der HTML form cgitb.enable(display=0, logdir="/var/log/apache2") form = cgi.FieldStorage() cgi_adjustX = form.getvalue('adjustX') cgi_adjustY = form.getvalue('adjustY') cgi_adjustZ = form.getvalue('adjustZ') #print(cgi_adjustX, cgi_adjustY, cgi_adjustZ) (adjustX, adjustY, adjustZ, toleranceX, toleranceY, approximationX, approximationY, distRight, distFront, distAxis) = CaravanPiFiles.readAdjustment() if (cgi_adjustX != None and cgi_adjustY != None and cgi_adjustZ != None): adjustX = float(cgi_adjustX) adjustY = float(cgi_adjustY) adjustZ = float(cgi_adjustZ) CaravanPiFiles.writeAdjustment(0, 0, adjustX, adjustY, adjustZ, toleranceX, toleranceY, approximationX, approximationY, distRight, distFront, distAxis) # Ergebnis Website schreiben print("Content-Type: text/html; charset=utf-8\n\n") print("<html>") print("<head>") print("<title>CaravanPi Konfiguration</title>") print("<meta http-equiv='refresh' content='2; URL=position.php'>") print("<link rel='stylesheet' type='text/css' href='css/main.css'>") print("<link rel='stylesheet' type='text/css' href='css/custom.css'>") print("</head>") print("<body>") print('<header class="header">CaravanPi Konfiguration - manuelle Einstellungen Lage-Sensor</header>') if (cgi_adjustX != None and cgi_adjustY != None and cgi_adjustZ != None): print("Die eingegebenen Werte wurden erfolgreich gespeichert") else: print("ES KONNTEN KEINE WERTE AUS DEM FORMULAR GELESEN WERDEN!") print("<br/><br/>Sie werden zur Eingabeseite weitergeleitet") print("</body>") print("</html>")
def signalInterruptUSR1(signum, stack): # ------------------------- # signalInterruptUSR1 # SIGUSR1 was send to this process (from setDefaults) # # read Defaults again # ------------------------- global adjustX, adjustY, adjustZ, toleranceX, toleranceY, approximationX, approximationY, distRight, distFront, distAxis print(signum, ' received: read defaults again') (adjustX, adjustY, adjustZ, toleranceX, toleranceY, approximationX, approximationY, distRight, distFront, distAxis) = CaravanPiFiles.readAdjustment()
def signalInterruptUSR2(signum, stack): # ------------------------- # signalInterruptUSR1 # SIGUSR2 was send to this process (from Config Website) # # read color from file to test LEDs # first switchLiveMode if live # ------------------------- print(signum, ' received: test LEDs') color = int(CaravanPiFiles.readTestColor()) print('test LEDs with color ', color) if liveMode == 1: switchInterruptLive(0) setAlle(color)
def main(): # ------------------------- # main # ------------------------- # lesen der Werte aus der HTML form cgitb.enable(display=0, logdir="/var/log/apache2") form = cgi.FieldStorage() cgi_number = form.getvalue('flasche-nr') cgi_leer = form.getvalue('gewicht-leer') cgi_voll = form.getvalue('gewicht-voll') cgi_pin_dout = form.getvalue('gpio-pin-dout') cgi_pin_sck = form.getvalue('gpio-pin-sck') cgi_channel = form.getvalue('hx711-channel') cgi_refUnit = form.getvalue('hx711-refUnit') # print(cgi_number, cgi_leer, cgi_voll, cgi_pin_dout, cgi_pin_sck, cgi_channel, cgi_refUnit) if (cgi_number != None): (emptyWeight, fullWeight, pin_dout, pin_sck, channel, refUnit) = CaravanPiFiles.readGasScale(float(cgi_number)) if (cgi_number != None and cgi_leer != None and cgi_voll != None and cgi_pin_dout != None and cgi_pin_sck != None and cgi_channel != None and cgi_refUnit != None): emptyWeight = float(cgi_leer) fullWeight = float(cgi_voll) pin_dout = float(cgi_pin_dout) pin_sck = float(cgi_pin_sck) channel = cgi_channel refUnit = float(cgi_refUnit) CaravanPiFiles.writeGasScale(float(cgi_number), 0, 0, emptyWeight, fullWeight, pin_dout, pin_sck, channel, refUnit) # Ergebnis Website schreiben print("Content-Type: text/html; charset=utf-8\n\n") print("<html>") print("<head>") print("<title>CaravanPi Konfiguration</title>") print("<meta http-equiv='refresh' content='2; URL=gas-scale.php'>") print("<link rel='stylesheet' type='text/css' href='css/main.css'>") print("<link rel='stylesheet' type='text/css' href='css/custom.css'>") print("</head>") print("<body>") print( '<header class="header">CaravanPi Konfiguration - Gasflaschen-Gewichte</header>' ) if (cgi_number != None and cgi_leer != None and cgi_voll != None and cgi_pin_dout != None and cgi_pin_sck != None and cgi_channel != None and cgi_refUnit != None): print("Die eingegebenen Werte wurden erfolgreich gespeichert") else: print( "ES KONNTEN KEINE bzw. NICHT ALLE WERTE AUS DEM FORMULAR GELESEN WERDEN!" ) print("<br/><br/>Sie werden zur Eingabeseite weitergeleitet") print("</body>") print("</html>")
def main(): # ------------------------- # main # ------------------------- # ------------------------- # process call parameters # ------------------------- opts = [] args = [] gasCylinderNumber = 1 tare = 0 emptyWeight = 0 fullWeight = 0 try: opts, args = getopt.getopt(sys.argv[1:], shortOptions, longOptions) except getopt.GetoptError: print("ERROR: options not correct") usage() sys.exit() for o, a in opts: if o == "--help" or o == "-h": print("HELP") usage() sys.exit() elif o == "--gasscale" or o == "-g": gasCylinderNumber = int(a) for a in args: print("further argument: ", a) # ------------------------- # gpio warnings off # ------------------------- GPIO.setwarnings(False) # ------------------------- # read defaults # ------------------------- (emptyWeight, fullWeight, pin_dout, pin_sck, channel, refUnit) = CaravanPiFiles.readGasScale(gasCylinderNumber) print("bisherige Werte:") print("Leergewicht Flasche: ", emptyWeight) print("max. Gas-Gewicht: ", fullWeight) print("Pin DOUT: ", pin_dout) print("Pin SCK: ", pin_sck) print("Channel: >>", channel, "<<") print("Reference Unit: ", refUnit) hx = HX711(pin_dout, pin_sck) hx.set_reading_format("MSB", "MSB") if channel == "A": hx.set_reference_unit_A(refUnit) elif channel == "B": hx.set_reference_unit_B(refUnit) else: print("invalid HX711 channel: ", channel) print("set channel to A") channel = "A" hx.set_reference_unit_A(refUnit) hx.reset() try: # read sensor if channel == "B": weight = hx.get_weight_B(5) else: weight = hx.get_weight_A(5) print("aktuelle Messung Gaswaage: ", weight) if (weight < 0): weight = weight * (-1) print("aktuelle Messung Gaswaage: ", weight) nettoWeight = weight - tare - emptyWeight nettoLevel = (nettoWeight / fullWeight) * 100 print("Nettogewicht Gas: ", nettoWeight) print("Nettofüllgrad: ", nettoLevel) write2file(nettoWeight, nettoLevel) except (KeyboardInterrupt, SystemExit): cleanAndExit() cleanAndExit()
def main(): # ------------------------- # main # ------------------------- global mymcp1, mymcp2 global tank global waitAfterPumpSeconds global pumpOnTime global pinPumpeAn # ----------------------------------------------- # Initialize the I2C bus and the GPIO port expander # ----------------------------------------------- i2c = busio.I2C(board.SCL, board.SDA) mymcp1 = MCP23017(i2c, address=0x20) mymcp2 = MCP23017(i2c, address=0x21) # ----------------------------------------------- # Initialize the GPIO ports # ----------------------------------------------- GPIO.setmode(GPIO.BCM) # ------------------------- # process call parameters # ------------------------- opts = [] args = [] writeFile = 0 displayScreen = 0 try: opts, args = getopt.getopt(sys.argv[1:], shortOptions, longOptions) except getopt.GetoptError: print(datetime.datetime.now().strftime("%Y%m%d%H%M%S "), "ERROR: options not correct") usage() sys.exit() for o, a in opts: if o == "--help" or o == "-h": print("HELP") usage() sys.exit() elif o == "--tank" or o == "-t": tank = int(a) print("Tanknummer ", '{:.0f}'.format(tank)) elif o == "--file" or o == "-f": print("output also to file ", filePosition) writeFile = 1 elif o == "--screen" or o == "-s": print("output also to this screen") displayScreen = 1 for a in args: print("further argument: ", a) # ------------------------- # read defaults # ------------------------- (literLevel1, literLevel2, literLevel3, literLevel4) = CaravanPiFiles.readFillLevels(tank) # ------------------------- # initialize IO Pins on MCP23017 # pin number from 0 to 15 for the GPIOA0...GPIOA7, GPIOB0...GPIOB7 pins (i.e. pin 12 is GPIOB4) # Füllstände: 1 an Pin GPIOB0 (8), ..., 4 an Pin GPIOB3 (11) # Relais an Pin GPIOB4 (12) # ------------------------- fillingLevel1 = mymcp1.get_pin(8) fillingLevel1.direction = digitalio.Direction.INPUT fillingLevel2 = mymcp1.get_pin(9) fillingLevel2.direction = digitalio.Direction.INPUT fillingLevel3 = mymcp1.get_pin(10) fillingLevel3.direction = digitalio.Direction.INPUT fillingLevel4 = mymcp1.get_pin(11) fillingLevel4.direction = digitalio.Direction.INPUT levelPower = mymcp1.get_pin(12) levelPower.direction = digitalio.Direction.OUTPUT # ------------------------- # initialisieren # ------------------------- levelPower.value = False # ------------------------- # Interrupt for switching on the pump # ------------------------- GPIO.setup(pinPumpeAn, GPIO.IN) # Wenn Pumpe wieder ausschaltet, dann Interruptbehandlung GPIO.add_event_detect(pinPumpeAn, GPIO.RISING, callback=interruptPumpOn, bouncetime=400) # ------------------------- # set things for meassuring at startup # ------------------------- actLiter = 0 pumpOnTime = datetime.datetime.now() - datetime.timedelta( seconds=waitAfterPumpSeconds + 1) # ------------------------- # Main loop # ------------------------- try: while True: if pumpOnTime is not None: elapsed = (datetime.datetime.now() - pumpOnTime).total_seconds() # print("Sekunden seit Interrupt: ", elapsed) if elapsed >= waitAfterPumpSeconds: # print(datetime.datetime.now().strftime("%Y%m%d%H%M%S "), "Spannung anlegen") levelPower.value = True time.sleep(.5) level1contact = not fillingLevel1.value level2contact = not fillingLevel2.value level3contact = not fillingLevel3.value level4contact = not fillingLevel4.value # print("Spannung aus") levelPower.value = False pumpOnTime = None if displayScreen == 1: print("Level 1 erreicht? {0}".format(level1contact), literLevel1, " Liter") print("Level 2 erreicht? {0}".format(level2contact), literLevel2, " Liter") print("Level 3 erreicht? {0}".format(level3contact), literLevel3, " Liter") print("Level 4 erreicht? {0}".format(level4contact), literLevel4, " Liter") if level4contact: actLiter = literLevel4 elif level3contact: actLiter = literLevel3 elif level2contact: actLiter = literLevel2 elif level1contact: actLiter = literLevel1 else: actLiter = 0 if displayScreen == 1: if actLiter < literLevel1: print("Füllmenge gering") else: print("mind. " + str(actLiter) + " Liter im Tank") if writeFile == 1: write2file(actLiter) time.sleep(waitAfterPumpSeconds) except KeyboardInterrupt: GPIO.cleanup() except: print("unprocessed Error:", sys.exc_info()[0]) GPIO.cleanup() # ------------------------- # Cleaning at the end # ------------------------- GPIO.cleanup()
def main(): # ------------------------- # main # ------------------------- # ------------------------- # process call parameters # ------------------------- opts = [] args = [] writeTestFile = 0 displayScreen = 0 displayCode = 0 calibrationWait = 0 # seconds gasCylinderNumber = 1 testgewicht = 1 try: opts, args = getopt.getopt(sys.argv[1:], shortOptions, longOptions) except getopt.GetoptError: print("ERROR: options not correct") usage() sys.exit() for o, a in opts: if o == "--code" or o == "-c": displayCode = 1 elif o == "--help" or o == "-h": print("HELP") usage() sys.exit() elif o == "--gasscale" or o == "-g": gasCylinderNumber = int(a) elif o == "--screen" or o == "-s": print("output also to this screen") displayScreen = 1 elif o == "--test" or o == "-t": writeTestFile = 1 elif o == "--weight" or o == "-e": testgewicht = int(a) elif o == "--wait" or o == "-w": calibrationWait = int(a) for a in args: print("further argument: ", a) # read defaults (emptyWeight, fullWeight, pin_dout, pin_sck, channel, refUnit) = CaravanPiFiles.readGasScale(gasCylinderNumber) if displayScreen == 1: print("Die Kalibrierung wird gestartet ....") print("... vorbereiten der Wägezelle und des HX711 ...") if displayCode == 1: print("Content-Type: text/html; charset=utf-8\n\n") print("<html>") print("<head>") print("<title>CaravanPi Konfiguration</title>") print("<meta http-equiv='refresh' content='20; URL=gas-scale.php'>") print("<link rel='stylesheet' type='text/css' href='css/main.css'>") print("<link rel='stylesheet' type='text/css' href='css/custom.css'>") print("</head>") print("<body>") print('<header class="header">CaravanPi Konfiguration - Kalibrirung der Waage für Gasflasche ', gasCylinderNumber,'</header>') print("Die Kalibrierung wird gestartet ....<br/><br/>") print("... vorbereiten der Wägezelle und des HX711 ...<br/>") # test GPIO Pins if pin_dout == 0 or pin_sck == 0: if displayCode == 1: print("GPIO Pins des HX711 sind nicht richtig gesetzt<br/>") print("PIN DOUT: ", pin_dout, "<br/>") print("PIN SCK: ", pin_sck, "<br/>") print("ABBRUCH<br/>") print("<br/><br/>Sie werden in Kürze zur Eingabeseite weitergeleitet") print("</body>") print("</html>") if displayScreen == 1: print("GPIO Pins des HX711 sind nicht richtig gesetzt") print("PIN DOUT: ", pin_dout) print("PIN SCK: ", pin_sck) print("ABBRUCH") exit(-1) # start sensor hx = HX711(pin_dout, pin_sck) hx.set_reading_format("MSB", "MSB") if displayScreen == 1: print("... setzen des Referenzwertes auf 1 ...") if displayCode == 1: print("... setzen des Referenzwertes auf 1 ...<br/>") if channel == "A": hx.set_reference_unit_A(1) elif channel == "B": hx.set_reference_unit_B(1) else: print("invalid HX711 channel: ", channel) print("set channel to A") channel = "A" hx.set_reference_unit_A(1) hx.reset() # Wait if there was a waiting time parameter i=0 while i < calibrationWait: sleep(1) i+=1 if displayScreen == 1: print("... mehrmaliges Wiegen des Testgewichts ...") if displayCode == 1: print("... mehrmaliges Wiegen des Testgewichts ...<br/><br/>") # read sensor if channel == "B": weight = hx.get_weight_B(19) else: weight = hx.get_weight_A(19) if displayScreen == 1: print("... für das Testgewichts von ",testgewicht, " Gramm wurde ein Referenzwert von ", weight ," ermittelt ...") if displayCode == 1: print("... für das Testgewichts von ",testgewicht, " Gramm wurde ein Referenzwert von ", weight ," ermittelt ...<br/>") refUnit = weight / testgewicht if displayScreen == 1: print("... daraus ergibt sich ein Referenzwert von ", refUnit, " ...") print("... setzen des Referenzwertes auf ", refUnit, " ...") if displayCode == 1: print("... daraus ergibt sich ein Referenzwert von ", refUnit, " ...<br/><br/>") print("... setzen des Referenzwertes auf ", refUnit, " ...<br/>") if channel == "B": hx.set_reference_unit_B(refUnit) else: hx.set_reference_unit_A(refUnit) hx.reset() if displayScreen == 1: print("... erneutes mehrmaliges Wiegen des Testgewichts ...") if displayCode == 1: print("... erneutes mehrmaliges Wiegen des Testgewichts ...<br/><br/>") # read sensor if channel == "B": weight = hx.get_weight_B(5) else: weight = hx.get_weight_A(5) if displayScreen == 1: print("... für das Testgewichts von ",testgewicht, " Gramm wurde nun ein Gewicht von ", weight ," Gramm ermittelt ...") print("... der neue Referenzwert wird in die Default Datei geschrieben ...") if displayCode == 1: print("... für das Testgewichts von ",testgewicht, " Gramm wurde nun ein Gewicht von ", weight ," Gramm ermittelt ...<br/><br/>") print("... der neue Referenzwert wird in die Default Datei geschrieben ...<br/><br/>") # write new defaults CaravanPiFiles.writeGasScale(gasCylinderNumber, writeTestFile, displayScreen, emptyWeight, fullWeight, pin_dout, pin_sck, channel, refUnit) # cleanup GPIO hx.GPIOcleanup() if displayCode == 1: print("... damit wurde die Kalibrierung der Waage für die Gasflasche ", gasCylinderNumber, " abgeschlossen.<br/><br/>") print("<br/><br/>Sie werden in Kürze zur Eingabeseite weitergeleitet") print("</body>") print("</html>")
def main(): # ------------------------- # main # ------------------------- global adjustX, adjustY, adjustZ, toleranceX, toleranceY, approximationX, approximationY, distRight, distFront, distAxis global LED_HR, LED_HL, LED_ZR, LED_ZL, LED_VR, LED_VL, LED_Vo global globY, globAdjustY, globAdjustSwitchY global lengthOverAll, width, lengthBody global pinSwitchNowHorizontal, pinSwitchLive, pinLEDLive global liveMode # ------------------------- # tactile switches # ------------------------- GPIO.setmode(GPIO.BCM) GPIO.setup(pinSwitchNowHorizontal, GPIO.IN) GPIO.add_event_detect(pinSwitchNowHorizontal, GPIO.RISING, callback=switchInterruptNowHorizontal, bouncetime=400) GPIO.setup(pinSwitchLive, GPIO.IN) GPIO.add_event_detect(pinSwitchLive, GPIO.RISING, callback=switchInterruptLive, bouncetime=400) GPIO.setup(pinLEDLive, GPIO.OUT) GPIO.output(pinLEDLive, False) # ------------------------- # process call parameters # ------------------------- opts = [] args = [] writeFile = 0 displayScreen = 0 liveMode = 0 try: opts, args = getopt.getopt(sys.argv[1:], shortOptions, longOptions) except getopt.GetoptError: print(datetime.datetime.now().strftime("%Y%m%d%H%M%S "), "ERROR: options not correct") usage() sys.exit() for o, a in opts: if o == "--help" or o == "-h": print("HELP") usage() sys.exit() elif o == "--file" or o == "-f": print("output also to file ", filePosition) writeFile = 1 elif o == "--screen" or o == "-s": print("output also to this screen") displayScreen = 1 elif o == "--live" or o == "-l": print("start in live mode") liveMode = 1 GPIO.output(pinLEDLive, True) for a in args: print("further argument: ", a) # ------------------------- # avoid outliers - init values # ------------------------- lastX = None lastY = None lastZ = None secondLastX = None # read defaults # The 3-axis sensor may not be installed exactly horizontally. The values to compensate for this installation difference are read from a file. # --> adjustX, adjustY, adjustZ # In addition, the LEDs should already indicate "horizontal" as soon as the deviation from the horizontal is within a tolerance. # --> approximationX, approximationY (adjustX, adjustY, adjustZ, toleranceX, toleranceY, approximationX, approximationY, distRight, distFront, distAxis) = CaravanPiFiles.readAdjustment() # dimensions of the caravan (lengthOverAll, width, lengthBody) = CaravanPiFiles.readDimensions() # ------------------------- # listen to SIGUSR1 for renew the defaults # ------------------------- signal.signal(signal.SIGUSR1, signalInterruptUSR1) signal.signal(signal.SIGUSR2, signalInterruptUSR2) # ------------------------- # initialize LEDs # ------------------------- LED_HR = setupHR() LED_HL = setupHL() LED_ZR = setupZR() LED_ZL = setupZL() LED_VR = setupVR() LED_VL = setupVL() LED_Vo = setupVo() # ------------------------- # leds off if non-live-mode # ------------------------- if liveMode == 0: ledOff() # read sensor and adjust LEDs while True: print(datetime.datetime.now().strftime("%Y%m%d%H%M%S "), "live Modus:", liveMode) try: i = 0 arrayX = [] arrayY = [] arrayZ = [] # read sensor 200 times and put values in a list while i < 200: (x, y, z) = accelerometer.acceleration arrayX.append(x) arrayY.append(y) arrayZ.append(z) i += 1 # no sleep here, because the accuracy of Python/Raspberry Sleep is not sufficient anyway # instead a high number of passes over the loop variable # normalize values over the calculation of the median (extreme values/outliers are not considered) # Adjustment of the values by subtraction of the initial value x = statistics.median(arrayX) # determine the index of the first occurrence of x in the list try: i = arrayX.index(x) # set the counterparts for y and z belonging to the value x y = arrayY[i] z = arrayZ[i] except (ValueError, IndexError): # the median did not result in a value that appears in the list (i.e. an actually calculated value). # Then set the other median values as well y = statistics.median(arrayY) z = statistics.median(arrayZ) # save values for tactile switch adjustment globY = y globAdjustY = adjustY tolX = checkTolerance(x, adjustX, toleranceX) tolY = checkTolerance(y, adjustY, toleranceY) # calculate the horizontal distance # Attention: If the 3-axis sensor is mounted behind the axis (in driving direction), # the distance to the axis is positive. Otherwise this constant is negative. distLeft = width - distRight distBack = lengthBody - distFront # ADXL345 data sheet: # resolution typical 3.9 mg = 0.0039g # arcsin(0.0039) = 0.223454 degree # # diff = dist * sin(angle) # # x is the gravity in longitudinal direction # arcsin (gravity) = angle # sin(angle) = sin(arcsin(gravity)) = gravity # difference negative = position is "too high" diffHL = round((distLeft * tolY / 10) + (distBack * tolX / 10) * -1) diffHR = round((distRight * tolY / 10) + (distBack * tolX / 10) * -1) diffZL = round((distLeft * tolY / 10) + (distAxis * tolX / 10)) diffZR = round((distRight * tolY / 10) + (distAxis * tolX / 10)) diffVL = round((distLeft * tolY / 10) + (distFront * tolX / 10)) diffVR = round((distRight * tolY / 10) + (distFront * tolX / 10)) # where is the sensor left or right of the middle? if distRight <= (width / 2): # sensor is on the right side in driving direction of the caravan diffVo = round((((width / 2) - distRight) * tolY / 10) + ((distFront + (lengthOverAll - lengthBody)) * tolX / 10)) else: diffVo = round((((width / 2) - distLeft) * tolY / 10) + ((distFront + (lengthOverAll - lengthBody)) * tolX / 10)) # one of the Z-values should be zero - normalise the others if diffZL >= diffZR: diffNormal = diffZL else: diffNormal = diffZR diffHL = diffHL - diffNormal diffHR = diffHR - diffNormal diffZL = diffZL - diffNormal diffZR = diffZR - diffNormal diffVL = diffVL - diffNormal diffVR = diffVR - diffNormal diffVo = diffVo - diffNormal # write values to file and or screen write2file(writeFile, displayScreen, x, y, z, tolX, tolY, z - adjustZ, lastX, secondLastX, diffHL, diffHR, diffVL, diffVR, diffZL, diffZR, diffVo) if liveMode == 1: ledX = x ledY = y ledZ = z # avoid outliers # if lastX and secondLastX have already been assigned values once # and the current value is not equal to lastX and is also not equal to secondLastX, # but the two values lastX and secondLastX are equal, it may be an outlier. # Then the current values are not used for LED control, but the previous values. #Only the comparison with the X values is necessary, because y and z are dependent on x. if (lastX != None and secondLastX != None): if (x != lastX and x != secondLastX and lastX == secondLastX): ledX = lastX ledY = lastY ledZ = lastZ LED(ledX, ledY, ledZ, adjustX, adjustY, globAdjustSwitchY, adjustZ, toleranceX, toleranceY, approximationX, approximationY) # avoid outliers - swap vars secondLastX = lastX lastX = x lastY = y lastZ = z sleep(.1) else: j = 0 while j < 120 and liveMode == 0: # 120/.5 = 60 Sekunden j = j + 1 sleep(.5) # falls inzwsichen LEDtest gestartet wurde, alle LEDs aus ledOff() except KeyboardInterrupt: ledOff() GPIO.cleanup() break except: print("unprocessed Error:", sys.exc_info()[0]) ledOff() GPIO.cleanup() raise GPIO.cleanup()
def main(): # ------------------------- # main # ------------------------- global mymcp1, mymcp2 global tank # ----------------------------------------------- # Initialize the I2C bus and the GPIO port expander # ----------------------------------------------- i2c = busio.I2C(board.SCL, board.SDA) mymcp1 = MCP23017(i2c, address=0x20) mymcp2 = MCP23017(i2c, address=0x21) # ----------------------------------------------- # Initialize the GPIO ports # ----------------------------------------------- GPIO.setmode(GPIO.BCM) # ------------------------- # process call parameters # ------------------------- opts = [] args = [] writeFile = 0 displayScreen = 0 try: opts, args = getopt.getopt(sys.argv[1:], shortOptions, longOptions) except getopt.GetoptError: print(datetime.datetime.now().strftime("%Y%m%d%H%M%S "), "ERROR: options not correct") usage() sys.exit() for o, a in opts: if o == "--help" or o == "-h": print("HELP") usage() sys.exit() elif o == "--tank" or o == "-t": tank = int(a) print("Tanknummer ", '{:.0f}'.format(tank)) elif o == "--file" or o == "-f": print("output also to file ", filePosition) writeFile = 1 elif o == "--screen" or o == "-s": print("output also to this screen") displayScreen = 1 for a in args: print("further argument: ", a) # ------------------------- # read defaults # ------------------------- (literLevel1, literLevel2, literLevel3, literLevel4) = CaravanPiFiles.readFillLevels(tank) # ------------------------- # initialize IO Pins on MCP23017 # pin number from 0 to 15 for the GPIOA0...GPIOA7, GPIOB0...GPIOB7 pins (i.e. pin 12 is GPIOB4) # Füllstände: 1 an Pin GPIOB3 (11), ..., 4 an Pin GPIOB6 (14) # ------------------------- fillingLevel1 = mymcp2.get_pin(11) fillingLevel1.direction = digitalio.Direction.INPUT fillingLevel2 = mymcp2.get_pin(12) fillingLevel2.direction = digitalio.Direction.INPUT fillingLevel3 = mymcp2.get_pin(13) fillingLevel3.direction = digitalio.Direction.INPUT fillingLevel4 = mymcp2.get_pin(14) fillingLevel4.direction = digitalio.Direction.INPUT # ------------------------- # Main # ------------------------- try: while True: if displayScreen == 1: print("Level prüfen ...") level1contact = fillingLevel1.value level2contact = fillingLevel2.value level3contact = fillingLevel3.value level4contact = fillingLevel4.value if displayScreen == 1: print("Level 1 erreicht? {0}".format(level1contact), literLevel1, " Liter") print("Level 2 erreicht? {0}".format(level2contact), literLevel2, " Liter") print("Level 3 erreicht? {0}".format(level3contact), literLevel3, " Liter") print("Level 4 erreicht? {0}".format(level4contact), literLevel4, " Liter") if level4contact: actLiter = literLevel4 elif level3contact: actLiter = literLevel3 elif level2contact: actLiter = literLevel2 elif level1contact: actLiter = literLevel1 else: actLiter = 0 if displayScreen == 1: if actLiter < literLevel1: print("Füllmenge gering") else: print("mind. " + str(actLiter) + " Liter im Tank") if writeFile == 1: write2file(actLiter) time.sleep(waitAfterReadingSeconds) except KeyboardInterrupt: GPIO.cleanup() except: print("unprocessed Error:", sys.exc_info()[0]) GPIO.cleanup() # ------------------------- # Cleaning at the end # ------------------------- GPIO.cleanup()