Priorisierung

Python auf Einplatinencomputer wie Raspberry Pi, Banana Pi / Python für Micro-Controller
DL9AM
User
Beiträge: 27
Registriert: Mittwoch 29. August 2018, 14:28

Hallo,

ich habe mal einen Code zusammen gebaut, der aber noch nicht so funktioniert wie ich es mir vorstelle.
Halbwegs geht er, denn wenn ich GPIO 18 high mache gibt er einmal den Flankentext, wird Pin 18 low kommt einmal
"Ende" angezeigt...

Das würde so gehen um einmal einen Befehl auszuführen...

So müsste es aber auch bei GPIO 23 und 24 gehen ...

und als Step 2 müsste bei aktiven GPIO 18, 23 oder 24 das "False" blockiert werden, erst wenn der letzte aktive GPIO low wird, darf
das "Ende" auftauchen..

Code: Alles auswählen

#!/usr/bin/python
import RPi.GPIO as GPIO
import time
import datetime

# Variablen initialisieren
Tic = 0    # Zaehler
stopp = 0  # Zeitpunkt steigende Flanke
start = 0  # Zeitpunkt fallende Flanke
delta = 0  # Zeitdifferenz zwischen start und stopp
# Variablen initialisieren
Tic2 = 0    # Zaehler
stopp2 = 0  # Zeitpunkt steigende Flanke
start2 = 0  # Zeitpunkt fallende Flanke
delta2 = 0  # Zeitdifferenz zwischen start und stopp
# Variablen initialisieren
Tic3 = 0    # Zaehler
stopp3 = 0  # Zeitpunkt steigende Flanke
start3 = 0  # Zeitpunkt fallende Flanke
delta3 = 0  # Zeitdifferenz zwischen start und stopp

# GPIO initialisieren
GPIO.setmode(GPIO.BCM)
GPIO.setup(18, GPIO.IN) # Pin 11
GPIO.setup(23, GPIO.IN)
GPIO.setup(24, GPIO.IN)

# internen Pullup-Widerstand aktivieren.
GPIO.setup(18, GPIO.IN, pull_up_down = GPIO.PUD_UP)
GPIO.setup(23, GPIO.IN, pull_up_down = GPIO.PUD_UP)
GPIO.setup(24, GPIO.IN, pull_up_down = GPIO.PUD_UP)

# Callback-Funktion fuer beide Flanken
def measure(channel):
  global start
  global stopp
  global delta
  if GPIO.input(18) == 0:       # fallende Flanke, Startzeit speichern
    start = time.time()
  else:                         # steigende Flanke, Endezeit speichern
    stopp = time.time()
    delta = stopp - start       # Zeitdifferenz berechnen
    print("delta = %1.2f" % delta)

  global start2
  global stopp2
  global delta2
  if GPIO.input(23) == 0:
    start2 = time.time()
  else:                         # steigende Flanke, Endezeit speichern
    stopp2 = time.time()
    delta2 = stopp - start       # Zeitdifferenz berechnen
    print("delta = %1.2f" % delta)

  global start3
  global stopp3
  global delta3
  if GPIO.input(24) == 0:
    start3 = time.time()
  else:                         # steigende Flanke, Endezeit speichern
    stopp3 = time.time()
    delta3 = stopp - start       # Zeitdifferenz berechnen
    print("delta = %1.2f" % delta)

  if GPIO.input(18) == False:
    print("Test1")
  if GPIO.input(23) == False:
    print("Test2")
  if GPIO.input(24) == False:
    print("Test3")

# Interrupt fuer beide Flanken aktivieren
GPIO.add_event_detect(18, GPIO.BOTH, callback=measure, bouncetime=200)
GPIO.add_event_detect(23, GPIO.BOTH, callback=measure, bouncetime=200)
GPIO.add_event_detect(24, GPIO.BOTH, callback=measure, bouncetime=200)

try:
  i = 3
  while i < 100:
    # nix Sinnvolles tun
    Tic = Tic + 1
    print "Tic %d" % Tic
    time.sleep(1)

# reset GPIO settings if user pressed Ctrl+C
except KeyboardInterrupt:
  GPIO.cleanup()
  print("\nBye!")

DL9AM
User
Beiträge: 27
Registriert: Mittwoch 29. August 2018, 14:28

Hallo,

jetzt läuft es, aber ein Problem besteht noch bevor ich den Code einbaue.

Wie kann ich es hinbekommen, das solange GPIO 18 UND/ODER 23 UND/ODER 24 UND/ODER 12 nicht :

xx = 18,23,24,12
if GPIO.input(xx) == False:
print("SquelchDetect_1 - GPIO low")

ausgeführt wird - also quasi übersprungen ?

Erst wenn keiner der 4 GPIO mehr high ist, darf der Befehl erfolgen...

glg

Code: Alles auswählen

#!/usr/bin/python
import RPi.GPIO as GPIO
import time
import datetime

# Variablen initialisieren
Tic = 0    # Zaehler
stopp = 0  # Zeitpunkt steigende Flanke
start = 0  # Zeitpunkt fallende Flanke
delta = 0  # Zeitdifferenz zwischen start und stopp

# GPIO initialisieren
GPIO.setmode(GPIO.BCM)
GPIO.setup(18, GPIO.IN) # VideoDetect_1
GPIO.setup(23, GPIO.IN) # VideoDetect_2
GPIO.setup(24, GPIO.IN) # VideoDetect_3
GPIO.setup(12, GPIO.IN) # SquelchDetect_1

# internen Pullup-Widerstand aktivieren.
GPIO.setup(18, GPIO.IN, pull_up_down = GPIO.PUD_UP)
GPIO.setup(23, GPIO.IN, pull_up_down = GPIO.PUD_UP)
GPIO.setup(24, GPIO.IN, pull_up_down = GPIO.PUD_UP)
GPIO.setup(12, GPIO.IN, pull_up_down = GPIO.PUD_UP)

# Callback-Funktion fuer beide Flanken
def measure1(channel):
  global start
  global stopp
  global delta
  if GPIO.input(18) == 0:       # fallende Flanke, Startzeit speichern
    start = time.time()
  else:                         # steigende Flanke, Endezeit speichern
    stopp = time.time()
    delta = stopp - start       # Zeitdifferenz berechnen
    print("VideoDetect_1 - GPIO high")
  if GPIO.input(18) == False:
    print("VideoDetect_1 - GPIO low")

def measure2(channel):
  global start
  global stopp
  global delta
  if GPIO.input(23) == 0:
    start = time.time()
  else:                         # steigende Flanke, Endezeit speichern
    stopp = time.time()
    delta = stopp - start       # Zeitdifferenz berechnen
    print("VideoDetect_2 - GPIO high")
  if GPIO.input(23) == False:
    print("VideoDetect_2 - GPIO low")

def measure3(channel):
  global start
  global stopp
  global delta
  if GPIO.input(24) == 0:
    start = time.time()
  else:                         # steigende Flanke, Endezeit speichern
    stopp = time.time()
    delta = stopp - start       # Zeitdifferenz berechnen
    print("VideoDetect_3 - GPIO high")
  if GPIO.input(24) == False:
    print("VideoDetect_3 - GPIO low")

def measure4(channel):
  global start
  global stopp
  global delta
  if GPIO.input(12) == 0 == False:
    start = time.time()
  else:                         # steigende Flanke, Endezeit speichern
    stopp = time.time()
    delta = stopp - start       # Zeitdifferenz berechnen
    print("SquelchDetect_1 - GPIO high")
  if GPIO.input(12) == False:
    print("SquelchDetect_1 - GPIO low")

# Interrupt fuer beide Flanken aktivieren
GPIO.add_event_detect(18, GPIO.BOTH, callback=measure1, bouncetime=200)
GPIO.add_event_detect(23, GPIO.BOTH, callback=measure2, bouncetime=200)
GPIO.add_event_detect(24, GPIO.BOTH, callback=measure3, bouncetime=200)
GPIO.add_event_detect(12, GPIO.BOTH, callback=measure4, bouncetime=200)

try:
  i = 3
  while i < 100:
    # nix Sinnvolles tun
    Tic = Tic + 1
    print "Tic %d" % Tic
    time.sleep(1)

# reset GPIO settings if user pressed Ctrl+C
except KeyboardInterrupt:
  GPIO.cleanup()
  print("\nBye!")

DL9AM
User
Beiträge: 27
Registriert: Mittwoch 29. August 2018, 14:28

Hallo,

so geht es :


Code: Alles auswählen

#!/usr/bin/python
import RPi.GPIO as GPIO
import time
import datetime

# Variablen initialisieren
Tic = 0    # Zaehler
stopp = 0  # Zeitpunkt steigende Flanke
start = 0  # Zeitpunkt fallende Flanke
delta = 0  # Zeitdifferenz zwischen start und stopp

# GPIO initialisieren
GPIO.setmode(GPIO.BCM)
GPIO.setup(18, GPIO.IN) # VideoDetect_1
GPIO.setup(23, GPIO.IN) # VideoDetect_2
GPIO.setup(24, GPIO.IN) # VideoDetect_3
GPIO.setup(12, GPIO.IN) # SquelchDetect_1

# internen Pullup-Widerstand aktivieren.
GPIO.setup(18, GPIO.IN, pull_up_down = GPIO.PUD_UP)
GPIO.setup(23, GPIO.IN, pull_up_down = GPIO.PUD_UP)
GPIO.setup(24, GPIO.IN, pull_up_down = GPIO.PUD_UP)
GPIO.setup(12, GPIO.IN, pull_up_down = GPIO.PUD_DOWN)

# Callback-Funktion fuer beide Flanken
def measure1(channel):
  global start
  global stopp
  global delta
  if GPIO.input(18) == 0:       # fallende Flanke, Startzeit speichern
    start = time.time()
  else:                         # steigende Flanke, Endezeit speichern
    stopp = time.time()
    delta = stopp - start       # Zeitdifferenz berechnen
    print("VideoDetect_1 - GPIO high")
  if GPIO.input(18) ++ GPIO.input(23) ++ GPIO.input(24) ++ GPIO.input(12) == False:
    print("VideoDetect_1 - GPIO low")

def measure2(channel):
  global start
  global stopp
  global delta
  if GPIO.input(23) == 0:
    start = time.time()
  else:                         # steigende Flanke, Endezeit speichern
    stopp = time.time()
    delta = stopp - start       # Zeitdifferenz berechnen
    print("VideoDetect_2 - GPIO high")
  if GPIO.input(18) ++ GPIO.input(23) ++ GPIO.input(24) ++ GPIO.input(12) == False:
    print("VideoDetect_2 - GPIO low")

def measure3(channel):
  global start
  global stopp
  global delta
  if GPIO.input(24) == 0:
    start = time.time()
  else:                         # steigende Flanke, Endezeit speichern
    stopp = time.time()
    delta = stopp - start       # Zeitdifferenz berechnen
    print("VideoDetect_3 - GPIO high")
  if GPIO.input(18) ++ GPIO.input(23) ++ GPIO.input(24) ++ GPIO.input(12) == False:
    print("VideoDetect_3 - GPIO low")

def measure4(channel):
  global start
  global stopp
  global delta
  if GPIO.input(12) == 0 == False:
    start = time.time()
  else:                         # steigende Flanke, Endezeit speichern
    stopp = time.time()
    delta = stopp - start       # Zeitdifferenz berechnen
    print("SquelchDetect_1 - GPIO high")
  if GPIO.input(18) ++ GPIO.input(23) ++ GPIO.input(24) ++ GPIO.input(12) == False:
    print("SquelchDetect_1 - GPIO low")

# Interrupt fuer beide Flanken aktivieren
GPIO.add_event_detect(18, GPIO.BOTH, callback=measure1, bouncetime=200)
GPIO.add_event_detect(23, GPIO.BOTH, callback=measure2, bouncetime=200)
GPIO.add_event_detect(24, GPIO.BOTH, callback=measure3, bouncetime=200)
GPIO.add_event_detect(12, GPIO.BOTH, callback=measure4, bouncetime=200)

try:
  i = 3
  while i < 100:
    # nix Sinnvolles tun
    Tic = Tic + 1
    print "Tic %d" % Tic
    time.sleep(1)

# reset GPIO settings if user pressed Ctrl+C
except KeyboardInterrupt:
  GPIO.cleanup()
  print("\nBye!")

__deets__
User
Beiträge: 14522
Registriert: Mittwoch 14. Oktober 2015, 14:29

Ich weiss nicht genau was jetzt daran "geht" - aber konkret sind doch die ganzen deltas geschweige denn starts und stops voellig sinnfrei, denn sie werden ja gar nicht genutzt. Und WENN sie genutzt werden wuerden, dann wuerde das ganze explodieren, denn start, stopp und delta sind globale Variablen die fuer alle verschiedenen Events benutzt werden. Wenn also measure1 kommt, und start belegt, und dann kommt danach measure2, und belegt start2, dann rechnet das naechste measure1 mit fallender Flanke delta ja nicht korrekt aus.

Aber wenn dein Problem damit geloest ist, dann ist ja gut :)
__deets__
User
Beiträge: 14522
Registriert: Mittwoch 14. Oktober 2015, 14:29

Achso, ++ gibt es in Python nicht. Woher auch immer du das hast. Das ist ein normales +, weil + genauso wie - einfach vorangestellt werden kann. Und was du mit GPIO.input(18) ++ GPIO.input(23) ++ GPIO.input(24) ++ GPIO.input(12) sagst ist im Grunde nur

GPIO.input(18) or GPIO.input(23) orGPIO.input(24) or GPIO.input(12)

oder noch ein bisschen kompakter

any(GPIO.input(pin) for pin in (18, 23, 24, 12))
DL9AM
User
Beiträge: 27
Registriert: Mittwoch 29. August 2018, 14:28

Hallo,

ja das Problem ist, das ich ja leider kein Python kann und auf externe Hilfe angewiesen bin.
Daher habe ich einiges versucht und es läuft aber so ohne meckern von Python.

Schau doch mal etwas tiefer im Skript...
Wenn jetzt GPIO high wird , wird einmalig ein Befehl abgesendet und wenn GPIO inaktiv usw
wieder hin und her geschalten.
Dort wo jetzt die print's stehen wird ein i2c.write-Befehl für eine Relaisplatine gesteuert...

Code: Alles auswählen

# coding: utf-8
# HAMKit VMAC PiHat 2.4 - VideoDetect Video and Audio Matrix with OSD
# Video A/V In 1 and Audio A/V In 4 to Video A/V Out 1 and Audio A/V Out 3
# with OSD
# Video A/V In 1 and Audio A/V In 4 to Video A/V Out 2 and Audio A/V Out 4
# with OSD
# Video A/V In 2 and Audio A/V In 5 to Video A/V Out 1 and Audio A/V Out 3
# with OSD
# Video A/V In 2 and Audio A/V In 5 to Video A/V Out 2 and Audio A/V Out 4
# with OSD
# Video A/V In 3 and Audio A/V In 6 to Video A/V Out 1 and Audio A/V Out 3
# with OSD
# Video A/V In 3 and Audio A/V In 6 to Video A/V Out 2 and Audio A/V Out 4
# with OSD
# No VideoDetect Video Signal Inputs 1, 2 and 3: Video A/V In Pi with Audio
# A/V In Pi to Video A/V Out 1 and Audio A/V Out 3 with OSD
# No VideoDetect Video Signal Inputs 1, 2 and 3: Video A/V In Pi with Audio
# A/V In Pi to Video A/V Out 2 and Audio A/V Out 4 with OSD
# Marco Dittmann DL9AM, August 2018
#!/usr/bin/python

import RPi.GPIO as GPIO
import smbus
import spidev

import threading

import time
import datetime
import os

from ctypes import *

#====== GPIO

GPIO.setmode(GPIO.BCM)
GPIO.setwarnings(False)
GPIO.cleanup()

#Define GPIO Outputs
LEDStatus = 22
PTT = 27
OSD_RST = 25

#Setup Outputs
GPIO.setup(LEDStatus,GPIO.OUT)
GPIO.setup(PTT,GPIO.OUT)
GPIO.setup(OSD_RST,GPIO.OUT)

#Define GPIO Inputs
GPIO_Button = 4
GPIO_VideoDetect_1 = 18
GPIO_VideoDetect_2 = 23
GPIO_VideoDetect_3 = 24
GPIO_SquelchDetect_1 = 12
GPIO_SquelchDetect_2 = 16
GPIO_SquelchDetect_3 = 20
GPIO_SquelchDetect_4 = 21
GPIO_D0 = 26
GPIO_D1 = 19
GPIO_D2 = 13
GPIO_D3 = 6
GPIO_DINT = 5

#Setup Inputs with pull-ups enabled
GPIO.setup(GPIO_Button, GPIO.IN, pull_up_down=GPIO.PUD_UP)
GPIO.setup(GPIO_VideoDetect_1, GPIO.IN, pull_up_down=GPIO.PUD_UP)
GPIO.setup(GPIO_VideoDetect_2, GPIO.IN, pull_up_down=GPIO.PUD_UP)
GPIO.setup(GPIO_VideoDetect_3, GPIO.IN, pull_up_down=GPIO.PUD_UP)
GPIO.setup(GPIO_SquelchDetect_1, GPIO.IN, pull_up_down=GPIO.PUD_DOWN)
GPIO.setup(GPIO_SquelchDetect_2, GPIO.IN, pull_up_down=GPIO.PUD_DOWN)
GPIO.setup(GPIO_SquelchDetect_3, GPIO.IN, pull_up_down=GPIO.PUD_DOWN)
GPIO.setup(GPIO_SquelchDetect_4, GPIO.IN, pull_up_down=GPIO.PUD_DOWN)
GPIO.setup(GPIO_D0, GPIO.IN, pull_up_down=GPIO.PUD_UP)
GPIO.setup(GPIO_D1, GPIO.IN, pull_up_down=GPIO.PUD_UP)
GPIO.setup(GPIO_D2, GPIO.IN, pull_up_down=GPIO.PUD_UP)
GPIO.setup(GPIO_D3, GPIO.IN, pull_up_down=GPIO.PUD_UP)
GPIO.setup(GPIO_DINT, GPIO.IN, pull_up_down=GPIO.PUD_UP)

#Initiate LEDs
GPIO.output(LEDStatus,GPIO.HIGH)
GPIO.output(PTT,GPIO.HIGH)
time.sleep(.2)
GPIO.output(LEDStatus,GPIO.LOW)
GPIO.output(PTT,GPIO.LOW)
time.sleep(1)

#Define Variables
VideoDetect_1 = False
VideoDetect_2 = False
VideoDetect_3 = False
SquelchDetect_1 = False
SquelchDetect_2 = False
SquelchDetect_3 = False
SquelchDetect_4 = False
DValueStore = 0
dateString = '%H %M %S'
stopp = 0
start = 0
delta = 0

#Good old fashion subroutines
def flashleds (flashes):
    for x in range(flashes):
        GPIO.output(LEDStatus,GPIO.HIGH)
        GPIO.output(PTT,GPIO.HIGH)
        time.sleep(.2)
        GPIO.output(LEDStatus,GPIO.LOW)
        GPIO.output(PTT,GPIO.LOW)
        time.sleep(1)

#====== FMS6501 Matrix

#Define Values
DEVICE_BUS = 1            # FMS6501
DEVICE_ADDR = 0x43        # FMS6501 Address 0x43 or 0x03
DEVICE_BUS_RELAIS = 1     # I2C Output Card for HDMI Switch
DEVICE_ADDR_RELAIS = 0x01 # I2C Output Card Address for HDMI Switch

#Setup I2C Bus
i2cbus = smbus.SMBus(DEVICE_BUS)
i2cbus_relais = smbus.SMBus(DEVICE_BUS_RELAIS)

#OSD Reset High
GPIO.output(OSD_RST,GPIO.HIGH)

#Set all outputs to mute.
i2cbus.write_byte_data(DEVICE_ADDR, 0x01, 0x0) #Mute
time.sleep(.01)
i2cbus.write_byte_data(DEVICE_ADDR, 0x03, 0x0) #Mute
time.sleep(.01)
i2cbus.write_byte_data(DEVICE_ADDR, 0x06, 0x0) #Mute
time.sleep(.01)
i2cbus.write_byte_data(DEVICE_ADDR, 0x09, 0x0) #Mute
time.sleep(.01)

#Matrix priority allows switching the last VideoDetect or SquelchDetect over the previous one
class SourceStack(object):

    def __init__(self):
        self._stack = []
        self._lock = threading.Lock()


    def on(self, value):
        with self._lock:
            if value not in self._stack:
                self._stack.append(value)


    def off(self, value):
        with self._lock:
            if value in self._stack:
                self._stack.remove(value)


    @property
    def current(self):
        with self._lock:
            return self._stack[-1] if self._stack else None

ss = SourceStack()

#OSD MAX7456
class max7456():

    # Create a SPI
    spi = spidev.SpiDev()

    # MAX7456 opcodes
    VM0_reg  = 0x00
    VM1_reg  = 0x01
    HOS_reg  = 0x02
    VOS_reg  = 0x03
    DMM_reg  = 0x04
    DMAH     = 0x05
    DMAL     = 0x06
    DMDI     = 0x07
    OSDM     = 0x0C
    RB0      = 0x10
    HOS_reg  = 0x02
    STATUS   = 0xA0

    # PAL - VM0_reg commands
    ENABLE_display      = 0x48
    ENABLE_display_vert = 0x4c
    MAX7456_reset       = 0x42
    DISABLE_display     = 0x40

    # Read command
    READ = 0x80
    MAX_screen_rows = 16

    # White levels
    WHITE_level_80  = 0x03
    WHITE_level_90  = 0x02
    WHITE_level_100 = 0x01
    WHITE_level_120 = 0x00

    chars = {' ':0, '1':1, '2':2, '3':3, '4':4, '5':5, '6':6, '7':7, '8':8, '9':9,
        '0':10, 'A':11, 'B':12, 'C':13, 'D':14, 'E':15, 'F':16, 'G':17, 'H':18, 'I':19,
        'J':20, 'K':21, 'L':22, 'M':23, 'N':24, 'O':25, 'P':26, 'Q':27, 'R':28, 'S':29,
        'T':30, 'U':31, 'V':32, 'W':33, 'X':34, 'Y':35, 'Z':36, 'a':37, 'b':38, 'c':39,
        'd':40, 'e':41, 'f':42, 'g':43, 'h':44, 'i':45, 'j':46, 'k':47, 'l':48, 'm':49,
        'n':50, 'o':51, 'p':52, 'q':53, 'r':54, 's':55, 't':56, 'u':57, 'v':58, 'w':59,
        'x':60, 'y':61, 'z':62, '(':63, ')':64, '.':65, '?':66, ';':67, ':':68, ',':69,
        '´':70, '/':71, '"':72, '-':73, '<':74, '>':75, '@':76

    }

    def __init__(self):
        # Open a SPI port - max7456 connected on SPI0
        self.spi.open(0, 0)
        self.spi.max_speed_hz = 1000000
        self.spi.bits_per_word = 8
        self.spi.cshigh = False
        self.spi.lsbfirst = False
        self.spi.mode = 0

        # On init, reset max7456
        self.reset()

        # Set all rows at the same white level
        for x in range (0, self.MAX_screen_rows):
          self.spi.xfer2([(self.RB0 + x), self.WHITE_level_90])

        # Enable max7456
        self.spi.xfer2([self.VM0_reg, self.ENABLE_display]);

    def printStr(self, X, Y, string, enable = True):
        disp = []
        for char in string:
                 disp.append(self.chars[char])

        print (string)

        if enable == False:
            self.spi.xfer([self.VM0_reg, self.Disable_display])

        # Enable 8 bit mode:
        dmm = self.spi.xfer2([self.DMM_reg + self.READ, 0x00])
        dmm = self.setBit(dmm[1], 6)
        self.spi.xfer2([self.DMM_reg, dmm])

        start = X * 30 + Y

        # Clear position
        self.spi.xfer2([self.DMAH, 0x00])
        self.spi.xfer2([self.DMAL, 0x00])

        for char in disp:
            # Write char
            dmah = self.spi.xfer2([self.DMAH + self.READ, 0x00])
            dmah = self.clearBit(dmah[1], 1)
            self.spi.xfer2([self.DMAH, dmah])

            dmah_pos = ((start >> 8) & 0x01)
            dmal = (start & 0xff)
            dmah = dmah | dmah_pos
            start = start + 1

            # Select MSB
            self.spi.xfer2([self.DMAH, dmah])
            self.spi.xfer2([self.DMAL, dmal])

            self.spi.xfer2([self.DMDI, (char)])

    def reset(self):
        self.spi.xfer2([self.VM0_reg, self.MAX7456_reset])
        time.sleep(.1)
        while True:
            r = self.spi.xfer([self.STATUS, 0x00])
            stable = self.testBit(r[1], 1)
            if stable == 0:
                print ("Reset MAX7456 Ok...")
                break
            break

    def testBit(self, value, offset):
        mask = 1 << value
        return(value & mask)

    def setBit(self, value, offset):
        mask = 1 << offset
        return(value + mask)

    def clearBit(self, int_type, offset):
        mask = ~(1 << offset)
        return(int_type & mask)

try:
    max7456 = max7456()

except KeyboardInterrupt:
    spi.close()

print ("VideoDetect_1, VideoDetect_2, VideoDetect_3, Squelch_Detect_1 running...")

#Check GPIO VideoDetect and SquelchDetect for high or low for Output Card for HDMI Switch
def measure1(channel):
  global start
  global stopp
  global delta
  if GPIO.input(GPIO_VideoDetect_1) == 0:
    start = time.time()
  else:
    stopp = time.time()
    delta = stopp - start
    print ("Switch to HDMI Port 2 CVBS")
    time.sleep(1)
    print ("Done")
  if GPIO.input(GPIO_VideoDetect_1) ++ GPIO.input(GPIO_VideoDetect_2) ++ GPIO.input(GPIO_VideoDetect_3) ++ GPIO.input(GPIO_SquelchDetect_1) == False:
    print ("Switch to HDMI Port 1 Camera")
    time.sleep(1)
    print ("Done")
  elif GPIO.input(GPIO_VideoDetect_1) ++ GPIO.input(GPIO_VideoDetect_2) ++ GPIO.input(GPIO_VideoDetect_3) == False and GPIO.input(GPIO_SquelchDetect_1) == True:
    print ("Switch to HDMI Port 3 DVB-T")
    time.sleep(1)
    print ("Done")
  elif GPIO.input(GPIO_SquelchDetect_1) == True and (GPIO_VideoDetect_1) == True:
    print ("Switch to HDMI Port 2 CVBS")
    time.sleep(1)
    print ("Done")

def measure2(channel):
  global start
  global stopp
  global delta
  if GPIO.input(GPIO_VideoDetect_2) == 0:
    start = time.time()
  else:
    stopp = time.time()
    delta = stopp - start
    print ("Switch to HDMI Port 2 CVBS")
    time.sleep(1)
    print ("Done")
  if GPIO.input(GPIO_VideoDetect_1) ++ GPIO.input(GPIO_VideoDetect_2) ++ GPIO.input(GPIO_VideoDetect_3) ++ GPIO.input(GPIO_SquelchDetect_1) == False:
    print ("Switch to HDMI Port 1 Camera")
    time.sleep(1)
    print ("Done")
  elif GPIO.input(GPIO_VideoDetect_1) ++ GPIO.input(GPIO_VideoDetect_2) ++ GPIO.input(GPIO_VideoDetect_3) == False and GPIO.input(GPIO_SquelchDetect_1) == True:
    print ("Switch to HDMI Port 3 DVB-T")
    time.sleep(1)
    print ("Done")
  elif GPIO.input(GPIO_SquelchDetect_1) == True and (GPIO_VideoDetect_2) == True:
    print ("Switch to HDMI Port 2 CVBS")
    time.sleep(1)
    print ("Done")

def measure3(channel):
  global start
  global stopp
  global delta
  if GPIO.input(GPIO_VideoDetect_3) == 0:
    start = time.time()
  else:
    stopp = time.time()
    delta = stopp - start
    print ("Switch to HDMI Port 2 CVBS")
    time.sleep(1)
    print ("Done")
  if GPIO.input(GPIO_VideoDetect_1) ++ GPIO.input(GPIO_VideoDetect_2) ++ GPIO.input(GPIO_VideoDetect_3) ++ GPIO.input(GPIO_SquelchDetect_1) == False:
    print ("Switch to HDMI Port 1 Camera")
    time.sleep(1)
    print ("Done")
  elif GPIO.input(GPIO_VideoDetect_1) ++ GPIO.input(GPIO_VideoDetect_2) ++ GPIO.input(GPIO_VideoDetect_3) == False and GPIO.input(GPIO_SquelchDetect_1) == True:
    print ("Switch to HDMI Port 3 DVB-T")
    time.sleep(1)
    print ("Done")
  elif GPIO.input(GPIO_SquelchDetect_1) == True and (GPIO_VideoDetect_3) == True:
    print ("Switch to HDMI Port 2 CVBS")
    time.sleep(1)
    print ("Done")

def measure4(channel):
  global start
  global stopp
  global delta
  if GPIO.input(GPIO_SquelchDetect_1) == 0:
    start = time.time()
  else:
    stopp = time.time()
    delta = stopp - start
    print ("Switch to HDMI Port 3 DVB-T")
    time.sleep(1)
    print ("Done")
  if GPIO.input(GPIO_VideoDetect_1) ++ GPIO.input(GPIO_VideoDetect_2) ++ GPIO.input(GPIO_VideoDetect_3) ++ GPIO.input(GPIO_SquelchDetect_1) == False:
    print ("Switch to HDMI Port 1 Camera")
    time.sleep(1)
    print ("Done")
  elif GPIO.input(GPIO_SquelchDetect_1) == False and GPIO.input(GPIO_VideoDetect_1) == True:
    print ("Switch to HDMI Port 2 CVBS")
    time.sleep(1)
    print ("Done")
  elif GPIO.input(GPIO_SquelchDetect_1) == False and GPIO.input(GPIO_VideoDetect_2) == True:
    print ("Switch to HDMI Port 2 CVBS")
    time.sleep(1)
    print ("Done")
  elif GPIO.input(GPIO_SquelchDetect_1) == False and GPIO.input(GPIO_VideoDetect_3) == True:
    print ("Switch to HDMI Port 2 CVBS")
    time.sleep(1)
    print ("Done")

GPIO.add_event_detect(18, GPIO.BOTH, callback=measure1, bouncetime=200)
GPIO.add_event_detect(23, GPIO.BOTH, callback=measure2, bouncetime=200)
GPIO.add_event_detect(24, GPIO.BOTH, callback=measure3, bouncetime=200)
GPIO.add_event_detect(12, GPIO.BOTH, callback=measure4, bouncetime=200)

#Loop
while True:

    VideoDetect_1 = GPIO.input(GPIO_VideoDetect_1)
    VideoDetect_2 = GPIO.input(GPIO_VideoDetect_2)
    VideoDetect_3 = GPIO.input(GPIO_VideoDetect_3)
    SquelchDetect_1 = GPIO.input(GPIO_SquelchDetect_1)
    SquelchDetect_2 = GPIO.input(GPIO_SquelchDetect_2)
    SquelchDetect_3 = GPIO.input(GPIO_SquelchDetect_3)
    SquelchDetect_4 = GPIO.input(GPIO_SquelchDetect_4)


    Button = GPIO.input(GPIO_Button)
    if Button == False:
        max7456.printStr(1,1, "HAMKit VMAC PiHat", enable = True)
        max7456.printStr(2,1, "Reboot by Sysop", enable = True)
        flashleds (10)
        os.system("sudo reboot")

    DINT = GPIO.input(GPIO_DINT)
    if DINT == True:
        D0 = GPIO.input(GPIO_D0)
        D1 = GPIO.input(GPIO_D1)
        D2 = GPIO.input(GPIO_D2)
        D3 = GPIO.input(GPIO_D3)
        DValue = D0+(D1*2)+(D2*4)+(D3*8)
        if DValue == 1:
            max7456.printStr(1,1, "CQ de 10.420GHz", enable = True)
            time.sleep(10)
            max7456.printStr(1,1, "               ", enable = True)
        elif DValue == 2:
              max7456.printStr(1,1, "CQ de 1.251GHz ", enable = True)
              time.sleep(10)
              max7456.printStr(1,1, "               ", enable = True)
        elif DValue == 3:
              max7456.printStr(1,1, "CQ de Test     ", enable = True)
              time.sleep(10)
              max7456.printStr(1,1, "               ", enable = True)

    if VideoDetect_1 == True:
       ss.on("VD_1")
    else:
         ss.off("VD_1")
    if VideoDetect_2 == True:
       ss.on("VD_2")
    else:
         ss.off("VD_2")
    if VideoDetect_3 == True:
       ss.on("VD_3")
    else:
         ss.off("VD_3")
    if SquelchDetect_1 == True:
       ss.on("SD_1")
    else:
         ss.off("SD_1")

    if ss.current == "VD_1":
#    if VideoDetect_1 == True:
        print ("VideoDetect_1")
        i2cbus.write_byte_data(DEVICE_ADDR, 0x01, 0x81) #Input 1 to Output 1
        i2cbus.write_byte_data(DEVICE_ADDR, 0x03, 0x81) #Input 1 to Output 2
        i2cbus.write_byte_data(DEVICE_ADDR, 0x06, 0x87) #Input 4 to Output 3
        i2cbus.write_byte_data(DEVICE_ADDR, 0x09, 0x87) #Input 4 to Output 4
        i2cbus.write_byte_data(DEVICE_ADDR, 0x07, 0x81) #Input 1 to OSD In
        i2cbus.write_byte_data(DEVICE_ADDR, 0x01, 0x86) #Input OSD to Output 1
        i2cbus.write_byte_data(DEVICE_ADDR, 0x03, 0x86) #Input OSD to Output 2
        max7456.printStr(14,1, "CQ 10.420GHz           ", enable = True)
        flashleds (1)

    elif ss.current == "VD_2":
#    elif VideoDetect_2 == True:
        print ("VideoDetect_2")
        i2cbus.write_byte_data(DEVICE_ADDR, 0x01, 0x83) #Input 2 to Output 1
        i2cbus.write_byte_data(DEVICE_ADDR, 0x03, 0x83) #Input 2 to Output 2
        i2cbus.write_byte_data(DEVICE_ADDR, 0x06, 0x88) #Input 5 to Output 3
        i2cbus.write_byte_data(DEVICE_ADDR, 0x09, 0x88) #Input 5 to Output 4
        i2cbus.write_byte_data(DEVICE_ADDR, 0x07, 0x83) #Input 2 to OSD In
        i2cbus.write_byte_data(DEVICE_ADDR, 0x01, 0x86) #Input OSD to Output 1
        i2cbus.write_byte_data(DEVICE_ADDR, 0x03, 0x86) #Input OSD to Output 2
        max7456.printStr(14,1, "CQ 1.251GHz            ", enable = True)
        flashleds (2)

    elif ss.current == "VD_3":
#    elif VideoDetect_3 == True:
        print ("VideoDetect_3")
        i2cbus.write_byte_data(DEVICE_ADDR, 0x01, 0x85) #Input 3 to Output 1
        i2cbus.write_byte_data(DEVICE_ADDR, 0x03, 0x85) #Input 3 to Output 2
        i2cbus.write_byte_data(DEVICE_ADDR, 0x06, 0x89) #Input 6 to Output 3
        i2cbus.write_byte_data(DEVICE_ADDR, 0x09, 0x89) #Input 6 to Output 4
        i2cbus.write_byte_data(DEVICE_ADDR, 0x07, 0x85) #Input 3 to OSD In
        i2cbus.write_byte_data(DEVICE_ADDR, 0x01, 0x86) #Input OSD to Output 1
        i2cbus.write_byte_data(DEVICE_ADDR, 0x03, 0x86) #Input OSD to Output 2
        max7456.printStr(14,1, "Test                   ", enable = True)
        flashleds (3)

    elif ss.current == "SD_1":
#    elif SquelchDetect_1 == False:
        print ("SquelchDetect_1")
        print ("CQ 436MHz")
        i2cbus.write_byte_data(DEVICE_ADDR, 0x01, 0x8c) #Input Pi-V to Output 1
        i2cbus.write_byte_data(DEVICE_ADDR, 0x03, 0x8c) #Input Pi-V to Output 2
        i2cbus.write_byte_data(DEVICE_ADDR, 0x06, 0x8b) #Input Pi-A to Output 3
        i2cbus.write_byte_data(DEVICE_ADDR, 0x09, 0x8b) #Input Pi-A to Output 4
        i2cbus.write_byte_data(DEVICE_ADDR, 0x07, 0x8c) #Input Pi-V to OSD In
        i2cbus.write_byte_data(DEVICE_ADDR, 0x01, 0x86) #Input OSD to Output 1
        i2cbus.write_byte_data(DEVICE_ADDR, 0x03, 0x86) #Input OSD to Output 2
        max7456.printStr(14,1, datetime.datetime.now().strftime(dateString), enable = True)
        max7456.printStr(14,9, ", Pi Temp     C", enable = True)
        file = open("/home/pi/1.txt","r")
        max7456.printStr(14,19, file.readline().rstrip('\n'), enable = True)
        file.close()
        flashleds (4)

    else:
        print ("Pi")
        i2cbus.write_byte_data(DEVICE_ADDR, 0x01, 0x8c) #Input Pi-V to Output 1
        i2cbus.write_byte_data(DEVICE_ADDR, 0x03, 0x8c) #Input Pi-V to Output 2
        i2cbus.write_byte_data(DEVICE_ADDR, 0x06, 0x8b) #Input Pi-A to Output 3
        i2cbus.write_byte_data(DEVICE_ADDR, 0x09, 0x8b) #Input Pi-A to Output 4
        i2cbus.write_byte_data(DEVICE_ADDR, 0x07, 0x8c) #Input Pi-V to OSD In
        i2cbus.write_byte_data(DEVICE_ADDR, 0x01, 0x86) #Input OSD to Output 1
        i2cbus.write_byte_data(DEVICE_ADDR, 0x03, 0x86) #Input OSD to Output 2
        max7456.printStr(14,1, datetime.datetime.now().strftime(dateString), enable = True)
        max7456.printStr(14,9, ", Pi Temp     C", enable = True)
        file = open("/home/pi/1.txt","r")
        max7456.printStr(14,19, file.readline().rstrip('\n'), enable = True)
        file.close()
        flashleds (0)

    #Heatbeat PTT LED as test
    GPIO.output(PTT,GPIO.HIGH)
    time.sleep(.2)
    GPIO.output(PTT,GPIO.LOW)
    time.sleep(1)

Benutzeravatar
__blackjack__
User
Beiträge: 13069
Registriert: Samstag 2. Juni 2018, 10:21
Wohnort: 127.0.0.1
Kontaktdaten:

@DL9AM: „[E]s läuft aber so ohne meckern von Python“ muss nichts bedeuten. Nur weil etwas am Compiler vorbei kommt, und bei ein paar Testläufen zu funktionieren scheint, heisst ja nicht das es tatsächlich richtig ist und grundsätzlich funktioniert.
„All religions are the same: religion is basically guilt, with different holidays.” — Cathy Ladman
__deets__
User
Beiträge: 14522
Registriert: Mittwoch 14. Oktober 2015, 14:29

Das tut nicht was du willst. In einer Ereignis-Behandlung sleeps einzufügen ist der Tot. Du denkst vielleicht, dass die parallel abgearbeitet werden. Ist aber so nicht. Zwar läuft ein Thread für alle Ereignisse, und einer in der hauptschleife. Und damit sieht das im einzelnen Fall gut aus. Aber in dem Moment, wo eine deiner sleeps in der Ereignisbehanglung steht, kommt kein anderes Ereignis zum Zug.
DL9AM
User
Beiträge: 27
Registriert: Mittwoch 29. August 2018, 14:28

Hallo,

die "++" sollten bewirken, das VideoDetect_1 und VideoDetect_2 und VideoDetect_3 und Squelch_Detect "false" sind erst
auf HDMI 1 umgeschaltet wird.

Ich habe es auf eueren Rat mal umgebaut auf "and" ... "and", das ging aber nicht...

Habe es dann anstelle der "++" mit "==" probiert, das sah ok aus.
Aber warum es mit dem "++" auch klappte ohne Fehlermeldung ??? Laut euch und Foren stimmt es schon, es gibt unter
Python kein "++" wie im C++... nur ein einfaches "+" wenn überhaupt...

So wie ich es jetzt gebastelt habe wird ein Befehl sobald VideoDetect_1 oder anders erkannt ist ausgeführt, welcher eigentlich
ein "i2c"-Befehl um ein Relais zum Tasten des HDMI-Schalter, dann Pause 1 Sekunde und dann wieder Relais los lassen...
Deshalb die Pause.

Es sollte eigentlich in den nächsten paar Sekunden keine andere VideoDetect erfolgen, da die Matrix im Amateurfunk für ein
Television Relais dient und dort ein Wechselgespräch statt findet und kein VideoDetect_1 und VideoDetect_2 usw im schnellen
wechsel...

Aber wie könnte es ordentlicher aussehen ???

glg Marco
__deets__
User
Beiträge: 14522
Registriert: Mittwoch 14. Oktober 2015, 14:29

Mein Rat war nicht and. Mein Rat war "or". Und == ist ganz bestimmt nicht richtig, da es da *zwei* Bedingungen gibt, die wahr sind. Und warum ++ klappt hab' ich ja auch schon erwaehnt.
DL9AM
User
Beiträge: 27
Registriert: Mittwoch 29. August 2018, 14:28

Hallo,

sorry dann habe ich es durcheinander gebracht ;-(
Dann versuche ich es mal mit "or".

Wie sieht es mit der anderen Sache aus, gibt es da etwas ordentlicheres ?
Ich habe das Bsp von der Seite http://www.netzmafia.de/skripten/hardwa ... O_int.html

unten genommen:

"Die dritte Möglichkeit bei der Interrupt-Verarbeitung ermöglicht es, auf beide Flanken zu reagieren. Mit dem Befehl GPIO.add_event_detect(17, GPIO.BOTH, callback=measure) wird die Funktion measure() als Interrupt-Serviceroutine für steigende und fallende Flanke (GPIO.BOTH) eingetragen. Innerhalb der Funktion measure() wird dann der Port abgefragt. Hat er den Wert "1", war eine steigende Flanke Auslöser und die globale Variable start speichert die aktuelle Zeit. Im anderen Fall war die fallende Flanke der Auslöser und es wird die aktuelle Zeit in stopp gespeichert. Danach wird die Zeitdifferenz berechnet und ausgegeben. Der Taster hat wieder den Pullup-Widerstand aktiviert und schließt gegen GND-Pegel. Alles andere ist wie gehabt."

Code: Alles auswählen

#!/usr/bin/python
import RPi.GPIO as GPIO
import time
import datetime

# Variablen initialisieren
Tic = 0    # Zaehler
stopp = 0  # Zeitpunkt steigende Flanke 
start = 0  # Zeitpunkt fallende Flanke
delta = 0  # Zeitdifferenz zwischen start und stopp

# GPIO initialisieren
GPIO.setmode(GPIO.BCM)
GPIO.setup(17, GPIO.IN) # Pin 11

# internen Pullup-Widerstand aktivieren.
GPIO.setup(17, GPIO.IN, pull_up_down = GPIO.PUD_UP)

# Callback-Funktion fuer beide Flanken
def measure(channel):
  global start
  global stopp
  global delta
  if GPIO.input(17) == 0:       # fallende Flanke, Startzeit speichern
    start = time.time()
  else:                         # steigende Flanke, Endezeit speichern
    stopp = time.time()
    delta = stopp - start       # Zeitdifferenz berechnen
    print("delta = %1.2f" % delta)

# Interrupt fuer beide Flanken aktivieren
GPIO.add_event_detect(17, GPIO.BOTH, callback=measure, bouncetime=200)

try:
  while True:
    # nix Sinnvolles tun
    Tic = Tic + 1
    print "Tic %d" % Tic
    time.sleep(1)

# reset GPIO settings if user pressed Ctrl+C
except KeyboardInterrupt:
  GPIO.cleanup()
  print("\nBye!")
Benutzeravatar
__blackjack__
User
Beiträge: 13069
Registriert: Samstag 2. Juni 2018, 10:21
Wohnort: 127.0.0.1
Kontaktdaten:

@DL9AM: Noch mal zu dem + als unäres Vorzeichen:

Code: Alles auswählen

In [12]: 1 ++ 2 == 1 + +2 == 1 ++2
Out[12]: True
In [13]: ++++++++++++42
Out[13]: 42
„All religions are the same: religion is basically guilt, with different holidays.” — Cathy Ladman
__deets__
User
Beiträge: 14522
Registriert: Mittwoch 14. Oktober 2015, 14:29

Der Code von Netzmafia ist wegen der globals Mist. Aber selbst wenn wir das mal kurz beiseite lassen: das Beispiel von NM funktioniert. Was NICHT funktioniert ist, wie du es dann fuer deinen Fall umgebaut hast. Denn da du die jeweiligen Start-Zeiten der verschiedenen Flanken alle mit dem gleichen Zustand erfasst. Du kannst auch nicht die Zeiten von 3 100-Meter-Laeufern mit der gleichen Stopuhr nehmen. Da musst du schon drei fuer nehmen.
DL9AM
User
Beiträge: 27
Registriert: Mittwoch 29. August 2018, 14:28

Heisst es, das ich aus den stop, start und delta z.B.

stop1
start1
delta1

stop2
start2
delta2

stop3
start3
delta3

machen muss und natürlich unter den "def" auch entsprechend aus stop, start und delta -> stop1,start1,delta1 unter measure1 bzw.
start2, stop2 und delta2 unter measure2 usw...

lg
__deets__
User
Beiträge: 14522
Registriert: Mittwoch 14. Oktober 2015, 14:29

Das ist eine Loesung, ja. Besser waere das Verhalten in eine Klasse zu kapseln, um die nervige Wiederholung von Code zu reduzieren.

Code: Alles auswählen

class LowFlankMeasurer:

    def __init__(self, pin):
        GPIO.add_event_detect(
            pin,
            GPIO.BOTH,
            callback=self._measure,
            bouncetime=200,
        )
        self._start = None
        self.length = None


    def _measure(self, pin):
        level = GPIO.input(pin)
        now = time.time()
        if level and self._start is not None:
            self.length = now - self._start
        else:
            self._start = now
            self.length = None


channel_one_measurer = LowFlankMeasurer(DIE_PIN_NUMMER)

# hauptschleife
while True:
    if channel_one_measurer.length is not None:
        # tu was
    else:
        # tu was anderes
        
DL9AM
User
Beiträge: 27
Registriert: Mittwoch 29. August 2018, 14:28

Hallo,

das würde aber bedeuten das die Abfrage nur alle x Zeilen im while getätigt wird?

LG Marco
__deets__
User
Beiträge: 14522
Registriert: Mittwoch 14. Oktober 2015, 14:29

Da die while-Schleife der einzige Ort ist, an dem die Zeit mehr oder minder kontinuierlich verfliesst, ist das der Ort, wo man Dinge die abhaengigk von der Zeit passieren sollen eben machen muss. Dein Ansatz, time.sleep in measurement-Funktionen zu packen funktioniert NICHT, denn damit legst du den gesamten Mechanismus zur Ereigniserkennung lahm. Fuer alle anderen Ereignisse.
DL9AM
User
Beiträge: 27
Registriert: Mittwoch 29. August 2018, 14:28

Hallo,

angenommen, zwei i2c Befehle würden bei meiner bisherigen Sache ohne "time.sleep" hinter einander ausreichen vom Relaisschalten um den HDMI
Schalter zu betätigen, wäre es dann ok?

Ich probiere natürlich gern Deine "def" aus, nur muss ich es damit hinbekommen, das VideoDetect1....3 und SquelchDetect_1 überwacht wird...
so wie es jetzt zzt läuft....
also auch wenn eine Erkennung weg fällt z.B. VideoDetect_1, aber noch VideoDetect_2 aktiv der Befehl aktiv bleibt und nicht wieder i2c schaltet...

glg Marco
DL9AM
User
Beiträge: 27
Registriert: Mittwoch 29. August 2018, 14:28

Hallo,

hier jetzt mal mein Skript. Er funktioniert. Auch die kleine Pause von .2 stört mich nicht in den Ereignissen.

Dennoch gravierende Fehler drin zu entdecken ?
Das "or" ging nicht, da er dann auf oder oder schaute , aber ein "+" geht genauso wie das falsche "++".

Code: Alles auswählen

# coding: utf-8
#
# HAMKit VMAC PiHat 2.4 - VideoDetect Video and Audio Matrix with OSD German-utf                                                                                   8
# Prioritization: The last one comes is switched and vice versa
#
# Video A/V In 1 and Audio A/V In 4 to Video A/V Out 1 and Audio A/V Out 3
# with OSD
# Video A/V In 1 and Audio A/V In 4 to Video A/V Out 2 and Audio A/V Out 4
# with OSD
# Video A/V In 2 and Audio A/V In 5 to Video A/V Out 1 and Audio A/V Out 3
# with OSD
# Video A/V In 2 and Audio A/V In 5 to Video A/V Out 2 and Audio A/V Out 4
# with OSD
# Video A/V In 3 and Audio A/V In 6 to Video A/V Out 1 and Audio A/V Out 3
# with OSD
# Video A/V In 3 and Audio A/V In 6 to Video A/V Out 2 and Audio A/V Out 4
# with OSD
# No VideoDetect Video Signal Inputs 1, 2 and 3: Video A/V In Pi with Audio
# A/V In Pi to Video A/V Out 1 and Audio A/V Out 3 with OSD
# No VideoDetect Video Signal Inputs 1, 2 and 3: Video A/V In Pi with Audio
# A/V In Pi to Video A/V Out 2 and Audio A/V Out 4 with OSD
#
# With an optional I2C controlled output card to control in parallel to
# VideoDetect_1, VideoDetect_2, VideoDetect_3 or SquelchDetect_1 relay
# for example to operate an HDMI switch
# https://www.horter-shop.de/de/i2c-ausgabekarten-do/136-bausatz-i2c-ausgabekart                                                                                   e-8-bit-ohne-endstufen-4260404260592.html#/27-pcf_typ-pcf_8574_adresse_64_78/35-                                                                                   logik-invers
#
# DTMF code for OSD CQ overlay
# 1: CQ de VideoDetect_1, 2: CQ de VideoDetect_2, 3: CQ de VideoDetect_3
# 4: CQ de SquelchDetect_1
#
# Button on the board for pi restart
#
# Marco Dittmann DL9AM, September 2018
#
#!/usr/bin/python

import RPi.GPIO as GPIO
import smbus
import spidev

import threading

import time
import datetime
import os

from ctypes import *

#====== GPIO

GPIO.setmode(GPIO.BCM)
GPIO.setwarnings(False)
GPIO.cleanup()

#Define GPIO Outputs
LEDStatus = 22
PTT = 27
OSD_RST = 25

#Setup Outputs
GPIO.setup(LEDStatus,GPIO.OUT)
GPIO.setup(PTT,GPIO.OUT)
GPIO.setup(OSD_RST,GPIO.OUT)

#Define GPIO Inputs
GPIO_Button = 4
GPIO_VideoDetect_1 = 18
GPIO_VideoDetect_2 = 23
GPIO_VideoDetect_3 = 24
GPIO_SquelchDetect_1 = 12
GPIO_SquelchDetect_2 = 16
GPIO_SquelchDetect_3 = 20
GPIO_SquelchDetect_4 = 21
GPIO_D0 = 26
GPIO_D1 = 19
GPIO_D2 = 13
GPIO_D3 = 6
GPIO_DINT = 5

#Setup Inputs with pull-ups enabled
GPIO.setup(GPIO_Button, GPIO.IN, pull_up_down=GPIO.PUD_UP)
GPIO.setup(GPIO_VideoDetect_1, GPIO.IN, pull_up_down=GPIO.PUD_UP)
GPIO.setup(GPIO_VideoDetect_2, GPIO.IN, pull_up_down=GPIO.PUD_UP)
GPIO.setup(GPIO_VideoDetect_3, GPIO.IN, pull_up_down=GPIO.PUD_UP)
GPIO.setup(GPIO_SquelchDetect_1, GPIO.IN, pull_up_down=GPIO.PUD_DOWN)
GPIO.setup(GPIO_SquelchDetect_2, GPIO.IN, pull_up_down=GPIO.PUD_DOWN)
GPIO.setup(GPIO_SquelchDetect_3, GPIO.IN, pull_up_down=GPIO.PUD_DOWN)
GPIO.setup(GPIO_SquelchDetect_4, GPIO.IN, pull_up_down=GPIO.PUD_DOWN)
GPIO.setup(GPIO_D0, GPIO.IN, pull_up_down=GPIO.PUD_UP)
GPIO.setup(GPIO_D1, GPIO.IN, pull_up_down=GPIO.PUD_UP)
GPIO.setup(GPIO_D2, GPIO.IN, pull_up_down=GPIO.PUD_UP)
GPIO.setup(GPIO_D3, GPIO.IN, pull_up_down=GPIO.PUD_UP)
GPIO.setup(GPIO_DINT, GPIO.IN, pull_up_down=GPIO.PUD_UP)

#Initiate LEDs
GPIO.output(LEDStatus,GPIO.HIGH)
GPIO.output(PTT,GPIO.HIGH)
time.sleep(.2)
GPIO.output(LEDStatus,GPIO.LOW)
GPIO.output(PTT,GPIO.LOW)
time.sleep(1)

#Define Variables
VideoDetect_1 = False
VideoDetect_2 = False
VideoDetect_3 = False
SquelchDetect_1 = False
SquelchDetect_2 = False
SquelchDetect_3 = False
SquelchDetect_4 = False
DValueStore = 0
dateString = '%H %M %S'
stopp1 = 0
stopp2 = 0
stopp3 = 0
stopp4 = 0
start1 = 0
start2 = 0
start3 = 0
start4 = 0
delta1 = 0
delta2 = 0
delta3 = 0
delta4 = 0
o1 = 0

#Good old fashion subroutines
def flashleds (flashes):
    for x in range(flashes):
        GPIO.output(LEDStatus,GPIO.HIGH)
        GPIO.output(PTT,GPIO.HIGH)
        time.sleep(.2)
        GPIO.output(LEDStatus,GPIO.LOW)
        GPIO.output(PTT,GPIO.LOW)
        time.sleep(1)

#====== FMS6501 Matrix

#Define Values
DEVICE_BUS = 1            # FMS6501
DEVICE_ADDR = 0x43        # FMS6501 Address 0x43 or 0x03
DEVICE_BUS_RELAIS = 1     # I2C Output Card for HDMI Switch
DEVICE_ADDR_RELAIS = 0x20 # I2C Output Card Address for HDMI Switch 0x20

#Setup I2C Bus
i2cbus = smbus.SMBus(DEVICE_BUS)
i2cbus_relais = smbus.SMBus(DEVICE_BUS_RELAIS)

#OSD Reset High
GPIO.output(OSD_RST,GPIO.HIGH)

#Set all outputs to mute.
i2cbus.write_byte_data(DEVICE_ADDR, 0x01, 0x0) #Mute
time.sleep(.01)
i2cbus.write_byte_data(DEVICE_ADDR, 0x03, 0x0) #Mute
time.sleep(.01)
i2cbus.write_byte_data(DEVICE_ADDR, 0x06, 0x0) #Mute
time.sleep(.01)
i2cbus.write_byte_data(DEVICE_ADDR, 0x09, 0x0) #Mute
time.sleep(.01)

#Matrix priority allows switching the last VideoDetect or SquelchDetect over the                                                                                    previous one
class SourceStack(object):

    def __init__(self):
        self._stack = []
        self._lock = threading.Lock()


    def on(self, value):
        with self._lock:
            if value not in self._stack:
                self._stack.append(value)


    def off(self, value):
        with self._lock:
            if value in self._stack:
                self._stack.remove(value)


    @property
    def current(self):
        with self._lock:
            return self._stack[-1] if self._stack else None

ss = SourceStack()

#OSD MAX7456
class max7456():

    # Create a SPI
    spi = spidev.SpiDev()

    # MAX7456 opcodes
    VM0_reg  = 0x00
    VM1_reg  = 0x01
    HOS_reg  = 0x02
    VOS_reg  = 0x03
    DMM_reg  = 0x04
    DMAH     = 0x05
    DMAL     = 0x06
    DMDI     = 0x07
    OSDM     = 0x0C
    RB0      = 0x10
    HOS_reg  = 0x02
    STATUS   = 0xA0

    # PAL - VM0_reg commands
    ENABLE_display      = 0x48
    ENABLE_display_vert = 0x4c
    MAX7456_reset       = 0x42
    DISABLE_display     = 0x40

    # Read command
    READ = 0x80
    MAX_screen_rows = 16

    # White levels
    WHITE_level_80  = 0x03
    WHITE_level_90  = 0x02
    WHITE_level_100 = 0x01
    WHITE_level_120 = 0x00

    chars = {' ':0, '1':1, '2':2, '3':3, '4':4, '5':5, '6':6, '7':7, '8':8, '9':                                                                                   9,
        '0':10, 'A':11, 'B':12, 'C':13, 'D':14, 'E':15, 'F':16, 'G':17, 'H':18,                                                                                    'I':19,
        'J':20, 'K':21, 'L':22, 'M':23, 'N':24, 'O':25, 'P':26, 'Q':27, 'R':28,                                                                                    'S':29,
        'T':30, 'U':31, 'V':32, 'W':33, 'X':34, 'Y':35, 'Z':36, 'a':37, 'b':38,                                                                                    'c':39,
        'd':40, 'e':41, 'f':42, 'g':43, 'h':44, 'i':45, 'j':46, 'k':47, 'l':48,                                                                                    'm':49,
        'n':50, 'o':51, 'p':52, 'q':53, 'r':54, 's':55, 't':56, 'u':57, 'v':58,                                                                                    'w':59,
        'x':60, 'y':61, 'z':62, '(':63, ')':64, '.':65, '?':66, ';':67, ':':68,                                                                                    ',':69,
        '´':70, '/':71, '"':72, '-':73, '<':74, '>':75, '@':76

    }

    def __init__(self):
        # Open a SPI port - max7456 connected on SPI0
        self.spi.open(0, 0)
        self.spi.max_speed_hz = 1000000
        self.spi.bits_per_word = 8
        self.spi.cshigh = False
        self.spi.lsbfirst = False
        self.spi.mode = 0

        # On init, reset max7456
        self.reset()

        # Set all rows at the same white level
        for x in range (0, self.MAX_screen_rows):
          self.spi.xfer2([(self.RB0 + x), self.WHITE_level_90])

        # Enable max7456
        self.spi.xfer2([self.VM0_reg, self.ENABLE_display]);

    def printStr(self, X, Y, string, enable = True):
        disp = []
        for char in string:
                 disp.append(self.chars[char])

        print (string)

        if enable == False:
            self.spi.xfer([self.VM0_reg, self.Disable_display])

        # Enable 8 bit mode:
        dmm = self.spi.xfer2([self.DMM_reg + self.READ, 0x00])
        dmm = self.setBit(dmm[1], 6)
        self.spi.xfer2([self.DMM_reg, dmm])

        start = X * 30 + Y

        # Clear position
        self.spi.xfer2([self.DMAH, 0x00])
        self.spi.xfer2([self.DMAL, 0x00])

        for char in disp:
            # Write char
            dmah = self.spi.xfer2([self.DMAH + self.READ, 0x00])
            dmah = self.clearBit(dmah[1], 1)
            self.spi.xfer2([self.DMAH, dmah])

            dmah_pos = ((start >> 8) & 0x01)
            dmal = (start & 0xff)
            dmah = dmah | dmah_pos
            start = start + 1

            # Select MSB
            self.spi.xfer2([self.DMAH, dmah])
            self.spi.xfer2([self.DMAL, dmal])

            self.spi.xfer2([self.DMDI, (char)])

    def reset(self):
        self.spi.xfer2([self.VM0_reg, self.MAX7456_reset])
        time.sleep(.1)
        while True:
            r = self.spi.xfer([self.STATUS, 0x00])
            stable = self.testBit(r[1], 1)
            if stable == 0:
                print ("Reset MAX7456 Ok...")
                break
            break

    def testBit(self, value, offset):
        mask = 1 << value
        return(value & mask)

    def setBit(self, value, offset):
        mask = 1 << offset
        return(value + mask)

    def clearBit(self, int_type, offset):
        mask = ~(1 << offset)
        return(int_type & mask)

try:
    max7456 = max7456()

except KeyboardInterrupt:
    spi.close()

print ("VideoDetect_1, VideoDetect_2, VideoDetect_3, Squelch_Detect_1 running...                                                                                   ")

#Function Set bit in variable / function set bit in byte for Output Card
def set_bit(value, bit):
    print(value | (1<<bit))
    return value | (1<<bit)

#Function resets bit in variable / function reset bit in byte for Output Card
def clear_bit(value, bit):
    print(value & ~(1<<bit))
    return value & ~(1<<bit)

#Check GPIO VideoDetect and SquelchDetect for high or low for Output Card for HD                                                                                   MI Switch
def measure1(channel):
  global start1
  global stopp1
  global delta1
  global o1
  if GPIO.input(GPIO_VideoDetect_1) == 0:
    start1 = time.time()
  else:
    stopp1 = time.time()
    delta1 = stopp1 - start1
    print ("Switch HDMI to Port 2 CVBS")
    o1 = set_bit(o1, 1)
    i2cbus_relais.write_byte(DEVICE_ADDR_RELAIS,255-o1)
    time.sleep(.2)
    o1 = clear_bit(o1, 1)
    i2cbus_relais.write_byte(DEVICE_ADDR_RELAIS,255-o1)
  if GPIO.input(GPIO_VideoDetect_1) + GPIO.input(GPIO_VideoDetect_2) + GPIO.inpu                                                                                   t(GPIO_VideoDetect_3) + GPIO.input(GPIO_SquelchDetect_1) == False:
    print ("Switch HDMI to Port 1 Camera")
    o1 = set_bit(o1, 0)
    i2cbus_relais.write_byte(DEVICE_ADDR_RELAIS,255-o1)
    time.sleep(.2)
    o1 = clear_bit(o1, 0)
    i2cbus_relais.write_byte(DEVICE_ADDR_RELAIS,255-o1)
  elif GPIO.input(GPIO_VideoDetect_1) + GPIO.input(GPIO_VideoDetect_2) + GPIO.in                                                                                   put(GPIO_VideoDetect_3) == False and GPIO.input(GPIO_SquelchDetect_1) == True:
    print ("Switch HDMI to Port 3 DVB-T")
    o1 = set_bit(o1, 2)
    i2cbus_relais.write_byte(DEVICE_ADDR_RELAIS,255-o1)
    time.sleep(.2)
    o1 = clear_bit(o1, 2)
    i2cbus_relais.write_byte(DEVICE_ADDR_RELAIS,255-o1)
  elif GPIO.input(GPIO_SquelchDetect_1) == True and (GPIO_VideoDetect_1) == True                                                                                   :
    print ("Switch HDMI to Port 2 CVBS")
    o1 = set_bit(o1, 1)
    i2cbus_relais.write_byte(DEVICE_ADDR_RELAIS,255-o1)
    time.sleep(.2)
    o1 = clear_bit(o1, 1)
    i2cbus_relais.write_byte(DEVICE_ADDR_RELAIS,255-o1)

def measure2(channel):
  global start2
  global stopp2
  global delta2
  global o1
  if GPIO.input(GPIO_VideoDetect_2) == 0:
    start2 = time.time()
  else:
    stopp2 = time.time()
    delta2 = stopp2 - start2
    print ("Switch HDMI to Port 2 CVBS")
    o1 = set_bit(o1, 1)
    i2cbus_relais.write_byte(DEVICE_ADDR_RELAIS,255-o1)
    time.sleep(.2)
    o1 = clear_bit(o1, 1)
    i2cbus_relais.write_byte(DEVICE_ADDR_RELAIS,255-o1)
  if GPIO.input(GPIO_VideoDetect_1) + GPIO.input(GPIO_VideoDetect_2) + GPIO.inpu                                                                                   t(GPIO_VideoDetect_3) + GPIO.input(GPIO_SquelchDetect_1) == False:
    print ("Switch HDMI to Port 1 Camera")
    o1 = set_bit(o1, 0)
    i2cbus_relais.write_byte(DEVICE_ADDR_RELAIS,255-o1)
    time.sleep(.2)
    o1 = clear_bit(o1, 0)
    i2cbus_relais.write_byte(DEVICE_ADDR_RELAIS,255-o1)
  elif GPIO.input(GPIO_VideoDetect_1) + GPIO.input(GPIO_VideoDetect_2) + GPIO.in                                                                                   put(GPIO_VideoDetect_3) == False and GPIO.input(GPIO_SquelchDetect_1) == True:
    print ("Switch HDMI to Port 3 DVB-T")
    o1 = set_bit(o1, 2)
    i2cbus_relais.write_byte(DEVICE_ADDR_RELAIS,255-o1)
    time.sleep(.2)
    o1 = clear_bit(o1, 2)
    i2cbus_relais.write_byte(DEVICE_ADDR_RELAIS,255-o1)
  elif GPIO.input(GPIO_SquelchDetect_1) == True and (GPIO_VideoDetect_2) == True                                                                                   :
    print ("Switch HDMI to Port 2 CVBS")
    o1 = set_bit(o1, 1)
    i2cbus_relais.write_byte(DEVICE_ADDR_RELAIS,255-o1)
    time.sleep(.2)
    o1 = clear_bit(o1, 1)
    i2cbus_relais.write_byte(DEVICE_ADDR_RELAIS,255-o1)

def measure3(channel):
  global start3
  global stopp3
  global delta3
  global o1
  if GPIO.input(GPIO_VideoDetect_3) == 0:
    start3 = time.time()
  else:
    stopp3 = time.time()
    delta3 = stopp3 - start3
    print ("Switch HDMI to Port 2 CVBS")
    o1 = set_bit(o1, 1)
    i2cbus_relais.write_byte(DEVICE_ADDR_RELAIS,255-o1)
    time.sleep(.2)
    o1 = clear_bit(o1, 1)
    i2cbus_relais.write_byte(DEVICE_ADDR_RELAIS,255-o1)
  if GPIO.input(GPIO_VideoDetect_1) + GPIO.input(GPIO_VideoDetect_2) + GPIO.inpu                                                                                   t(GPIO_VideoDetect_3) + GPIO.input(GPIO_SquelchDetect_1) == False:
    print ("Switch HDMI to Port 1 Camera")
    o1 = set_bit(o1, 0)
    i2cbus_relais.write_byte(DEVICE_ADDR_RELAIS,255-o1)
    time.sleep(.2)
    o1 = clear_bit(o1, 0)
    i2cbus_relais.write_byte(DEVICE_ADDR_RELAIS,255-o1)
  elif GPIO.input(GPIO_VideoDetect_1) + GPIO.input(GPIO_VideoDetect_2) + GPIO.in                                                                                   put(GPIO_VideoDetect_3) == False and GPIO.input(GPIO_SquelchDetect_1) == True:
    print ("Switch HDMI to Port 3 DVB-T")
    o1 = set_bit(o1, 2)
    i2cbus_relais.write_byte(DEVICE_ADDR_RELAIS,255-o1)
    time.sleep(.2)
    o1 = clear_bit(o1, 2)
    i2cbus_relais.write_byte(DEVICE_ADDR_RELAIS,255-o1)
  elif GPIO.input(GPIO_SquelchDetect_1) == True and (GPIO_VideoDetect_3) == True                                                                                   :
    print ("Switch HDMI to Port 2 CVBS")
    o1 = set_bit(o1, 1)
    i2cbus_relais.write_byte(DEVICE_ADDR_RELAIS,255-o1)
    time.sleep(.2)
    o1 = clear_bit(o1, 1)
    i2cbus_relais.write_byte(DEVICE_ADDR_RELAIS,255-o1)

def measure4(channel):
  global start4
  global stopp4
  global delta4
  global o1
  if GPIO.input(GPIO_SquelchDetect_1) == 0:
    start4 = time.time()
  else:
    stopp4 = time.time()
    delta4 = stopp4 - start4
    print ("Switch HDMI to Port 3 DVB-T")
    o1 = set_bit(o1, 2)
    i2cbus_relais.write_byte(DEVICE_ADDR_RELAIS,255-o1)
    time.sleep(.2)
    o1 = clear_bit(o1, 2)
    i2cbus_relais.write_byte(DEVICE_ADDR_RELAIS,255-o1)
  if GPIO.input(GPIO_VideoDetect_1) + GPIO.input(GPIO_VideoDetect_2) + GPIO.inpu                                                                                   t(GPIO_VideoDetect_3) + GPIO.input(GPIO_SquelchDetect_1) == False:
    print ("Switch HDMI to Port 1 Camera")
    o1 = set_bit(o1, 0)
    i2cbus_relais.write_byte(DEVICE_ADDR_RELAIS,255-o1)
    time.sleep(.2)
    o1 = clear_bit(o1, 0)
    i2cbus_relais.write_byte(DEVICE_ADDR_RELAIS,255-o1)
  elif GPIO.input(GPIO_SquelchDetect_1) == False and GPIO.input(GPIO_VideoDetect                                                                                   _1) == True:
    print ("Switch HDMI to Port 2 CVBS")
    o1 = set_bit(o1, 1)
    i2cbus_relais.write_byte(DEVICE_ADDR_RELAIS,255-o1)
    time.sleep(.2)
    o1 = clear_bit(o1, 1)
    i2cbus_relais.write_byte(DEVICE_ADDR_RELAIS,255-o1)
  elif GPIO.input(GPIO_SquelchDetect_1) == False and GPIO.input(GPIO_VideoDetect                                                                                   _2) == True:
    print ("Switch HDMI to Port 2 CVBS")
    o1 = set_bit(o1, 1)
    i2cbus_relais.write_byte(DEVICE_ADDR_RELAIS,255-o1)
    time.sleep(.2)
    o1 = clear_bit(o1, 1)
    i2cbus_relais.write_byte(DEVICE_ADDR_RELAIS,255-o1)
  elif GPIO.input(GPIO_SquelchDetect_1) == False and GPIO.input(GPIO_VideoDetect                                                                                   _3) == True:
    print ("Switch HDMI to Port 2 CVBS")
    o1 = set_bit(o1, 1)
    i2cbus_relais.write_byte(DEVICE_ADDR_RELAIS,255-o1)
    time.sleep(.2)
    o1 = clear_bit(o1, 1)
    i2cbus_relais.write_byte(DEVICE_ADDR_RELAIS,255-o1)

GPIO.add_event_detect(18, GPIO.BOTH, callback=measure1, bouncetime=200)
GPIO.add_event_detect(23, GPIO.BOTH, callback=measure2, bouncetime=200)
GPIO.add_event_detect(24, GPIO.BOTH, callback=measure3, bouncetime=200)
GPIO.add_event_detect(12, GPIO.BOTH, callback=measure4, bouncetime=200)

#Loop
while True:

    VideoDetect_1 = GPIO.input(GPIO_VideoDetect_1)
    VideoDetect_2 = GPIO.input(GPIO_VideoDetect_2)
    VideoDetect_3 = GPIO.input(GPIO_VideoDetect_3)
    SquelchDetect_1 = GPIO.input(GPIO_SquelchDetect_1)
    SquelchDetect_2 = GPIO.input(GPIO_SquelchDetect_2)
    SquelchDetect_3 = GPIO.input(GPIO_SquelchDetect_3)
    SquelchDetect_4 = GPIO.input(GPIO_SquelchDetect_4)


    Button = GPIO.input(GPIO_Button)
    if Button == False:
        max7456.printStr(1,1, "HAMKit VMAC PiHat", enable = True)
        max7456.printStr(2,1, "Reboot by Sysop", enable = True)
        flashleds (10)
        os.system("sudo reboot")

    DINT = GPIO.input(GPIO_DINT)
    if DINT == True:
        D0 = GPIO.input(GPIO_D0)
        D1 = GPIO.input(GPIO_D1)
        D2 = GPIO.input(GPIO_D2)
        D3 = GPIO.input(GPIO_D3)
        DValue = D0+(D1*2)+(D2*4)+(D3*8)
        if DValue == 1:
            max7456.printStr(1,1, "CQ de 10.420GHz", enable = True)
            time.sleep(5)
            max7456.printStr(1,1, "               ", enable = True)
        elif DValue == 2:
              max7456.printStr(1,1, "CQ de 1.251GHz ", enable = True)
              time.sleep(5)
              max7456.printStr(1,1, "               ", enable = True)
        elif DValue == 3:
              max7456.printStr(1,1, "CQ de Test     ", enable = True)
              time.sleep(5)
              max7456.printStr(1,1, "               ", enable = True)
        elif DValue == 4:
              max7456.printStr(1,1, "CQ de 436MHz   ", enable = True)
              time.sleep(5)
              max7456.printStr(1,1, "               ", enable = True)

    if VideoDetect_1 == True:
       ss.on("VD_1")
    else:
         ss.off("VD_1")
    if VideoDetect_2 == True:
       ss.on("VD_2")
    else:
         ss.off("VD_2")
    if VideoDetect_3 == True:
       ss.on("VD_3")
    else:
         ss.off("VD_3")
    if SquelchDetect_1 == True:
       ss.on("SD_1")
    else:
         ss.off("SD_1")

    if ss.current == "VD_1":
#    if VideoDetect_1 == True:
        print ("VideoDetect_1")
        i2cbus.write_byte_data(DEVICE_ADDR, 0x01, 0x81) #Input 1 to Output 1
        i2cbus.write_byte_data(DEVICE_ADDR, 0x03, 0x81) #Input 1 to Output 2
        i2cbus.write_byte_data(DEVICE_ADDR, 0x06, 0x87) #Input 4 to Output 3
        i2cbus.write_byte_data(DEVICE_ADDR, 0x09, 0x87) #Input 4 to Output 4
        i2cbus.write_byte_data(DEVICE_ADDR, 0x07, 0x81) #Input 1 to OSD In
        i2cbus.write_byte_data(DEVICE_ADDR, 0x01, 0x86) #Input OSD to Output 1
        i2cbus.write_byte_data(DEVICE_ADDR, 0x03, 0x86) #Input OSD to Output 2
        max7456.printStr(14,1, "RX 10.420GHz           ", enable = True)
        flashleds (1)

    elif ss.current == "VD_2":
#    elif VideoDetect_2 == True:
        print ("VideoDetect_2")
        i2cbus.write_byte_data(DEVICE_ADDR, 0x01, 0x83) #Input 2 to Output 1
        i2cbus.write_byte_data(DEVICE_ADDR, 0x03, 0x83) #Input 2 to Output 2
        i2cbus.write_byte_data(DEVICE_ADDR, 0x06, 0x88) #Input 5 to Output 3
        i2cbus.write_byte_data(DEVICE_ADDR, 0x09, 0x88) #Input 5 to Output 4
        i2cbus.write_byte_data(DEVICE_ADDR, 0x07, 0x83) #Input 2 to OSD In
        i2cbus.write_byte_data(DEVICE_ADDR, 0x01, 0x86) #Input OSD to Output 1
        i2cbus.write_byte_data(DEVICE_ADDR, 0x03, 0x86) #Input OSD to Output 2
        max7456.printStr(14,1, "RX 1.251GHz            ", enable = True)
        flashleds (2)

    elif ss.current == "VD_3":
#    elif VideoDetect_3 == True:
        print ("VideoDetect_3")
        i2cbus.write_byte_data(DEVICE_ADDR, 0x01, 0x85) #Input 3 to Output 1
        i2cbus.write_byte_data(DEVICE_ADDR, 0x03, 0x85) #Input 3 to Output 2
        i2cbus.write_byte_data(DEVICE_ADDR, 0x06, 0x89) #Input 6 to Output 3
        i2cbus.write_byte_data(DEVICE_ADDR, 0x09, 0x89) #Input 6 to Output 4
        i2cbus.write_byte_data(DEVICE_ADDR, 0x07, 0x85) #Input 3 to OSD In
        i2cbus.write_byte_data(DEVICE_ADDR, 0x01, 0x86) #Input OSD to Output 1
        i2cbus.write_byte_data(DEVICE_ADDR, 0x03, 0x86) #Input OSD to Output 2
        max7456.printStr(14,1, "RX Test                ", enable = True)
        flashleds (3)

    elif ss.current == "SD_1":
#    elif SquelchDetect_1 == False:
        print ("SquelchDetect_1")
        i2cbus.write_byte_data(DEVICE_ADDR, 0x01, 0x8c) #Input Pi-V to Output 1
        i2cbus.write_byte_data(DEVICE_ADDR, 0x03, 0x8c) #Input Pi-V to Output 2
        i2cbus.write_byte_data(DEVICE_ADDR, 0x06, 0x8b) #Input Pi-A to Output 3
        i2cbus.write_byte_data(DEVICE_ADDR, 0x09, 0x8b) #Input Pi-A to Output 4
        i2cbus.write_byte_data(DEVICE_ADDR, 0x07, 0x8c) #Input Pi-V to OSD In
        i2cbus.write_byte_data(DEVICE_ADDR, 0x01, 0x86) #Input OSD to Output 1
        i2cbus.write_byte_data(DEVICE_ADDR, 0x03, 0x86) #Input OSD to Output 2
        max7456.printStr(14,1, datetime.datetime.now().strftime(dateString), ena                                                                                   ble = True)
        max7456.printStr(14,9, ", Pi Temp     C", enable = True)
        file = open("/home/pi/1.txt","r")
        max7456.printStr(14,19, file.readline().rstrip('\n'), enable = True)
        file.close()
        flashleds (4)

    else:
        print ("Pi")
        i2cbus.write_byte_data(DEVICE_ADDR, 0x01, 0x8c) #Input Pi-V to Output 1
        i2cbus.write_byte_data(DEVICE_ADDR, 0x03, 0x8c) #Input Pi-V to Output 2
        i2cbus.write_byte_data(DEVICE_ADDR, 0x06, 0x8b) #Input Pi-A to Output 3
        i2cbus.write_byte_data(DEVICE_ADDR, 0x09, 0x8b) #Input Pi-A to Output 4
        i2cbus.write_byte_data(DEVICE_ADDR, 0x07, 0x8c) #Input Pi-V to OSD In
        i2cbus.write_byte_data(DEVICE_ADDR, 0x01, 0x86) #Input OSD to Output 1
        i2cbus.write_byte_data(DEVICE_ADDR, 0x03, 0x86) #Input OSD to Output 2
        max7456.printStr(14,1, datetime.datetime.now().strftime(dateString), ena                                                                                   ble = True)
        max7456.printStr(14,9, ", Pi Temp     C", enable = True)
        file = open("/home/pi/1.txt","r")
        max7456.printStr(14,19, file.readline().rstrip('\n'), enable = True)
        file.close()
        flashleds (0)

    #Heatbeat PTT LED as test
    GPIO.output(PTT,GPIO.HIGH)
    time.sleep(.2)
    GPIO.output(PTT,GPIO.LOW)
    time.sleep(1)

Benutzeravatar
__blackjack__
User
Beiträge: 13069
Registriert: Samstag 2. Juni 2018, 10:21
Wohnort: 127.0.0.1
Kontaktdaten:

@DL9AM: Die `setBit()`-”Methode” ist fehlerhaft, da muss ``|`` statt ``+`` verwendet werden, sonst ist das Ergebnis falsch wenn das Bit bereits gesetzt war. Und ”Methode” in Anführungszeichen, weil das eigentlich eine Funktion ist und ausserhalb der Klasse stehen sollte. Und solche Funktionen gibt es ja bereits auf Modulebene‽

Bei ``GPIO.input(GPIO_VideoDetect_1) + GPIO.input(GPIO_VideoDetect_2) + …`` sollte man ``or`` statt ``+`` verwenden. Ich glaube das wurde schon mal gesagt. ;-)

So ist das eher verwirrend und, auch wenn es wahrscheinlich nicht sooo wichtig ist, verbraucht mehr Rechenzeit für alle Fälle wo der erste Eingang nicht bereits GPIO.HIGH ist.

Statt ``GPIO.setwarnings(False)`` sollte man schauen was man falsch macht und das beheben. Das ``GPIO.cleanup()`` gehört beispielsweise ans Ende. Und am besten in einem ``finally``-Block, damit das auch wirklich sichergestellt ist.

Beim Erstellen des `max7456`-Objekts ist eine kaputte Ausnahmebehandlung. Es gibt auf Modulebene kein `spi`, das wird also zu einem `NameError` führen. An sich auch nicht schlecht, denn dann läuft der Rest des Programms nicht weiter, was ja keinen Sinn macht wenn es das Display nicht gibt, was im weiteren Verlauf verwendet wird. Denn spätestens dann wird es Probleme geben. Keinen `NameError`, denn den das Objekt auf Modulebene wurde ja genau wie die Klasse benannt. Was keine gute Idee ist. `max7456` entspricht auch nicht den Namenskonventionen für Klassen (MixedCase), die unter anderem dafür sorgt das man Exemplare wie die Klasse nennen kann, nur eben mit Kleinbuchstaben, ohne das solche Unfälle passieren.

In der `reset()`-Methode ist eine ``while True:``-Schleife deren letzte Anweisung ein ``break`` ist. Dann ist das keine Schleife sondern verwirrender Unsinn.

``global``, durchnummerierte Namen, und diese Unmengen an Codewiederholungen machen den Code schwer lesbar und fehleranfällig.
„All religions are the same: religion is basically guilt, with different holidays.” — Cathy Ladman
Antworten