# coding: utf-8
# python 2 only

# Copyright (c) 2026 TormachTips.com. All rights reserved.
# Licensed under the TormachTips Personal Use License.
# Permission is granted only for private personal use and private personal modification.
# No sharing, publication, distribution, resale, sublicensing, screenshots, code excerpts,
# benchmarks, or videos are permitted without prior written permission.
# Requests:         tormach.1100m@gmail.com
# Information page: https://tormachtips.com/plugins.htm

######################################
##                                  ##
##     Machine Ready Check 0.95     ##
##       www.tormachtips.com        ##
##                                  ##
######################################

# 0.95 - Public beta - 5/2/2026

import os
import glib
import linuxcnc
import constants
import singletons
from ui_hooks import plugin

CURRENT_VER        = "0.95"
SCRIPT_NAME        = "Machine Ready Check"
DESCRIPTION        = "Once per sec, determines if the machined is out of e-stop and homed, then writes OK or NOT OK to the status window."
ENABLED            = 1
DEV_MACHINE        = 0
DEV_MACHINE_FLAG   = "/home/operator/gcode/python/dev_machine.txt"
STATUS_INTERVAL_MS = 1000
REQUIRE_HOMED      = True

class UserPlugin(plugin):
    def __init__(self):
        plugin.__init__(self, '%s %s' % (SCRIPT_NAME, CURRENT_VER))
        dev_machine_found = os.path.exists(DEV_MACHINE_FLAG)
        if dev_machine_found:
            plugin_enabled = DEV_MACHINE
        else:
            plugin_enabled = ENABLED
        if plugin_enabled:
            self.error_handler.write("[%s] Loaded v%s" % (SCRIPT_NAME, CURRENT_VER), constants.ALARM_LEVEL_LOW)
            glib.timeout_add(STATUS_INTERVAL_MS, self.status_timer)
            return
        if dev_machine_found:
            self.error_handler.write("[%s] Dev machine found. Plugin loaded, but disabled by DEV_MACHINE." % SCRIPT_NAME, constants.ALARM_LEVEL_QUIET)
        else:
            self.error_handler.write("[%s] Plugin loaded, but is disabled. To enable it, open the script, find ENABLED = 0, and change it to ENABLED = 1." % SCRIPT_NAME, constants.ALARM_LEVEL_QUIET)
    
    def machine_ready_to_move(self):
        try:
            ui = singletons.g_Machine
            if not ui:
                return False
            if not hasattr(ui, "status") or not ui.status:
                return False
            try:
                ui.status.poll()
            except:
                pass
            try:
                if not ui.hal["machine-ok"]:
                    return False
            except:
                return False
            if ui.status.task_state != linuxcnc.STATE_ON:
                return False
            if REQUIRE_HOMED:
                try:
                    if not ui.status.homed[0]:
                        return False
                    if not ui.status.homed[1]:
                        return False
                    if not ui.status.homed[2]:
                        return False
                except:
                    return False
            return True
        except:
            return False
    
    def status_timer(self):
        try:
            if self.machine_ready_to_move():
                self.error_handler.write("[%s] OK" % SCRIPT_NAME, constants.ALARM_LEVEL_LOW)
            else:
                self.error_handler.write("[%s] NOT OK" % SCRIPT_NAME, constants.ALARM_LEVEL_LOW)
        except Exception as e:
            self.error_handler.write("[%s] Error: %s" % (SCRIPT_NAME, str(e)), constants.ALARM_LEVEL_LOW)
        return True
        
DESCRIPTION_LONG = """This is a simple script I created mostly for internal use. It just checks if the machine is out of e-stop, homed and ready for work. If so, it spams "OK" to the status window. If not, "NOT OK". To be used for other projects."""