osdir.com


[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

printing to stdout


On Fri, 17 Aug 2018 08:31:22 +1000
Cameron Simpson <cs at cskk.id.au> wrote:

> Just looking at your loop I would be inclined to just call flush once
> at the bottom, _before_ the sleep() call:
> 
>   sys.stdout.flush()
> 
> Your call; the performance difference will be small, so it tends to
> come down to keeping your code readable and maintainable.

This is a working script I made. It initializes the I/O expanders, then
it waits for an INT from these I/O expanders on GPIO23, reads the
contents and sends which bit on which chip went up or down to a fifo
(and stdout for logging)

As I'm new to Python, just this question: are there any unPythony
things in this code?

##############################################################

#!/usr/bin/env python3

list_pcf = [0x38, 0x39, 0x3a, 0x3b]
list_pcf_value = []

import sys
from smbus import SMBus
from time import sleep
import RPi.GPIO as GPIO
GPIO.setmode(GPIO.BCM)
bus = SMBus(1)

# initialisation of the input devices:
print ("[INFO] initialisation input devices")
for i in range(len(list_pcf)):
  try:
    bus.write_byte(list_pcf[i], 0xff) # set device to 0xff
    output = bus.read_byte(list_pcf[i])
    list_pcf_value.append(output) # append value to list
    print ("found: %d, input value: 0x%x" % (list_pcf[i], output))
  except IOError:
    print ("[ALERT] I/O problem device 0x%x (init)" % pcf)
  sys.stdout.flush()

# GPIO 23 set up as input. It is pulled up to stop false signals
GPIO.setup(23, GPIO.IN, pull_up_down=GPIO.PUD_UP)
loopcntr = 0 # detects if INT is kept low

while True:
  if GPIO.input(23) == 1: # if still 0, another event has occurred
    GPIO.wait_for_edge(23, GPIO.FALLING)
  print ('-------')
  while GPIO.input(23) == 0:
    for i in range(len(list_pcf)):
      try:
        output = bus.read_byte(list_pcf[i])
        if output != list_pcf_value[i]:
          xor = list_pcf_value[i] ^ output
          for l in range(8):
            if xor & 0x1:
              updown = (output >> l) & 0x1
              print ("%d bit %d: to %d" % (list_pcf[i],l,updown))
              print("%d %d %d" % (list_pcf[i],l,updown), 
                file=open('/mnt/ramdisk/var/lib/ha/events.fifo', 'w'))
            xor = xor >> 1
          list_pcf_value[i] = output
      except IOError:
        print ("[ALERT] I/O problem device 0x%x" % list_pcf[i])

      if GPIO.input(23) == 1:
        loopcntr = 0
        break
      else:
        loopcntr += 1
        if loopcntr >=20:
          print ('[ALERT] possible INT loop, disable 10 seconds')
          sleep (10)
    sys.stdout.flush()
GPIO.cleanup()

-- 
richard lucassen
http://contact.xaq.nl/