Skip to content

Instantly share code, notes, and snippets.

@davidhoness
Last active January 25, 2024 08:36
Show Gist options
  • Save davidhoness/0f45ef6a41bac6311614f109acbf92db to your computer and use it in GitHub Desktop.
Save davidhoness/0f45ef6a41bac6311614f109acbf92db to your computer and use it in GitHub Desktop.
#!/usr/bin/python3
import time
import os
from watchdog.observers import Observer
from watchdog.events import *
CMD_MOUNT = "modprobe g_mass_storage file=/piusb.bin stall=0 ro=1"
CMD_UNMOUNT = "modprobe -r g_mass_storage"
CMD_SYNC = "sync"
WATCH_PATH = "/mnt/usb_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_SYNC)
time.sleep(1)
os.system(CMD_MOUNT)
evh.reset()
time.sleep(1)
time.sleep(1)
except KeyboardInterrupt:
observer.stop()
observer.join()
@Wookie1
Copy link

Wookie1 commented Apr 28, 2019

This doesn't seem to quite work as-is with Raspbian Stretch. Based on some other people's comments, change
CMD_MOUNT = "modprobe g_mass_storage file=/piusb.bin stall=0 ro=1"

To
CMD_MOUNT = "modprobe g_mass_storage file=/piusb.bin stall=0 ro=0 removable=1"

That worked for me. I forked this gist with the modification.

@felsgaertner
Copy link

Is it possible (and how) to add a check for open files to this watchdog, so that the unmount/mount only happens when no files are opened on the emulated stick? I plan to use this on a 3D printer, and I want the print to be finished before the stick is re-installed.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment