def output(self, value): self.State = value if (value): print("BEEP") else: print("----") GPIO.output(self.Pin, value)
def timer_cycle(self): self.thr = threading.Timer(1, BackgroundWorker.timer_cycle,[self]) self.thr.start() self.requestTimer += 1 if self.requestTimer >= 2: self.requestTimer = 0 self.resetTagInfo() self.readRFIDTag() #print "Check for opening request" if self.requestOpening == True: self.requestOpening = False self.openingTimer = 0; print "Opening request" if self.openingTimer >= 0: print "Opened door cycle" + "(" + ")" GPIO.output(12, GPIO.LOW) self.openingTimer += 1 if self.openingTimer >= 7: self.openingTimer = -1 print "Closing door" GPIO.output(12, GPIO.HIGH)
def setReadWrite(channelsToDown, channelsToUp): logging.info("switching rows/columns") for row in channelsToDown: #logging.info("Setting up channel " + str(row) + " to PUD_DOWN. ") GPIO.setup(row, GPIO.IN, pull_up_down=GPIO.PUD_DOWN) for column in channelsToUp: #logging.info("Setting up channel " + str(column) + " to PUD_UP. ") #GPIO.setup(column, GPIO.IN, pull_up_down=GPIO.PUD_UP) GPIO.setup(column, GPIO.OUT)
def listenToHoorn(): global run global hoorn global HOORN_UP global HOORN_DOWN global hoorn_previous_state global initial_state while run: # also listen to hoorn hoorn_state = GPIO.input(hoorn) if not initial_state and hoorn_previous_state != hoorn_state: if hoorn_state == HOORN_UP: if inXbmc: xbmc.log(msg="hoorn up", level=xbmc.LOGDEBUG) send_key("hoorn_up") else: if inXbmc: xbmc.log(msg="hoorn down", level=xbmc.LOGDEBUG) send_key("hoorn_down") hoorn_previous_state = hoorn_state else: initial_state = False sleep(hoornWaitTime) logging.info("Stopped listening to hook...")
def row_changed(row): if verbose: logging.info("Row " + str(row) + " has changed") global processing global rowsWithColumns global columns global keys if not processing: processing = True # Disable events until action is done setRowEvents(row, KEYPAD_MODE_READCOLUMNS) # Read which column it was for column in rowsWithColumns[row]: columnValue = GPIO.input(column) if columnValue: key = keys[str(row) + "," + str(column)] send_key(key) pass # Re-enable events setRowEvents(row, KEYPAD_MODE_READROWS) sleep(0.1) # GPIO.wait_for_edge(row, GPIO.FALLING) processing = False else: logging.info("already processing, ignored")
def row_changed(button, i): logging.info("entering row_changed with button: " + str(button) + ", i: " + str(i)) global channelVal #switch columns to input to read the values setReadWrite(columns, rows) #now read columns for column in columns: value = GPIO.input(column) logging.info("column " + str(column) + ": " + str(value)) if value: logging.info("column " + str(channelEnums[i])) channelVal = channelVal + channelEnums[i] i = i + 1; logging.info("Button event: " + str(channelVal)) if button == G.NONE: xbmc.release_button() else: try: global mapping print(kbmapping[channelVal]) xbmc.send_keyboard_button(button=kbmapping[channelVal]) except: logging.warning("value invalid") sleep(0.025) #switch back to reading rows setReadWrite(rows, columns)
def __init__(self): self.pins = [GPIO(12), GPIO(13), GPIO(182)] # green, red, blue # thread, used to blink later self.blinker_thread = None # to stop blinker later self.blinker_not_interrupted = True # keep current state in order to restore later self.current_blink_pattern = "" self.colors_dict = { "off": [0, 0, 0], "red": [1, 0, 0], "green": [0, 1, 0], "blue": [0, 0, 1], "white": [1, 1, 1], "yellow": [1, 1, 0], "cyan": [0, 1, 1], "magenta": [1, 0, 1], "orange": [1, 0.4, 0], "weakred": [0.1, 0, 0] } # channel numbers self.pwm_channels = [0, 1, 2] # red, green, blue # first, we need to change the pin's pinmux to mode1 for pin in self.pins: pin.setPinmux("mode1") # then, export the 3 pwn channels if needed for ch in self.pwm_channels: if not os.path.exists(self.pwm_prefix + "/pwm" + str(ch)): with open(self.pwm_prefix + "export", "w") as f: f.write(str(ch)) # enable all of the channels for ch in self.pwm_channels: with open(self.pwm_prefix + "pwm" + str(ch) + "/enable", "w") as f: f.write("1") # set period for ch in self.pwm_channels: with open(self.pwm_prefix + "pwm" + str(ch) + "/period", "w") as f: f.write("1000000")
def __init__(self): self.button_state: bool = False self.gpio: GPIO = GPIO() self.gpio.bind_to(self.update_button_state) self.camera: Camera = Camera(video_device=0) Process(target=self.gpio.run).start()
def listenToRows(): global run global keypadWaitTime while run: global rowsWithColumns global lastPing global initial_state if (lastPing - datetime.now()).seconds == 50: xClient.ping() lastPing = datetime.now() for row in rowsWithColumns: rowinput = GPIO.input(row) if verbose: logging.info("Row " + str(row) + ": " + str(rowinput)) if rowinput: row_changed(row) sleep(keypadWaitTime) logging.info("Stopped listening to rows...")
def __init__(self, app): # initialize worker variables self.app = app self.requestOpening = False self.openingTimer = -1 self.requestTimer = 0 self.tagInfo = RfidTagInfo("", "") self.tagResetCount = 0 self.lock = False # setup gpio and set default (Low) GPIO.setmode(GPIO.BOARD) GPIO.setup(12,GPIO.OUT, initial=GPIO.HIGH) GPIO.output(12, GPIO.HIGH)
def start(): global channelVal global previousChannelVal global previousRow i = 0 for row in rows: value = GPIO.input(row) logging.info("row " + str(row) + ": " + str(value)) if value: channelVal = channelVal + channelEnums[i] i = i + 1 if previousRow <> channelVal & channelVal: logging.info("change detected") logging.info("row " + str(row) + " is up: " + str(channelEnums[i])) # Keep track of row to check changes previousRow = channelVal; row_changed(channelVal, i) previousChannelVal = channelVal channelVal = G.NONE lock = False
G.BUTTON8: "down", G.BUTTON9: "space", G.BUTTON0: "esc", G.BUTTONHEK: "a", G.BUTTONSTER: "backspace" } #logging.basicConfig(filename=addonFolder + 'keypad.log',level=logging.INFO) logging.basicConfig(level=logging.INFO) now = datetime.now().isoformat() logging.info(str(now)) logging.info("Cleanup GPIO") GPIO.cleanup() logging.info("Setting GPIO mode to BCM") GPIO.setmode(GPIO.BCM) def setReadWrite(channelsToDown, channelsToUp): logging.info("switching rows/columns") for row in channelsToDown: #logging.info("Setting up channel " + str(row) + " to PUD_DOWN. ") GPIO.setup(row, GPIO.IN, pull_up_down=GPIO.PUD_DOWN) for column in channelsToUp: #logging.info("Setting up channel " + str(column) + " to PUD_UP. ") #GPIO.setup(column, GPIO.IN, pull_up_down=GPIO.PUD_UP) GPIO.setup(column, GPIO.OUT) #rows = json.loads(config.get("Foo","fibs"))
def Value(self): self.__Value = GPIO.input(self.Pin) return self.__Value
keypadWaitTime = 0.25 logging.warning("Can't find sleep setting. Defaulted to " + str(keypadWaitTime)) try: bounceTime = config.getfloat("settings", "bounceTime") logging.info("BounceTime: " + str(bounceTime)) except: bounceTime = 0.25 logging.warning("Can't find bounceTime setting. Defaulted to " + str(bounceTime)) now = datetime.now().isoformat() logging.info(str(now)) logging.info("Setting GPIO mode to BCM") GPIO.setmode(GPIO.BCM) # contains a dictionary of each row an array of columns for that row rowsWithColumns = {} # keep seperate array with columns to check if already set up columns = [] keys = {} i = 1 processing = False actions = {} lastPing = datetime.now() def listenToRows():
def addEventListner(self, event, func, delta): GPIO.add_event_detect(self.Pin, event, callback=func, bouncetime=delta)
def __init__(self, name="gpio", interval=0.1, hostname=""): httphandle.__init__(self, name, interval, hostname) self.gpio = GPIO(self)
from Signal import Signal from Turnout import Turnout json_data = open('/home/pi/elite-xpressnet/track/config.json') data = json.load(json_data) redis = redis.Redis() pi = {} gpio = {} output = {} for pi_in in data["piinterface"]: pi[pi_in["id"]] = PiInterface(pi_in["bus"]) for gpio_in in data["gpio"]: gpio[gpio_in["id"]] = GPIO(pi[gpio_in["pi_id"]], gpio_in["address"], gpio_in["bank"], gpio_in["mode"]) logging.debug(str(gpio_in["id"])) for s_in in data["signals"]: bits = s_in["id"].split(",") key = str(bits[0]) + "," + str(bits[1]) io = gpio[key] start_address = bits[2] output[s_in["id"]] = Signal(s_in["id"], io, s_in["pinOut"], start_address, s_in["aspects"]) io.addOutput(output[s_in["id"]]) for t_in in data["turnouts"]: bits = t_in["id"].split(",") key = str(bits[0]) + "," + str(bits[1]) io = gpio[key]
def row_changed(row): global rows GPIO.remove_event_detect(row) GPIO.setup(row, GPIO.OUT) for column in rows[row]: GPIO.setup(column, GPIO.IN, pull_up_down=GPIO.PUD_DOWN) # Send signal from row to columns GPIO.output(row, 1) #sleep(0.05) # Read which column it was for column in rows[row]: columnValue = GPIO.input(column) if(columnValue): key = keys[str(row) + "," + str(column)] logging.info("row changed: " + str(row)) send_key(key) # Set row and columns back to original setup GPIO.setup(row, GPIO.IN, pull_up_down=GPIO.PUD_DOWN) for column in rows[row]: GPIO.remove_event_detect(column) GPIO.setup(column, GPIO.OUT) GPIO.output(column, 1) GPIO.add_event_detect(row, GPIO.RISING, callback=row_changed)
# need this for GPIO's from GPIO import GPIO # filter F = {1: GPIO("UV_filter", 11)} # valves V = {3: GPIO("CO2_solenoid", 89), 4: GPIO("N2_solenoid", 10)} # miscellaneous M = { 1: GPIO("heater", 45), 2: GPIO("chiller", 44), 6: GPIO("fan_1", 70), 7: GPIO("fan_2", 71), 8: GPIO("O2_concentrator", 26), 18: GPIO("LED", 51) } # pumps P = { 1: GPIO("main_pump", 62), 2: GPIO("condensate_pump", 63), 3: GPIO("nutrient_1_dosing", 23), 4: GPIO("nutrient_2_dosing", 65), 5: GPIO("pH_dosing", 27), 6: GPIO("nutrient_1_circulation", 37), 7: GPIO("air_bubbler", 33), 8: GPIO("filter_pump", 61), 9: GPIO("nutrient_2_circulation", 86), 10: GPIO("humidifier_pump", 32),
def open_the_door(self): while (True): print "Openening door" time.sleep(1.0) GPIO.output(GPIO_RELAY, GPIO.LOW) GPIO.output(GPIO_LED_GREEN, GPIO.HIGH)
logging.basicConfig(filename=addonFolder + 'keypad.log',level=logging.INFO) #logging.basicConfig(level=logging.INFO) #hoorn = 11 config = ConfigParser.RawConfigParser() configFile = addonFolder + 'keypad.config' logging.info("reading config file " + configFile) config.read(configFile) now = datetime.now().isoformat() logging.info(str(now)) logging.info("Setting GPIO mode to BCM") GPIO.setmode(GPIO.BCM) #contains a dictionary of each row an array of columns for that row rows = {} #keep seperate array with columns to check if already set up columns = [] keys = {} i = 1 def send_key(key): try: xbmc.send_keyboard_button(button=key) sleep(0.25) xbmc.release_button() except:
def led_cycle(self): if self.systemUp == True: GPIO.output(GPIO_LED_YELLOW, GPIO.HIGH) else: GPIO.output(GPIO_LED_YELLOW, GPIO.LOW) if self.ledState == self.LED_STATE_IDLE: self.ledStateCounter = 0 if self.ledState == self.LED_STATE_ACCESS_GRANTED: if self.ledStateCounter % 2 == 0: GPIO.output(GPIO_LED_GREEN, GPIO.HIGH) else: GPIO.output(GPIO_LED_GREEN, GPIO.LOW) self.ledStateCounter += 1 if self.ledStateCounter > 15: self.ledState = self.LED_STATE_IDLE self.ledStateCounter = 0 if self.ledState == self.LED_STATE_ACCESS_DENIED: if self.ledStateCounter % 2 == 0: GPIO.output(GPIO_LED_RED, GPIO.HIGH) else: GPIO.output(GPIO_LED_RED, GPIO.LOW) self.ledStateCounter += 1 if self.ledStateCounter > 15: self.ledState = self.LED_STATE_IDLE self.ledStateCounter = 0 if self.ledState == self.LED_STATE_CLOSED: self.ledState = self.LED_STATE_IDLE self.ledStateCounter = 0 GPIO.output(GPIO_LED_RED, GPIO.LOW) GPIO.output(GPIO_LED_GREEN, GPIO.LOW)
def __init__(self, app): # initialize worker variables self.LED_STATE_IDLE = 0 self.LED_STATE_ACCESS_GRANTED = 1 self.LED_STATE_ACCESS_DENIED = 2 self.LED_STATE_CLOSED = 3 self.first = True self.app = app self.requestOpening = False self.openingTimer = -1 self.requestTimer = 0 self.syncTimer = 0 self.ledStateTimer = 0 self.ledState = self.LED_STATE_IDLE self.ledStateCounter = 0 self.systemUp = True if config.NODE_SYNC_ON_STARTUP == True: self.forceSync = True else: self.forceSync = False self.forceBackup = False self.backupTimer = 0 self.cleanupTimer = 0 self.tagInfo = RfidTagInfo("", "") self.tagResetCount = 0 self.lock = False self.lastBackupTime = datetime.datetime.now() self.lastCleanupTime = datetime.datetime.now().replace(1910) self.lastSyncTime = datetime.datetime.now() # setup gpio and set default (Low) GPIO.setmode(GPIO.BOARD) GPIO.setup(GPIO_RELAY, GPIO.OUT, initial=GPIO.HIGH) GPIO.output(GPIO_RELAY, GPIO.HIGH) GPIO.setup(GPIO_LED_GREEN, GPIO.OUT, initial=GPIO.LOW) GPIO.output(GPIO_LED_GREEN, GPIO.LOW) GPIO.setup(GPIO_LED_YELLOW, GPIO.OUT, initial=GPIO.LOW) GPIO.output(GPIO_LED_YELLOW, GPIO.LOW) GPIO.setup(GPIO_LED_RED, GPIO.OUT, initial=GPIO.LOW) GPIO.output(GPIO_LED_RED, GPIO.LOW)
'*****@*****.**', 'Error: ' + str(traceback.format_exc()), 'Error occured', 'L1', 0, 'Internal') db.session.add(logentry) db.session.commit() # print "Check for opening request" if self.requestOpening == True: self.requestOpening = False self.openingTimer = 0 print "Opening request" if self.openingTimer >= 0: if self.openingTimer == 0: print "Openening door" GPIO.output(GPIO_RELAY, GPIO.LOW) self.openingTimer += 1 if self.openingTimer >= 16: self.openingTimer = -1 print "Closing door" GPIO.output(GPIO_RELAY, GPIO.HIGH) self.ledState = self.LED_STATE_CLOSED else: GPIO.output(GPIO_RELAY, GPIO.HIGH) self.ledStateTimer += 1 if self.ledStateTimer >= 0: self.ledStateTimer = 0 try: self.led_cycle()
def setup(self): GPIO.setup(self.Pin, self.Type)
class gpiohandle(httphandle): def __init__(self,name='gpio',interval=0.1,hostname=""): httphandle.__init__(self,name,interval,hostname) self.gpio=GPIO() def execute(self):#重写 self.gpio.stop()#停止之前的命令 cmd= self.gethttpdata(self.name) if cmd<>None: cmdname=cmd['cmdname'] if cmdname=='setgpio': self.setgpio(cmd) elif cmdname=='replygpio': self.replygpio(cmd) elif cmdname=='getgpio': self.getgpio(cmd) elif cmdname=='getgpios': self.getgpios() def checkGPIO(self, gpio): i = int(gpio) if not self.gpio.isAvailable(i): print "GPIO " + gpio + " Not Available" return False if not self.gpio.isEnabled(i): print "GPIO " + gpio + " Disabled" return False return True def getgpios(self): data=self.gpio.writeJSON() self.posthttpdata(self.name,data) def getgpio(self,cmd): pins=cmd["pins"] self.gpio.reply(pins) def setgpio(self,cmd): setup=cmd['setup'] loop=cmd['loop'] self.gpio.setdata(setup,loop) self.gpio.setDaemon(True)#守护线程 self.gpio.start()#开始执行命令 def replygpio(self,cmd): setup=cmd['setup'] loop=cmd['loop'] reply=cmd['reply'] self.gpio.setdata(setup,loop,reply,self.posthttpdata) self.gpio.setDaemon(True)#守护线程 self.gpio.start()#开始执行命令
def open_the_door(self): while True: print "Openening door" time.sleep(1.0) GPIO.output(GPIO_RELAY, GPIO.LOW) GPIO.output(GPIO_LED_GREEN, GPIO.HIGH)
def __init__(self,name='gpio',interval=0.1,hostname=""): httphandle.__init__(self,name,interval,hostname) self.gpio=GPIO()
class gpiohandle(httphandle): def __init__(self, name="gpio", interval=0.1, hostname=""): httphandle.__init__(self, name, interval, hostname) self.gpio = GPIO(self) def execute(self): # 重写 self.gpio.stop() # 停止之前的命令 cmd = self.gethttpdata(self.name) # print cmd if cmd <> None and cmd.has_key("cmdname"): cmdname = cmd["cmdname"] # print cmdname if cmdname == "setgpio": self.setgpio(cmd) elif cmdname == "replygpio": self.replygpio(cmd) elif cmdname == "getgpio": self.getgpio(cmd) elif cmdname == "getgpios": self.getgpios() def checkGPIO(self, gpio): i = int(gpio) if not self.gpio.isAvailable(i): print "GPIO " + gpio + " Not Available" return False if not self.gpio.isEnabled(i): print "GPIO " + gpio + " Disabled" return False return True def getgpios(self): data = self.gpio.writeJSON() self.posthttpdata(self.name, data) def getgpio(self, cmd): if cmd.has_key("pins"): pins = cmd["pins"] self.gpio.reply(pins) def setgpio(self, cmd): if cmd.has_key("setup") and cmd.has_key("loop"): setup = cmd["setup"] loop = cmd["loop"] self.gpio.setdata(setup, loop, []) if not self.gpio.isAlive(): self.gpio.setDaemon(True) # 守护线程 self.gpio.start() def replygpio(self, cmd): if cmd.has_key("setup") and cmd.has_key("loop") and cmd.has_key("reply"): setup = cmd["setup"] loop = cmd["loop"] reply = cmd["reply"] self.gpio.setdata(setup, loop, reply) if not self.gpio.isAlive(): self.gpio.setDaemon(True) # 守护线程 self.gpio.start()
def output(self, value): if (self.Type == GPIO.OUT): GPIO.output(self.Pin, value)
#!/usr/bin/python import sys sys.path.append('//usr/local/Python') from GPIO import GPIO import cgi import cgitb cgitb.enable() gpio = GPIO() gpio.Run()
def GPIO_Warning(self, value): GPIO.setwarnings(False) self.__GPIO_Warning = value
import GPIO.GPIO as GPIO GPIO.setmode(GPIO.BOARD)
def Mode(self, value): GPIO.setmode(value) self.__Mode = value
def __init__(self, context): gpio.setmode(gpio.BCM) gpio.setup(context.Config["gpio"]["hoorn"], gpio.IN, pull_up_down=gpio.PUD_DOWN)
def input(self): if (self.Type == GPIO.IN): return GPIO.input(self.Pin) else: return -1
def setRowEvents(row, mode): global bounceTime global rowsWithColumns if mode == KEYPAD_MODE_READROWS: # Set row to IN if GPIO.gpio_function(row) == GPIO.IN: logging.warning("Pin " + str(row) + " already set to IN") GPIO.setup(row, GPIO.IN, pull_up_down=GPIO.PUD_DOWN) # GPIO.add_event_detect(row, GPIO.RISING, callback=row_changed, bouncetime=bounceTime) # Set columns to OUT for column in rowsWithColumns[row]: if GPIO.gpio_function(column) == GPIO.OUT: logging.warning("Pin " + str(column) + " already set to OUT") else: GPIO.setup(column, GPIO.OUT, initial=1) else: # Set row to OUT # GPIO.remove_event_detect(row) if GPIO.gpio_function(row) == GPIO.OUT: logging.warning("Pin " + str(row) + " already set to OUT") else: GPIO.setup(row, GPIO.OUT, initial=1) # Set columns to IN for column in rowsWithColumns[row]: if GPIO.gpio_function(column) == GPIO.IN: logging.warning("Pin " + str(column) + " already set to IN") GPIO.setup(column, GPIO.IN, pull_up_down=GPIO.PUD_DOWN)
def getPin(self, pin_number): pin = GPIO(pin_number) pin.openPin() self.GPIOList.append(pin) return pin
def cleanup(): logging.info("Stopping threads...") global run run = False logging.info("Cleaning up GPIO...") GPIO.cleanup()
0, "Internal", ) db.session.add(logentry) db.session.commit() # print "Check for opening request" if self.requestOpening == True: self.requestOpening = False self.openingTimer = 0 print "Opening request" if self.openingTimer >= 0: if self.openingTimer == 0: print "Openening door" GPIO.output(GPIO_RELAY, GPIO.LOW) self.openingTimer += 1 if self.openingTimer >= 16: self.openingTimer = -1 print "Closing door" GPIO.output(GPIO_RELAY, GPIO.HIGH) self.ledState = self.LED_STATE_CLOSED else: GPIO.output(GPIO_RELAY, GPIO.HIGH) self.ledStateTimer += 1 if self.ledStateTimer >= 0: self.ledStateTimer = 0 try: self.led_cycle()
def debugOutput(self, value): self.__Value = value GPIO.output(self.Pin, value)
def removeEventListner(self): GPIO.remove_event_detect(self.Pin)