def __init__(self, **kwargs):
     self.dropped = False
     self.breaked = False
     self.completed = threading.Event()
     self.finished = threading.Event()
     self.action_completed = event.EventEmitter()
     self.action_started = event.EventEmitter()
     self.caching = False
     self.is_pause = False
     self.is_moving = False
     self.error = False
class EmulatorSender(object):

    indexed = event.EventEmitter()
    queued = event.EventEmitter()
    completed = event.EventEmitter()
    started = event.EventEmitter()
    dropped = event.EventEmitter()
    mcu_reseted = event.EventEmitter()
    error = event.EventEmitter()
    protocol_error = event.EventEmitter()

    has_slots = threading.Event()

    def __init__(self):
        self.id = 0
        self.has_slots.set()

    def send_command(self, command, wait=True):
        self.id += 1
        self.indexed(self.id)
        cmd = ("N%i " % self.id) + command + "\n"
        print("Command %s" % cmd)
        self.queued(self.id)
        oid = self.id
        self.started(self.id)
        self.completed(self.id, {})
        return oid

    def reset(self):
        self.id = 0
    def __init__(self, port, bdrate, timeout):
        self.__id = 0
        self.__qans = threading.Event()
        self.__reseted = False
        self.__slots = event.EventEmitter()
        self.__finish_event = threading.Event()

        self.port = port
        self.baudrate = bdrate
        self.timeout = timeout
        self.__ser = serial.Serial(self.port,
                                   self.baudrate,
                                   bytesize=8,
                                   parity='N',
                                   stopbits=1,
                                   rtscts=False,
                                   dsrdtr=False)

        self.__listener = self.SerialReceiver(self.__ser, self.__finish_event,
                                              self.completed, self.started,
                                              self.__slots, self.dropped,
                                              self.queued, self.protocol_error,
                                              self.__reseted_ev, self.error)
        self.__reseted_ev += self.__on_reset
        self.__slots += self.__on_slots
        self.__listener.start()
        self.has_slots.set()
    def __init__(self, ethname, timeout=0, debug=False):
        self.__id = 0
        self.__ethertype = bytes([0xFE, 0xFE])
        self.__remote = {
            "inited" : False,
            "mac" : bytes([255,255,255,255,255,255])
        }
        self.__localmac = self.__getHwAddr(ethname)
        self.__qans = threading.Event()
        self.__reseted = False
        self.__slots = event.EventEmitter()
        self.__finish_event = threading.Event()

        self.__sock = socket.socket(socket.AF_PACKET, socket.SOCK_RAW)
        self.__sock.bind((ethname, socket.htons(0xFEFE)))
        self.timeout = timeout

        self.__listener = self.EthernetReceiver(self.__sock, self.__remote, self.__finish_event,
                                                self.completed, self.started, self.__slots,
                                                self.dropped, self.queued,
                                                self.protocol_error, self.__reseted_ev, self.error)
        self.__reseted_ev += self.__on_reset
        self.__slots += self.__on_slots
        self.__listener.start()
        self.has_slots.set()
    def __init__(self, table_sender, spindle_sender):
        print("Creating machine...")
        self.registers = {"tools": {}}
        self.is_running = False
        self.is_finished = False
        self.table_sender = table_sender
        self.spindle_sender = spindle_sender
        self.running = event.EventEmitter()
        self.paused = event.EventEmitter()
        self.finished = event.EventEmitter()
        self.error = event.EventEmitter()
        self.line_selected = event.EventEmitter()
        self.tool_selected = event.EventEmitter()
        self.on_coordinates = event.EventEmitter()

        self.reset = False
        self.action_rdy = threading.Event()
        self.__table_reseted_ev = threading.Event()
        self.current_wait = None
        self.c_actions = []
        self.nc_action = None
        self.opt = Optimizer(common.config.JERKING, common.config.ACCELERATION,
                             common.config.MAXFEED)
        # loaded program
        self.user_program = None
        self.user_frames = []
        # actual program
        self.program = None
        self.state = None
        self.builder = None
        # special programs
        self.empty_program = pr.Program(self.table_sender, self.spindle_sender)
        # states
        self.previous_state = None
        self.work_init(self.empty_program)
        self.table_sender.mcu_reseted += self.__table_reseted
        # current states
        self.runtime_state = runtimestate.RuntimeState({
            "x": 0,
            "y": 0,
            "z": 0
        }, euclid3.Vector3())
        print("done")
Exemple #6
0
 def __init__(self, **kwargs):
     action.InstantAction.__init__(self, **kwargs)
     self.paused = event.EventEmitter()
     self.is_pause = True
class SerialSender(object):
    class SerialReceiver(threading.Thread):
        def __init__(self, ser, finish_event, ev_completed, ev_started,
                     ev_slots, ev_dropped, ev_queued, ev_protocolerror,
                     ev_mcu_reseted, ev_error):
            threading.Thread.__init__(self)
            self.ser = ser
            self.finish_event = finish_event

            self.ev_completed = ev_completed
            self.ev_started = ev_started
            self.ev_slots = ev_slots
            self.ev_queued = ev_queued
            self.ev_dropped = ev_dropped
            self.ev_protocolerror = ev_protocolerror
            self.ev_mcu_reseted = ev_mcu_reseted
            self.ev_error = ev_error

        def run(self):
            while not self.finish_event.is_set():
                resp = None
                try:
                    resp = self.ser.readline()
                except Exception as e:
                    print("Serial port read error", e)
                    self.ev_protocolerror(True, "Serial port read error")
                    break

                try:
                    ans = resp.decode("ascii")
                except:
                    print("Can not decode answer: ", e)
                    self.ev_protocolerror(False, resp)
                    continue

                ans = str(ans).strip()
                print("Received answer: [%s], len = %i" % (ans, len(ans)))

                evt = answer.parse_answer(ans)
                if evt["result"] == "ok":
                    if evt["event"] == "queue":
                        self.ev_slots(evt["action"], evt["slots"])
                        self.ev_queued(evt["action"])
                    elif evt["event"] == "drop":
                        self.ev_slots(evt["action"], evt["slots"])
                        self.ev_dropped(evt["action"])
                    elif evt["event"] == "start":
                        self.ev_slots(evt["action"], evt["slots"])
                        self.ev_started(evt["action"])
                    elif evt["event"] == "complete":
                        self.ev_slots(evt["action"], evt["slots"])
                        self.ev_completed(evt["action"], evt["response"])
                    elif evt["event"] == "init":
                        self.ev_mcu_reseted()
                    elif evt["event"] == "error":
                        self.ev_error(evt["msg"])

    indexed = event.EventEmitter()
    queued = event.EventEmitter()
    completed = event.EventEmitter()
    dropped = event.EventEmitter()
    started = event.EventEmitter()
    protocol_error = event.EventEmitter()
    mcu_reseted = event.EventEmitter()
    error = event.EventEmitter()

    __reseted_ev = event.EventEmitter()
    has_slots = threading.Event()

    def __init__(self, port, bdrate, timeout):
        self.__id = 0
        self.__qans = threading.Event()
        self.__reseted = False
        self.__slots = event.EventEmitter()
        self.__finish_event = threading.Event()

        self.port = port
        self.baudrate = bdrate
        self.timeout = timeout
        self.__ser = serial.Serial(self.port,
                                   self.baudrate,
                                   bytesize=8,
                                   parity='N',
                                   stopbits=1,
                                   rtscts=False,
                                   dsrdtr=False)

        self.__listener = self.SerialReceiver(self.__ser, self.__finish_event,
                                              self.completed, self.started,
                                              self.__slots, self.dropped,
                                              self.queued, self.protocol_error,
                                              self.__reseted_ev, self.error)
        self.__reseted_ev += self.__on_reset
        self.__slots += self.__on_slots
        self.__listener.start()
        self.has_slots.set()

    def __on_reset(self):
        self.has_slots.set()
        self.mcu_reseted()

    def __on_slots(self, Nid, Q):
        Nid = int(Nid)
        if Q == 0:
            self.has_slots.clear()
        else:
            self.has_slots.set()
        if Nid != self.__id:
            return

    def send_command(self, command, wait=True):
        self.__id += 1
        self.__reseted = False
        self.indexed(self.__id)
        cmd = ("N%i " % self.__id) + command
        encoded = bytes(cmd, "ascii")
        s = sum(encoded)
        crc = bytes("*%X" % s, "ascii")
        msg = encoded + crc + b'\n'
        print("Sending command %s" % msg)
        self.__ser.write(msg)
        self.__ser.flush()
        oid = self.__id
        return oid

    def close(self):
        self.__finish_event.set()
        self.__ser.close()

    def clean(self):
        self.__reseted = True
        self.__qans.set()

    def reset(self):
        pass
class EthernetSender(object):

    class EthernetReceiver(threading.Thread):

        def __init__(self, sock, remote, finish_event,
                    ev_completed, ev_started,
                    ev_slots, ev_dropped, ev_queued,
                    ev_protocolerror, ev_mcu_reseted, ev_error):
            threading.Thread.__init__(self)
            self.sock = sock
            self.remote = remote
            self.finish_event = finish_event

            self.ev_completed = ev_completed
            self.ev_started = ev_started
            self.ev_slots = ev_slots
            self.ev_queued = ev_queued
            self.ev_dropped = ev_dropped
            self.ev_protocolerror = ev_protocolerror
            self.ev_mcu_reseted = ev_mcu_reseted
            self.ev_error = ev_error

        def run(self):
            print("START RECEIVER")
            while not self.finish_event.is_set():
                resp = None
                try:
                    resp = self.sock.recv(1500)
                except Exception as e:
                    print("Ethernet read error", e)
                    self.ev_protocolerror(True, "Ethernet read error")
                    break
                #dst = resp[0:6]
                src = resp[6:12]
                ethtype = resp[12]*256 +resp[13] 
                #length = resp[14]*256 + resp[15]
                msg = resp[16:]
                if ethtype != 0xFEFE:
                    continue
                self.remote["mac"] = src
                try:
                    ans = msg.decode("ascii").replace("\x00", "")
                except:
                    print("Can not decode answer: ", e)
                    self.ev_protocolerror(False, resp)
                    continue

                print("Received answer: [%s], len = %i" % (ans, len(ans)))
                
                evt = answer.parse_answer(ans)
                if evt["result"] == "ok":
                    if evt["event"] == "queue":
                        self.ev_slots(evt["action"], evt["slots"])
                        self.ev_queued(evt["action"])
                    elif evt["event"] == "drop":
                        self.ev_slots(evt["action"], evt["slots"])
                        self.ev_dropped(evt["action"])
                    elif evt["event"] == "start":
                        self.ev_slots(evt["action"], evt["slots"])
                        self.ev_started(evt["action"])
                    elif evt["event"] == "complete":
                        self.ev_slots(evt["action"], evt["slots"])
                        self.ev_completed(evt["action"], evt["response"])
                    elif evt["event"] == "init":
                        self.ev_mcu_reseted()
                    elif evt["event"] == "error":
                        self.ev_error(evt["msg"])
                else:
                    print("problem", evt)

    indexed = event.EventEmitter()
    queued = event.EventEmitter()
    completed = event.EventEmitter()
    dropped = event.EventEmitter()
    started = event.EventEmitter()
    protocol_error = event.EventEmitter()
    mcu_reseted = event.EventEmitter()
    error = event.EventEmitter()

    __reseted_ev = event.EventEmitter()
    has_slots = threading.Event()
    
    @staticmethod
    def __getHwAddr(ifname):
        s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
        info = fcntl.ioctl(s.fileno(), 0x8927,  struct.pack('256s', bytes(ifname, 'utf-8')[:15]))
        return info[18:24]

    def __init__(self, ethname, timeout=0, debug=False):
        self.__id = 0
        self.__ethertype = bytes([0xFE, 0xFE])
        self.__remote = {
            "inited" : False,
            "mac" : bytes([255,255,255,255,255,255])
        }
        self.__localmac = self.__getHwAddr(ethname)
        self.__qans = threading.Event()
        self.__reseted = False
        self.__slots = event.EventEmitter()
        self.__finish_event = threading.Event()

        self.__sock = socket.socket(socket.AF_PACKET, socket.SOCK_RAW)
        self.__sock.bind((ethname, socket.htons(0xFEFE)))
        self.timeout = timeout

        self.__listener = self.EthernetReceiver(self.__sock, self.__remote, self.__finish_event,
                                                self.completed, self.started, self.__slots,
                                                self.dropped, self.queued,
                                                self.protocol_error, self.__reseted_ev, self.error)
        self.__reseted_ev += self.__on_reset
        self.__slots += self.__on_slots
        self.__listener.start()
        self.has_slots.set()

    def __on_reset(self):
        self.has_slots.set()
        self.mcu_reseted()

    def __on_slots(self, Nid, Q):
        Nid = int(Nid)
        if Q == 0:
            self.has_slots.clear()
        else:
            self.has_slots.set()
        if Nid != self.__id:
            return

    def send_command(self, command, wait=True):
        self.__id += 1
        self.__reseted = False
        self.indexed(self.__id)
        cmd = ("N%i " % self.__id) + command
        encoded = bytes(cmd, "ascii")
        s = sum(encoded)
        crc = bytes("*%X" % s, "ascii")
        msg = encoded + crc + b'\n'
        msglen = len(msg)
        lenb = bytes([int(msglen / 256), int(msglen % 256)])
        print("Sending command %s" % msg)
        frame = self.__remote["mac"] + self.__localmac + self.__ethertype + lenb + msg
        self.__sock.send(frame)
        oid = self.__id
        return oid

    def close(self):
        self.__finish_event.set()
        self.__sock.close()

    def clean(self):
        self.__reseted = True
        self.__qans.set()

    def reset(self):
        self.__remote["mac"] = bytes([255,255,255,255,255,255])
 def __init__(self, tool, **kwargs):
     action.InstantAction.__init__(self, **kwargs)
     self.tool_changed = event.EventEmitter()
     self.tool = tool
     self.is_pause = True
        def __init__(self, parent):
            self.loaded = event.EventEmitter()
            self.reset_clicked = event.EventEmitter()
            self.start_clicked = event.EventEmitter()
            self.continue_clicked = event.EventEmitter()
            self.pause_clicked = event.EventEmitter()
            self.stop_clicked = event.EventEmitter()
            self.home_clicked = event.EventEmitter()
            self.probe_clicked = event.EventEmitter()
            self.command_entered = event.EventEmitter()

            self.xp_clicked = event.EventEmitter()
            self.xm_clicked = event.EventEmitter()

            self.yp_clicked = event.EventEmitter()
            self.ym_clicked = event.EventEmitter()

            self.zp_clicked = event.EventEmitter()
            self.zm_clicked = event.EventEmitter()

            wx.Frame.__init__(self,
                              parent,
                              title="CNC Control",
                              size=(800, 600))
            menubar = wx.MenuBar()
            fileMenu = wx.Menu()
            openItem = fileMenu.Append(wx.ID_OPEN, 'Open', 'Open G-Code')
            quitItem = fileMenu.Append(wx.ID_EXIT, 'Quit', 'Quit application')
            menubar.Append(fileMenu, '&File')
            self.SetMenuBar(menubar)
            self.Bind(wx.EVT_MENU, self.OnQuit, quitItem)
            self.Bind(wx.EVT_MENU, self.OnOpen, openItem)

            panel = wx.Panel(self)
            hbox = wx.BoxSizer(wx.HORIZONTAL)
            panel.SetSizer(hbox)

            #region code area

            code_panel = wx.Panel(panel)
            hbox.Add(code_panel, wx.ID_ANY, wx.EXPAND, 0)
            code_sizer = wx.BoxSizer(wx.VERTICAL)
            code_panel.SetSizer(code_sizer)

            #region code
            self.code = wx.ListCtrl(code_panel,
                                    style=wx.LC_REPORT | wx.BORDER_SUNKEN)
            self.code.InsertColumn(0, "", width=32)
            self.code.InsertColumn(1, "", width=500)
            self.font = wx.Font(13, wx.MODERN, wx.NORMAL, wx.NORMAL, False,
                                u'Monospace')
            self.old_hl = None
            code_sizer.Add(self.code, wx.ID_ANY, flag=wx.EXPAND)
            #endregion

            code_sizer.Add((-1, 5))

            #region code
            self.cmdhist = wx.TextCtrl(code_panel,
                                       style=wx.TE_MULTILINE | wx.TE_READONLY
                                       | wx.HSCROLL | wx.TE_RICH)
            code_sizer.Add(self.cmdhist, wx.ID_ANY, flag=wx.EXPAND)
            #endregion

            #region command
            cmdpanel = wx.Panel(code_panel)
            cmdpanel_sizer = wx.BoxSizer(wx.HORIZONTAL)
            cmdpanel.SetSizer(cmdpanel_sizer)
            code_sizer.Add(cmdpanel, flag=wx.EXPAND)

            self.command = wx.TextCtrl(cmdpanel)
            self.command.Bind(wx.EVT_KEY_DOWN, self.__kd)
            cmdpanel_sizer.Add(self.command, wx.ID_ANY, flag=wx.EXPAND)

            self.send_command = wx.Button(cmdpanel, label='>', size=(32, -1))
            self.send_command.Bind(wx.EVT_BUTTON, self.__execute)
            cmdpanel_sizer.Add(self.send_command)
            #endregion

            #endregion

            #region control area
            control_panel = wx.Panel(panel)
            control_sizer = wx.BoxSizer(wx.VERTICAL)
            control_panel.SetSizer(control_sizer)

            hbox.Add(control_panel, flag=wx.LEFT | wx.RIGHT, border=15)

            vcmdpanel = wx.Panel(control_panel)
            control_sizer.Add(vcmdpanel)
            vcmdsizer = wx.BoxSizer(wx.HORIZONTAL)
            vcmdpanel.SetSizer(vcmdsizer)

            #region move control

            movegrid = wx.Panel(vcmdpanel)
            vcmdsizer.Add(movegrid)

            movegridsizer = wx.GridBagSizer(vgap=5, hgap=5)
            movegrid.SetSizer(movegridsizer)

            self.xp = wx.Button(movegrid, label=">")
            movegridsizer.Add(self.xp, (1, 2))
            self.xp.Bind(wx.EVT_BUTTON, self.__xp)

            self.xm = wx.Button(movegrid, label="<")
            movegridsizer.Add(self.xm, (1, 0))
            self.xm.Bind(wx.EVT_BUTTON, self.__xm)

            self.yp = wx.Button(movegrid, label="^")
            movegridsizer.Add(self.yp, (0, 1))
            self.yp.Bind(wx.EVT_BUTTON, self.__yp)

            self.ym = wx.Button(movegrid, label="v")
            movegridsizer.Add(self.ym, (2, 1))
            self.ym.Bind(wx.EVT_BUTTON, self.__ym)

            self.zp = wx.Button(movegrid, label="Up")
            movegridsizer.Add(self.zp, (3, 1))
            self.zp.Bind(wx.EVT_BUTTON, self.__zp)

            self.zm = wx.Button(movegrid, label="Down")
            movegridsizer.Add(self.zm, (4, 1))
            self.zm.Bind(wx.EVT_BUTTON, self.__zm)
            #endregion move control

            vcmdsizer.Add((10, -1))

            #region buttons
            button_panel = wx.Panel(vcmdpanel)
            btnsizer = wx.BoxSizer(wx.VERTICAL)
            vcmdsizer.Add(button_panel)
            button_panel.SetSizer(btnsizer)

            self.start_btn = wx.Button(button_panel, label='Start')
            btnsizer.Add(self.start_btn)
            self.start_btn.Bind(wx.EVT_BUTTON, self.__start)

            btnsizer.Add((-1, 5))

            self.pause_btn = wx.Button(button_panel, label='Pause')
            btnsizer.Add(self.pause_btn)
            self.pause_btn.Bind(wx.EVT_BUTTON, self.__pause)

            btnsizer.Add((-1, 5))

            self.continue_btn = wx.Button(button_panel, label='Continue')
            btnsizer.Add(self.continue_btn)
            self.continue_btn.Bind(wx.EVT_BUTTON, self.__continue)

            btnsizer.Add((-1, 5))

            self.stop_btn = wx.Button(button_panel, label='Stop')
            btnsizer.Add(self.stop_btn)
            self.stop_btn.Bind(wx.EVT_BUTTON, self.__stop)

            btnsizer.Add((-1, 20))

            self.reset_btn = wx.Button(button_panel, label='Reset')
            self.reset_btn.SetBackgroundColour(wx.Colour(255, 0, 0))
            self.reset_btn.SetForegroundColour(wx.Colour(255, 255, 255))
            self.reset_btn.SetFont(wx.Font(18, wx.DEFAULT, wx.NORMAL, wx.BOLD))
            btnsizer.Add(self.reset_btn)
            self.reset_btn.Bind(wx.EVT_BUTTON, self.__reset)

            btnsizer.Add((-1, 20))

            self.home_btn = wx.Button(button_panel, label='Home XYZ')
            btnsizer.Add(self.home_btn)
            self.home_btn.Bind(wx.EVT_BUTTON, self.__home)

            btnsizer.Add((-1, 5))

            self.probe_btn = wx.Button(button_panel, label='Probe Z')
            btnsizer.Add(self.probe_btn)
            self.probe_btn.Bind(wx.EVT_BUTTON, self.__probe)
            #endregion

            control_sizer.Add((-1, 15))

            #region status region
            status_panel = wx.Panel(control_panel)
            status_sizer = wx.BoxSizer(wx.VERTICAL)
            control_sizer.Add(status_panel)
            status_panel.SetSizer(status_sizer)

            lb = wx.StaticText(status_panel, label="Coordinates")
            status_sizer.Add(lb)

            self.crds = wx.grid.Grid(status_panel)
            status_sizer.Add(self.crds)
            self.crds.CreateGrid(4, 3)
            for i in range(3):
                for j in range(3):
                    self.crds.SetReadOnly(i, j, True)

            self.crds.SetColLabelValue(0, "HW")
            self.crds.SetColLabelValue(1, "Global")
            self.crds.SetColLabelValue(2, "Current")

            self.crds.SetRowLabelValue(0, "CS")
            self.crds.SetRowLabelValue(1, "X")
            self.crds.SetRowLabelValue(2, "Y")
            self.crds.SetRowLabelValue(3, "Z")

            self.crds.DisableRowResize(0)
            self.crds.DisableRowResize(1)
            self.crds.DisableRowResize(2)
            self.crds.DisableRowResize(3)

            self.crds.DisableColResize(0)
            self.crds.DisableColResize(1)
            self.crds.DisableColResize(2)

            self.crds.SetCellBackgroundColour(0, 0, wx.Colour("lightgrey"))
            self.crds.SetCellBackgroundColour(0, 1, wx.Colour("lightgrey"))