Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import csv
- import time
- from datetime import date, datetime
- from pathlib import Path
- HEADER = ("Date", "Time", "Sig_Name", "Pin_Status")
- class GpioCsvWriter:
- def __init__(self, base_path, base_name, gpio_pins=None, header=HEADER):
- self.base_name = base_name
- self.base_path = base_path
- self.gpio_pins = gpio_pins or []
- self.header = header
- self._fd = None
- self._csv = None
- self._setup_gpio()
- @property
- def current_file(self):
- return Path(self.base_path, f"{date.today():%Y-%m-%d}_{self.base_name}.csv")
- @property
- def name(self):
- if self._fd is None:
- return ""
- return self._fd.name
- def __enter__(self):
- return self
- def __exit__(self, exc_type, exc_obj, tb):
- self.close()
- def close(self):
- self._csv = None
- if self._fd is not None:
- self._fd.close()
- self._fd = None
- def _init_csv(self):
- if self._fd is not None:
- self._fd.close()
- if not self.current_file.exists():
- write_header = True
- else:
- write_header = False
- self._fd = self.current_file.open("at", encoding="utf8")
- self._csv = csv.writer(self._fd)
- if write_header:
- self._csv.writerow(self.header)
- def writerow(self, row):
- if self._fd is None or self._fd.name != self.current_file:
- self._init_csv()
- self._csv.writerow(row)
- self._fd.flush()
- def _signal(self, pin):
- now = datetime.now()
- self.writerow(
- [
- now.strptime("%Y-%m-%d"),
- now.strptime("%H:%M:%s"),
- str(gpio_pin),
- str(GPIO.input(gpio_pin)),
- ]
- )
- def _setup_gpio(self):
- if not self.gpio_pins:
- return
- GPIO.setmode(GPIO.BCM)
- for pin in self.gpio_pins:
- GPIO.setup(pin, GPIO.IN, GPIO.PUD_DOWN)
- GPIO.add_event_detect(pin, GPIO.BOTH, callback=self._signal)
- if __name__ == "__main__":
- writer = GpioCsvWriter("/tmp", "foo_bar")
- # writer.writerow(["1970-01-01", "00:00", "1", "1"])
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement