Join the newsletter for discounts and shop drop info!
The Watchdog
A python script that watches for file changes and moves them to the emulated USB share.
Usually I keep this Python script as a bare file, so be careful you mark only the actual code for copy-pasting. This way is hopefully temporary, until I set up the actual files system.
(Note that this is the new-and-improved watchdog: if you have an existing Pi that for some reason has lost its watchdog, make sure you've followed the Updating the Watchdog steps to use it. Those instructions are already in the Building your own page.)
#!/usr/bin/python3
import time
import os
from watchdog.observers import Observer
from watchdog.events import *
CMD_MOUNT = "sudo modprobe g_mass_storage file=/piusb.bin stall=0 ro=0 removable=1"
CMD_UNMOUNT = "sudo modprobe -r g_mass_storage"
CMD_COPY = "cp -r /home/pi/smb_share/* /mnt/usb_share/"
CMD_SYNC = "sudo sync"
WATCH_PATH = "/home/pi/smb_share"
ACT_EVENTS = [DirDeletedEvent, DirMovedEvent, FileDeletedEvent, FileModifiedEvent, FileMovedEvent]
ACT_TIME_OUT = 30
class DirtyHandler(FileSystemEventHandler):
def __init__(self):
self.reset()
def on_any_event(self, event):
if type(event) in ACT_EVENTS:
self._dirty = True
self._dirty_time = time.time()
@property
def dirty(self):
return self._dirty
@property
def dirty_time(self):
return self._dirty_time
def reset(self):
self._dirty = False
self._dirty_time = 0
self._path = None
os.system(CMD_MOUNT)
evh = DirtyHandler()
observer = Observer()
observer.schedule(evh, path=WATCH_PATH, recursive=True)
observer.start()
try:
while True:
while evh.dirty:
time_out = time.time() - evh.dirty_time
if time_out >= ACT_TIME_OUT:
os.system(CMD_UNMOUNT)
time.sleep(1)
os.system(CMD_COPY)
time.sleep(3)
os.system(CMD_SYNC)
time.sleep(1)
os.system(CMD_MOUNT)
evh.reset()
time.sleep(1)
time.sleep(1)
except KeyboardInterrupt:
observer.stop()
observer.join()