#!/usr/bin/env python3
import os
import time
import hal
import linuxcnc
import shutil

check_interval = 3000
source = "/mnt/taglio/CutDocument.txt"
destination = "/mnt/CutDocument.txt"

h = hal.component("file-check")
h.newpin("file-changed", hal.HAL_BIT, hal.HAL_OUT)
h.ready()
# create a connection to the status channel
s = linuxcnc.stat() 
# this is the file being checked for updates (example looks for 'file.txt' in the config folder)
file_path = '/mnt/taglio/CutDocument.txt' 
# wait time in milliseconds between file checks 
check_interval = 1000
# length of output pulse in milliseconds 
pulse_length = 1000 

last_modified = os.path.getmtime(file_path)
check_timer_start = round(time.time()*1000)
h['file-changed'] = False





try:
    while 1:
        s.poll()
        # see if it is time to check the file
        if round(time.time()*1000) >= check_timer_start + check_interval:
            # we don't want to reload when program is running
            if s.task_mode == 2 and s.state == 1: # ie AUTO-mode and 'RCS_DONE'
                current_modified = os.path.getmtime(file_path)
                if current_modified != last_modified:
                    print("File has changed!")
                    shutil.copyfile(source, destination)
                    h['file-changed'] = True
                    pulse_timer_start = round(time.time()*1000)
                    last_modified = current_modified
                if h['file-changed'] and pulse_timer_start + pulse_length <= round(time.time()*1000):
                    h['file-changed'] = False
            # restart the timer for file checking
            check_timer_start = round(time.time()*1000)
except KeyboardInterrupt:
    raise SystemExit
