Skip to content

Commit

Permalink
flask website weiterentwickelt, configs weiterentwickelt, 230V Check,…
Browse files Browse the repository at this point in the history
… Gas Check, BatteryMgmt Liontron

Die Flask Webseite wurde um Test Routinen, weiter Configs und Checks erweitert. Die Gaswaagen wurden getestet, aber sind noch nicht fertig. Die mariaDB wird nun bereinigt. Ein AD Wandler wurde integriert. Damit werden 230V und 12V überwacht, sowie ein Gassensor MQ-2. Für den Buzzer wurden Melodien eingefügt. Die Installation wurde bereinigt, obsoletes entsprechend markiert und verschoben.
  • Loading branch information
upgrade_script committed Mar 2, 2024
1 parent c6c6508 commit e96cb8d
Show file tree
Hide file tree
Showing 105 changed files with 3,729 additions and 495 deletions.
3 changes: 1 addition & 2 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -12,9 +12,8 @@ __pycache__/
# ignoriere fremde libraries
.lib/hx711py
.lib/hx711py/*
.lib/hx711pySJJSJJSJJSJJ
.lib/hx711pySJJSJJSJJSJJ/*
.lib/*pyc
.lib/Adafruit_Python_ADS1x15

# ignoriere defaults/_allt, das durch abwaerttskompatibilitaet entsteht
defaults/_alt/
Expand Down
367 changes: 219 additions & 148 deletions .lib/CaravanPiFilesClass.py

Large diffs are not rendered by default.

111 changes: 93 additions & 18 deletions .lib/CaravanPiFunctionsClass.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,9 +7,13 @@
#Since this class is not initialized via __init__, the functions do not contain a fist parameter self
#
#-------------------------------------------------------------------------------
import sys
import os
import time
import psutil
import sys
import subprocess




class CaravanPiFunctions:
Expand All @@ -27,25 +31,97 @@ def __init__(self):
# -----------------------------------------------
# determine process number pid
# -----------------------------------------------
def process_running(self, name):
for fso in os.listdir('/proc'):
path = os.path.join('/proc', fso)
if os.path.isdir(path):
try:
# das Verzeichnis eines Prozesses trägt die
# numerische UID als Namen
uid = int(fso)
stream = open(os.path.join(path, 'cmdline'))
cmdline = stream.readline()
stream.close()
if name in cmdline and "/bin/sh" not in cmdline:
return uid
except ValueError:
# kein Prozessverzeichnis
continue
def process_running(self, partial_name):
# Bestimmt die PID eines laufenden Prozesses anhand seines Namens.
for proc in psutil.process_iter(['pid', 'name', 'cmdline']):
# Überprüft, ob der gesuchte Prozessname in der Kommandozeile enthalten ist
if partial_name in ' '.join(proc.info['cmdline']):
return proc.pid
return 0

# -----------------------------------------------
# sende ein signal an einen Prozess, der einen String enthält
# sende das Signal nur an den ersten gefunden
# dies ist notwendig, da der prozess in der Prozessliste zweimal auftritt, da er durch cron gestartet wird
# -----------------------------------------------

def send_signal_to_process(self, partial_name, signal2process):
found_process = None

pid = self.process_running(partial_name)

if pid:
found_process = psutil.Process(pid)

# gibt es Kindprozesse?
# also wurde von crontab gestartet?
children = found_process.children()
if children:
try:
children[0].send_signal(signal2process)
print(f"Signal {signal2process} wurde erfolgreich an Kindprozess {children[0].pid} gesendet.")
except Exception as e:
print(f"Fehler beim Senden von {signal2process} an Kindprozess {children[0].pid}: {e}")
return -1
else:
# Versucht, das Signal an den Prozess (ohne Kindprozesse) zu senden
# Prozess wurde anscheinend manuell gestartet
try:
found_process.send_signal(signal2process)
print(f"Signal {signal2process} wurde erfolgreich an Prozess {found_process.pid} gesendet.")
except Exception as e:
print(f"Fehler beim Senden von {signal2process} an Prozess {found_process.pid}: {e}")
return -1

return 0
else:
print(f"Kein Prozess mit Teilstring '{partial_name}' gefunden.")
return -1


def start_process_in_background(self, command):
try:
# Stellt sicher, dass der Befehl als Hintergrundprozess läuft
process = subprocess.Popen(command, stdout=subprocess.PIPE, stderr=subprocess.PIPE, shell=True)
print(f"Prozess {process.pid} wurde erfolgreich im Hintergrund gestartet.")
return 0
except Exception as e:
print(f"Fehler beim Starten des Prozesses: {e}")
return -1


# -----------------------------------------------
# Spiele Alarmtöne
# -----------------------------------------------
def play_alarm_single(self, gpio, buzzer_pin, alarmnr):
gpio.setmode(gpio.BCM)
gpio.setup(buzzer_pin, gpio.OUT)

# Muster für die verschiedenen Alarme als Liste von (Tonlänge, Pausenlänge)-Tupeln (jeweils in Sekunden)
patterns = {
0: [(0.05, 0.1), (0.5, 1)], # Standardmuster für andere Alarme
1: [(0.05, 0.1), (0.05, 0.1), (0.5, 1)], # Alarm 1
2: [(0.05, 0.1), (0.05, 0.1), (0.05, 0.1), (0.5, 1)], # Alarm 2
3: [(0.05, 0.1), (0.05, 0.1), (0.05, 0.1), (0.05, 0.1), (0.5, 1)], # Alarm 2
}

# Muster basierend auf alarmnrsetzen
pattern = patterns.get(alarmnr, patterns[0])

print(f"Alarm {alarmnr}")

# Durchlaufe das gewählte Muster
for tone_length, pause_length in pattern:
gpio.output(buzzer_pin, gpio.HIGH)
time.sleep(tone_length)
gpio.output(buzzer_pin, gpio.LOW)
time.sleep(pause_length)

print("Alarm Ende")

#gpio.cleanup()
return True

# -----------------------------------------------
# Spiele einen Ton
# -----------------------------------------------
Expand All @@ -56,7 +132,6 @@ def play_tone(self, pwm, frequency, duration):
time.sleep(duration)
pwm.stop()


# -----------------------------------------------
# Spiele die Melodie Erfolg
# gpio ist bereits durch aufrufende Funktion initialisiert
Expand Down
10 changes: 10 additions & 0 deletions .lib/hx711.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,14 @@
# ----------------------------------------------------------------------------------------
# HX711 Routine für Python
#
# Quelle: underdog: https://gist.github.com/underdoeg/98a38b54f889fce2b237
#
# Erweiterungen von Josef Spitzlberger für CaravanPi https://github.com/spitzlbergerj/CaravanPi
#
# - Robustheit erhöht, damit bei fehlendem oder defektem HX711 keine Endlos schleifen entstehen
# - Fehlerstatus wird zurückgeliefert
#
# ---------------------------------------------------------------------------------------

import RPi.GPIO as GPIO
import time
Expand Down
179 changes: 179 additions & 0 deletions .lib/hx711_j_dohnalek.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,179 @@
"""
HX711 Load cell amplifier Python Library
Original source: https://gist.github.com/underdoeg/98a38b54f889fce2b237
Documentation source: https://github.com/aguegu/ardulibs/tree/master/hx711
Adapted by 2017 Jiri Dohnalek
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License along
with this program; if not, write to the Free Software Foundation, Inc.,
51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
"""


import RPi.GPIO as GPIO
import time
import sys


class HX711:

def __init__(self, dout, pd_sck, gain=128):
"""
Set GPIO Mode, and pin for communication with HX711
:param dout: Serial Data Output pin
:param pd_sck: Power Down and Serial Clock Input pin
:param gain: set gain 128, 64, 32
"""
self.GAIN = 0
self.OFFSET = 0
self.SCALE = 1

# Setup the gpio pin numbering system
GPIO.setmode(GPIO.BCM)

# Set the pin numbers
self.PD_SCK = pd_sck
self.DOUT = dout

# Setup the GPIO Pin as output
GPIO.setup(self.PD_SCK, GPIO.OUT)

# Setup the GPIO Pin as input
GPIO.setup(self.DOUT, GPIO.IN)

# Power up the chip
self.power_up()
self.set_gain(gain)

def set_gain(self, gain=128):

try:
if gain == 128:
self.GAIN = 3
elif gain == 64:
self.GAIN = 2
elif gain == 32:
self.GAIN = 1
except:
self.GAIN = 3 # Sets default GAIN at 128

GPIO.output(self.PD_SCK, False)
self.read()

def set_scale(self, scale):
"""
Set scale
:param scale, scale
"""
self.SCALE = scale

def set_offset(self, offset):
"""
Set the offset
:param offset: offset
"""
self.OFFSET = offset

def get_scale(self):
"""
Returns value of scale
"""
return self.SCALE

def get_offset(self):
"""
Returns value of offset
"""
return self.OFFSET

def read(self):
"""
Read data from the HX711 chip
:param void
:return reading from the HX711
"""

# Control if the chip is ready
while not (GPIO.input(self.DOUT) == 0):
# Uncommenting the print below results in noisy output
# print("No input from HX711.")
pass

# Original C source code ported to Python as described in datasheet
# https://cdn.sparkfun.com/datasheets/Sensors/ForceFlex/hx711_english.pdf
# Output from python matched the output of
# different HX711 Arduino library example
# Lastly, behaviour matches while applying pressure
# Please see page 8 of the PDF document

count = 0

for i in range(24):
GPIO.output(self.PD_SCK, True)
count = count << 1
GPIO.output(self.PD_SCK, False)
if(GPIO.input(self.DOUT)):
count += 1

GPIO.output(self.PD_SCK, True)
count = count ^ 0x800000
GPIO.output(self.PD_SCK, False)

# set channel and gain factor for next reading
for i in range(self.GAIN):
GPIO.output(self.PD_SCK, True)
GPIO.output(self.PD_SCK, False)

return count

def read_average(self, times=16):
"""
Calculate average value from
:param times: measure x amount of time to get average
"""
sum = 0
for i in range(times):
sum += self.read()
return sum / times

def get_grams(self, times=16):
"""
:param times: Set value to calculate average,
be aware that high number of times will have a
slower runtime speed.
:return float weight in grams
"""
value = (self.read_average(times) - self.OFFSET)
grams = (value / self.SCALE)
return grams

def tare(self, times=16):
"""
Tare functionality fpr calibration
:param times: set value to calculate average
"""
sum = self.read_average(times)
self.set_offset(sum)

def power_down(self):
"""
Power the chip down
"""
GPIO.output(self.PD_SCK, False)
GPIO.output(self.PD_SCK, True)

def power_up(self):
"""
Power the chip up
"""
GPIO.output(self.PD_SCK, False)
39 changes: 39 additions & 0 deletions analogSignals/analogRead.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
import time
import board
import busio
import adafruit_ads1x15.ads1015 as ADS
from adafruit_ads1x15.analog_in import AnalogIn

# Create the I2C bus
i2c = busio.I2C(board.SCL, board.SDA)

# Create the ADC object using the I2C bus
ads = ADS.ADS1015(i2c)

# Create single-ended input on channel 0
chan0 = AnalogIn(ads, ADS.P0)
chan1 = AnalogIn(ads, ADS.P1)
chan2 = AnalogIn(ads, ADS.P2)
chan3 = AnalogIn(ads, ADS.P3)

# Create differential input between channel 0 and 1
#chan = AnalogIn(ads, ADS.P0, ADS.P1)

print("{:>5}\t{:>5}".format('raw', 'v'))

print('[press ctrl+c to end the script]')

try: # Main program loop
while True:
print("0: {:>5}\t{:>5.3f}".format(chan0.value, chan0.voltage))
print("1: {:>5}\t{:>5.3f}".format(chan1.value, chan1.voltage))
print("2: {:>5}\t{:>5.3f}".format(chan2.value, chan2.voltage))
print("3: {:>5}\t{:>5.3f}".format(chan3.value, chan2.voltage))

print("---")

time.sleep(0.5)

except KeyboardInterrupt:
# Savenging work after the end of the program
print('Script end!')
Loading

0 comments on commit e96cb8d

Please sign in to comment.