G71 , ... (remap)

Обсуждение установки, настройки и использования LinuxCNC. Вопросы по Gкоду.
pkasy
Мастер
Сообщения: 1139
Зарегистрирован: 15 мар 2013, 09:39
Репутация: 45
Откуда: Владивосток

Re: G71 , ... (remap)

Сообщение pkasy »

нужно работать в том, что указал пользователь.
кому что удобнее. мне - диаметр. Васе - радиус.
а ты должен подстроиться.
nkp
Мастер
Сообщения: 8340
Зарегистрирован: 28 ноя 2011, 00:25
Репутация: 1589
Контактная информация:

Re: G71 , ... (remap)

Сообщение nkp »

pkasy писал(а):а ты должен подстроиться.
та не проблема :)
подстроимся даже к световым годам ;)
=============================================
картинка по поводу "в голове делить на 2"
вроде как интерфейс сам делит и выводит нам:
Выделение_009.png (4272 просмотра) <a class='original' href='./download/file.php?id=97216&sid=3e4e03a161d349c3c28b98b7b4adc80b&mode=view' target=_blank>Загрузить оригинал (63.92 КБ)</a>
Последний раз редактировалось nkp 09 дек 2016, 18:30, всего редактировалось 1 раз.
Аватара пользователя
aegis
Мастер
Сообщения: 3171
Зарегистрирован: 22 мар 2012, 06:59
Репутация: 1810
Настоящее имя: Михайло
Откуда: Україна, Конотоп=>Запоріжжя=>Харьків

Re: G71 , ... (remap)

Сообщение aegis »

nkp, ну а когда контур задаешь что должен в уме делить?
нікому нічого не нав'язую.
nkp
Мастер
Сообщения: 8340
Зарегистрирован: 28 ноя 2011, 00:25
Репутация: 1589
Контактная информация:

Re: G71 , ... (remap)

Сообщение nkp »

aegis писал(а):nkp, ну а когда контур задаешь что должен в уме делить?
тебе видней - ты практик ;)
но вроде как в HAAS (токарка) вообще нет G7-G8
(а если и правда нет - то какой режим оставлен? диаметр?)
Аватара пользователя
aegis
Мастер
Сообщения: 3171
Зарегистрирован: 22 мар 2012, 06:59
Репутация: 1810
Настоящее имя: Михайло
Откуда: Україна, Конотоп=>Запоріжжя=>Харьків

Re: G71 , ... (remap)

Сообщение aegis »

nkp, думаю что эти параметры на лету могут не меняться а быть спрятаны где-то в меню настройки
нікому нічого не нав'язую.
jo_key
Почётный участник
Почётный участник
Сообщения: 262
Зарегистрирован: 19 сен 2011, 14:49
Репутация: 30
Настоящее имя: Евгений
Откуда: Украина, Харьков
Контактная информация:

Re: G71 , ... (remap)

Сообщение jo_key »

blank - обычно называется у них заготовка
pkasy
Мастер
Сообщения: 1139
Зарегистрирован: 15 мар 2013, 09:39
Репутация: 45
Откуда: Владивосток

Re: G71 , ... (remap)

Сообщение pkasy »

nkp писал(а):вроде как интерфейс сам делит и выводит нам:
нажми F5 и посмотри, что в данный момент у тебя активно - G7 или G8
pkasy
Мастер
Сообщения: 1139
Зарегистрирован: 15 мар 2013, 09:39
Репутация: 45
Откуда: Владивосток

Re: G71 , ... (remap)

Сообщение pkasy »

проверяй опять.

Код: Выделить всё

G71.2 P6 Q12  D1 K0.5 I1.0 F0.05 J0 S1000.0 L0.0 T1
(N6 G1 X   0.000 Z   0.000)
(N7 G1 X   3.4 Z 0)
(N8 G1 X   4 Z -0.3)
(N9 G1 X  4 Z -8)
(N10 G1 X  8  Z -8)
(N11 G1 X  8  Z -18)
(N12 G1 X  12  Z -18)
nkp
Мастер
Сообщения: 8340
Зарегистрирован: 28 ноя 2011, 00:25
Репутация: 1589
Контактная информация:

Re: G71 , ... (remap)

Сообщение nkp »

pkasy писал(а):проверяй опять.
что конкретно ?
у меня открывается нормально: если ты про G7 - то работа в диаметрах пока не доделана,
работает все в радиусах...
зы
у меня конечно "крайняя" версия с github
pkasy
Мастер
Сообщения: 1139
Зарегистрирован: 15 мар 2013, 09:39
Репутация: 45
Откуда: Владивосток

Re: G71 , ... (remap)

Сообщение pkasy »

понятно. когда будет в G7?
Аватара пользователя
aegis
Мастер
Сообщения: 3171
Зарегистрирован: 22 мар 2012, 06:59
Репутация: 1810
Настоящее имя: Михайло
Откуда: Україна, Конотоп=>Запоріжжя=>Харьків

Re: G71 , ... (remap)

Сообщение aegis »

pkasy, чего на nkp наскочил? если есть время - делает, нет - не делает
нікому нічого не нав'язую.
pkasy
Мастер
Сообщения: 1139
Зарегистрирован: 15 мар 2013, 09:39
Репутация: 45
Откуда: Владивосток

Re: G71 , ... (remap)

Сообщение pkasy »

во-первых, не наскочил.
во-вторых, это продолжение переписки в личке.
в третьих, могу и сам исправить. делов-то.
nkp
Мастер
Сообщения: 8340
Зарегистрирован: 28 ноя 2011, 00:25
Репутация: 1589
Контактная информация:

Re: G71 , ... (remap)

Сообщение nkp »

pkasy писал(а):понятно. когда будет в G7?
ты знаешь,а вот сразу так у меня и не получилось ;) (подстроить)
с одними линейными перемещениями еще что то вышло,а вот с дугами пока засада...
так что любые советы,подсказки,пинки в нужное направление приветствуются,
а код - и подавно))
Аватара пользователя
aegis
Мастер
Сообщения: 3171
Зарегистрирован: 22 мар 2012, 06:59
Репутация: 1810
Настоящее имя: Михайло
Откуда: Україна, Конотоп=>Запоріжжя=>Харьків

Re: G71 , ... (remap)

Сообщение aegis »

nkp, что мешает ввести еще одну переменную и просто удваивать ее?
нікому нічого не нав'язую.
pkasy
Мастер
Сообщения: 1139
Зарегистрирован: 15 мар 2013, 09:39
Репутация: 45
Откуда: Владивосток

Re: G71 , ... (remap)

Сообщение pkasy »

nkp писал(а):ты знаешь,а вот сразу так у меня и не получилось
получилось. я ж пользуюсь твоей старой версией. которая не все заполняет черновыми проходами, но работает в G7
Аватара пользователя
Nick
Мастер
Сообщения: 22776
Зарегистрирован: 23 ноя 2009, 16:45
Репутация: 1735
Заслуга: Developer
Откуда: Gatchina, Saint-Petersburg distr., Russia
Контактная информация:

Re: G71 , ... (remap)

Сообщение Nick »

aegis писал(а):nkp, что мешает ввести еще одну переменную и просто удваивать ее?
вот-вот можешь везде где выводишь координату по X дописать *g7, а сам этот g7 где-нибудь в коде задать g7 = 1 if ... else 2
nkp
Мастер
Сообщения: 8340
Зарегистрирован: 28 ноя 2011, 00:25
Репутация: 1589
Контактная информация:

Re: G71 , ... (remap)

Сообщение nkp »

множитель d_m (diametr mode) введен на 15-й секунде возникновения проблемы :hehehe:
но вот так просто - взять его и тупо везде проставить не получится(я даже сам себе не поверил - и попробовал ;) )
===================
вот вариант: как я выше писал - работает с линиями - с дугами вечером поразбираюсь

Код: Выделить всё

# --*-- coding:utf-8 --*--
import linuxcnc
import re
from math import *
import traceback
from interpreter import *
from emccanon import MESSAGE

throw_exceptions = 1 # raises InterpreterException if execute() or read() fail
    
def pars(array,reg ,lines): 
    a=array.insert(0,(float(re.search(reg,lines, re.I).group(1))))
def cathetus(c,b):
    a = sqrt(abs(c*c - b*b))
    return a 
def hip(a,b):
    c = sqrt(abs(a*a + b*b))
    return c
def intersection_line_arc(G,Mz1,Mx1,Mz2,Mx2,centreZ,centreX,rad):    
    if (Mz2-Mz1)!=0:
        K=(Mx2-Mx1)/(Mz2-Mz1)
        B=-(K*Mz1-Mx1)           
        a = 1 + K**2 
        b = -2*centreZ + 2*K*B -2*K*centreX  
        c = -rad**2 + (B-centreX)**2 + centreZ**2 
        D = b**2 - 4*a*c 
        if D < 0: 
          print 'D<0' 
        z1 = (-b-sqrt(D))/(2*a) 
        z2 = (-b+sqrt(D))/(2*a)
        if G==3:
            if Mz2 < z1 < Mz1:
              pointZ1 = z1   
              pointX1 = K*z1+B
              return  pointZ1,pointX1
            else:
              pointZ1 = z2
              pointX1 = K*z2+B
              return  pointZ1,pointX1
        if G==2:
            if Mz2 < z1 < Mz1:
              pointZ1 = z2 
              pointX1 = K*z2+B
              return  pointZ1,pointX1
            else:
              pointZ1 = z1
              pointX1 = K*z1+B
              return  pointZ1,pointX1 
    else:
        pointZ1 = Mz1 
        pointX1 = centreX-(cathetus(rad,centreZ))
        return  pointZ1,pointX1              
def intersection_arc_arc(x1,z1,r1,x2,z2,r2,Px,Pz):
    d=sqrt( pow(abs(x1-x2),2) + pow(abs(z1-z2),2))
    if(d > r1+r2): 
        return
    a= (r1*r1 - r2*r2 + d*d ) / (2*d)
    h= sqrt( pow(r1,2) - pow(a,2))
    x0 = x1 + a*( x2 - x1 ) / d
    z0 = z1 + a*( z2 - z1 ) / d;
    ix1= x0 + h*( z2 - z1 ) / d
    iz1= z0 - h*( x2 - x1 ) / d
    ix2= x0 - h*( z2 - z1 ) / d
    iz2= z0 + h*( x2 - x1 ) / d
    if(a == r1 ) :
        intscX = ix2
        intscZ = iz2
        return intscX , intscZ 

    l1= sqrt((Px - ix1)**2+(Pz - iz1)**2)
    l2= sqrt((Px - ix2)**2+(Pz - iz2)**2)
    if l1>l2:
        intscX = ix2
        intscZ = iz2
    else:
       intscX = ix1
       intscZ = iz1              
    return  intscX , intscZ
     
def intersection_line_line(x1_1, z1_1, x1_2, z1_2):
    A1 = z1_1 - z1_2
    B1 = x1_2 - x1_1
    C1 = x1_1*z1_2 - x1_2*z1_1
    A2 = z2_1 - z2_2
    B2 = x2_2 - x2_1
    C2 = x2_1*z2_2 - x2_2*z2_1
     
    if B1*A2 - B2*A1 and A1:
        z = (C2*A1 - C1*A2) / (B1*A2 - B2*A1)
        x = (-C1 - B1*z) / A1
    elif B1*A2 - B2*A1 and A2:
        z = (C2*A1 - C1*A2) / (B1*A2 - B2*A1)
        x = (-C2 - B2*z) / A2    
    else:
        print 'нет пересечения '
        return
    if min(x1_1, x1_2) <= x <= max(x1_1, x1_2):
        return x, z 
                                      
def papp(n,G,x,z,App=[],r=None,xc=None,zc=None):
    App.append([])
    App[n].append(G)
    App[n].append(App[n-1][3])
    App[n].append(App[n-1][4])                                               
    App[n].append(x)
    App[n].append(z)
    if G>1:
        App[n].append(r)
        App[n].append(xc)
        App[n].append(zc)
    return App 
def prog(array,G,x,z,r=None):
    ser=' '
    string=ser.join(['G1','X',str(x),'Z',str(z)])
    if G==2: 
        string=ser.join(['G2','X',str(x),'Z',str(z),'R',str(r)])
    if G==3: 
        string=ser.join(['G3','X',str(x),'Z',str(z),'R',str(r)])        
    return array.append(string)                
#################################################-----G71.2
def g712(self, **words):
    """ remap code G71.2 """
    p = int(words['p'])    
    q = int(words['q'])
    d = float(words['d'])
    offset = float(words['k'])
    
    if words.has_key('s'):
        rsv1 = float(words['s'])
    if words.has_key('l'):
        rsv2 = float(words['l'])
    only_finishing_cut = 0    
    if words.has_key('j'):
        only_finishing_cut = int(words['j'])
    quantity = 1    
    if words.has_key('i'):
        quantity = int(words['i'])
    tool = 2
    if words.has_key('t'):
        tool = int(words['t'])
    if words.has_key('f'):    
        feed_rate = float(words['f'])
    s = linuxcnc.stat() 
    s.poll()
    #backangle  =  s.tool_table #TODO 
    #frontangle =  s.tool_table
    filename = s.file
    f = open(filename, "r")
    lines = f.readlines()

    line_or_arc = []
    coordZ = []
    coordX = []
    coordI = []
    coordK = []
    coordR = []
    s.poll()
    x = 0
    diameter_mode = 0 
    while x < len(lines):
        if re.search("\s*G0?7[^0-9]", lines[x], re.I):
            diameter_mode = 1
        if re.search("\s*F\d", lines[x], re.I) and not re.search("G71",lines[x].upper()) :
            feed_rate=float(re.search("F\s*([0-9.]+)",lines[x], re.I).group(1))
        if  re.search("^\s*[(]\s*N\d", lines[x], re.I):
            if not re.search("[^\(\)\.\-\+NGZXRIK\d\s]",lines[x].upper()):
                num = int(re.search("N\s*([0-9.]+)",lines[x], re.I).group(1))
                if num >= p and num <= q:
                    ins = line_or_arc.insert(0,(int(re.search("G\s*([0-4.]+)",lines[x], re.I).group(1))))
                    ins = pars(coordZ,"Z\s*([-0-9.]+)",lines[x])
                    ins = pars(coordX,"X\s*([-0-9.]+)",lines[x])                    
                    if  re.search("[I]", lines[x]):
                        ins = pars(coordI,"I\s*([-0-9.]+)",lines[x])
                        ins = pars(coordK,"K\s*([-0-9.]+)",lines[x])
                    else:
                        ins=coordI.insert(0,None)
                        ins=coordK.insert(0,None)                       
                    if  re.search("[R]", lines[x]):
                        ins = pars(coordR,"R\s*([-0-9.]+)",lines[x])
                    else:
                        ins=coordR.insert(0,None)
        x+=1 
    d_m=1
    if diameter_mode:
        d_m=2 #XXX    
    angle = []
    print 'd_m=',d_m 
    for n in range(len(coordZ)-1):
        lengthZ = abs(coordZ[n] - coordZ[n+1])
        lengthX = abs((coordX[n] - coordX[n+1])/d_m) #XXX /2                   
        app = angle.append(atan2(lengthX,lengthZ))
        print 'lengthX',lengthX
        print 'lengthZ',lengthZ
        print 'angle',degrees(atan2(lengthX,lengthZ))
        if line_or_arc[n]>1 and coordR[n]!=None:
            lh=(hip(lengthZ,lengthX))/2
            par=acos(lh/coordR[n])
            if line_or_arc[n]==2:
                ar=angle[n]+par
                indK=abs(cos(ar)*coordR[n])
            elif line_or_arc[n]==3:
                ar=angle[n]-par
                indK=-(cos(ar)*coordR[n])
            indI=sin(ar)*coordR[n] 
            pp=coordI.pop(n) 
            pp=coordK.pop(n) 
            ins=coordK.insert(n,indK) 
            ins=coordI.insert(n,indI)               
    app = angle.append(0.2914567944778671)                               
 ################################
    fn = '/home/nkp/fgcode.ngc'
    fgcode = open(fn, "w")
    self.execute("F%f" % feed_rate)#TODO

    part_n = -1
    flag_executed = 1 
    P = [] 
    program = [] 
    offset_mem=offset
    offsetX=offset*d_m
    mm=len(angle)-2  
    for i in range(quantity):
        print 'i=',i
        if i==1:
            if words.has_key('t'):
                self.execute("M6 T%d" % (tool))
                fgcode.write("M6 T%d\n" % (tool))
            if words.has_key('f'):
                feed_rate = float(words['f'])
                self.execute("F%f" % feed_rate)#TODO
                fgcode.write("F%f\n" % feed_rate)
        if line_or_arc[len(angle)-2] ==1:
            part_n+=1
            P.append([])
            P[part_n].append(1)
            P[part_n].append(round(coordX[mm+1]+(cos(angle[mm]))*offsetX,10))
            P[part_n].append(coordZ[mm+1]+(sin(angle[mm]))*offset)
            P[part_n].append(round(coordX[mm+1]+(cos(angle[mm]))*offsetX,10))
            P[part_n].append(coordZ[mm+1]+(sin(angle[mm]))*offset)
            FIRST_pointZ = coordZ[mm+1]+(sin(angle[mm]))*offset
            FIRST_pointX = round(coordX[mm+1]+(cos(angle[mm]))*offsetX,10)
            prog(program,1,FIRST_pointX,FIRST_pointZ)
        elif line_or_arc[len(angle)-2] ==3:
            FIRST_radius = sqrt((coordK[mm])*(coordK[mm]) + (coordI[mm])*(coordI[mm]))            
            FIRST_centreX = coordX[mm+1]/d_m + coordI[mm]            
            FIRST_centreZ = coordZ[mm+1] + coordK[mm]             
            FIRST_pointZ, FIRST_pointX=intersection_line_arc(3,coordZ[mm+1],coordX[mm+1]/d_m,
                                                                coordZ[mm+1]+10,coordX[mm+1]/d_m,
                                                                FIRST_centreZ,FIRST_centreX,
                                                                FIRST_radius+offset)
            FIRST_pointX = FIRST_pointX*d_m                                                   
            part_n+=1
            P.append([])
            P[part_n].append(3)         
            P[part_n].append(FIRST_pointX)
            P[part_n].append(FIRST_pointZ)
            P[part_n].append(FIRST_pointX)
            P[part_n].append(FIRST_pointZ)
            prog(program,1,FIRST_pointX,FIRST_pointZ) 
        elif line_or_arc[len(angle)-2] ==2:
            FIRST_radius = sqrt((coordK[mm])*(coordK[mm]) + (coordI[mm])*(coordI[mm]))            
            FIRST_centreX = coordX[mm+1]/d_m + coordI[mm]            
            FIRST_centreZ = coordZ[mm+1] + coordK[mm]                           
            FIRST_pointZ,FIRST_pointX=intersection_line_arc(2,coordZ[mm+1],
                                       coordX[mm+1]/d_m,coordZ[mm+1],
                                       coordX[mm+1]+10,FIRST_centreZ,
                                       FIRST_centreX,FIRST_radius-offset)
            FIRST_pointX = FIRST_pointX*d_m
            part_n+=1
            P.append([])
            P[part_n].append(2)     
            P[part_n].append(FIRST_pointX)
            P[part_n].append(FIRST_pointZ)
            P[part_n].append(FIRST_pointX)
            P[part_n].append(FIRST_pointZ)
            prog(program,1,FIRST_pointX,FIRST_pointZ)           
        coordZ_start =FIRST_pointZ                 
        for m in (reversed(range(len(angle)-1))):   
            if (line_or_arc[m] ==1): 
                if (line_or_arc[m-1] ==1): 
                    if angle[m-1] < angle[m]: 
                        print 'G01:LINE ANGLE:cw next:LINE'#OK_G7!
                        if m==0:
                            prog(program,1,coordX[m]+cos(angle[m])*offsetX,
                                 coordZ[m]+sin(angle[m])*offset)
                            part_n+=1
                            papp(part_n,1,coordX[m]+cos(angle[m])*offsetX,
                                  coordZ[m]+sin(angle[m])*offset,P)                             
                        else:
                            prog(program,1,coordX[m]+cos(angle[m])*offsetX,
                                 coordZ[m]+sin(angle[m])*offset)
                            part_n+=1
                            papp(part_n,1,coordX[m]+cos(angle[m])*offsetX,coordZ[m]+sin(angle[m])*offset,P) 
                            part_n+=1
                            papp(part_n,3,coordX[m]+cos(angle[m-1])*offsetX,coordZ[m]+sin(angle[m-1])*offset,
                                   P,offset,coordX[m]/d_m,coordZ[m])                 
                            prog(program,3,coordX[m]+cos(angle[m-1])*offsetX,
                                 coordZ[m]+sin(angle[m-1])*offset,offset)                           
                    else:                               
                        print 'G01:LINE ANGLE:ccw next:LINE' #OK_G7! 
                        angl = (angle[m] - angle[m-1])/2 
                        ggX =  offsetX / cos(angl)
                        gg =  offset / cos(angl)
                        angl1 = angle[m] - angl
                        prog(program,1,coordX[m]+cos(angl1)*ggX,
                                 coordZ[m]+sin(angl1)*gg)  
                        part_n+=1
                        papp(part_n,1,coordX[m]+cos(angl1)*ggX,coordZ[m]+sin(angl1)*gg,P)
                else: #если СЛЕДУЮЩИЙ участок "дуга"
                    NEXT_radius = sqrt((coordK[m-1])*(coordK[m-1]) + (coordI[m-1])*(coordI[m-1]))
                    print 'coordX[m]ДО=', coordX[m]
                    NEXT_centreX = coordX[m]/d_m + coordI[m-1]
                    print 'coordX[m]ПОСЛЕ=', coordX[m]
                    NEXT_centreZ = coordZ[m] + coordK[m-1] 
                    NEXT_lengthZ = abs(NEXT_centreZ - coordZ[m])
                    NEXT_lengthX = abs(NEXT_centreX - coordX[m]/d_m) 
                    NEXT_alfa = atan2(NEXT_lengthZ,NEXT_lengthX)
                    cw_next_pointZ= coordZ[m]+sin(NEXT_alfa)*offset
                    cw_next_pointX= coordX[m]+cos(NEXT_alfa)*offsetX
                    print ' +++++++++++++++++++++++++++++++++++++++'
                    print 'coordZ=', coordZ
                    print 'coordX=', coordX
                    print 'line_or_arc=', line_or_arc
                    print 'coordI=', coordI
                    print 'coordK=', coordK
                    print 'NEXT_radius=', NEXT_radius
                    print 'NEXT_centreX=', NEXT_centreX
                    print 'NEXT_centreZ=', NEXT_centreZ
                    print 'NEXT_lengthX=', NEXT_lengthX
                    print 'NEXT_lengthZ=', NEXT_lengthZ
                    print 'NEXT_alfa=', NEXT_alfa 
                    print 'angle[m]=', degrees(angle[m])
                    print 'NEXT_alfa=', degrees(NEXT_alfa) 
                    print 'angle[m]-NEXT_alfa=', angle[m]-NEXT_alfa                                       
                    print ' +++++++++++++++++++++++++++++++++++++++'                    
                    if (line_or_arc[m-1] ==3): #если СЛЕДУЮЩИЙ участок "дуга" CW 
                        if (angle[m] - NEXT_alfa<-0.00349): 
                            print '(G01:LINE)(ANGLE:angle[m]-NEXT_alfa < -0.00349)(next:ARC_G03)'#OK!! G7
                            radius_OFF = NEXT_radius+offset
                            NEXT_arc_itrs_lineZ,NEXT_arc_itrs_lineX = intersection_line_arc(3,coordZ[m+1]+sin(angle[m])*offset,
                                                                                  coordX[m+1]/d_m+cos(angle[m])*offset,
                                                                                  coordZ[m]+sin(angle[m])*offset,
                                                                                  coordX[m]/d_m+cos(angle[m])*offset,
                                                                                  NEXT_centreZ,NEXT_centreX,radius_OFF)
                            prog(program,1,NEXT_arc_itrs_lineX*d_m,NEXT_arc_itrs_lineZ)
                            part_n+=1
                            papp(part_n,1,NEXT_arc_itrs_lineX*d_m,NEXT_arc_itrs_lineZ,P)
                        elif (angle[m] - NEXT_alfa>0.00349): 
                            print '(G01:LINE)(ANGLE:angle[m]-NEXT_alfa > 0.00349)(next:ARC_G03)'#OK!! G7
                            prog(program,1,coordX[m]+cos(angle[m])*offsetX,
                                 coordZ[m]+sin(angle[m])*offset)
                            part_n+=1
                            papp(part_n,1,coordX[m]+cos(angle[m])*offsetX,
                                 coordZ[m]+sin(angle[m])*offset,P)
                            prog(program,3,cw_next_pointX,cw_next_pointZ,offset)
                            part_n+=1 
                            papp(part_n,3,cw_next_pointX,cw_next_pointZ,P,
                                              offset,coordX[m]/d_m,coordZ[m])                           
                        else: #angle[m] == NEXT_alfa 
                            print '(G01:LINE)  (ANGLE:angle[m] == NEXT_alfa)(next:ARC_G03)'#OK!! G7
                            prog(program,1,coordX[m]+cos(angle[m])*offsetX,
                                 coordZ[m]+sin(angle[m])*offset)
                            part_n+=1
                            papp(part_n,1,coordX[m]+cos(angle[m])*offsetX,
                                 coordZ[m]+sin(angle[m])*offset,P)                                 
                    if (line_or_arc[m-1] ==2): #если СЛЕДУЮЩИЙ участок "дуга" CCW
                        if (angle[m] - NEXT_alfa<-0.00349):
                            print '(G01:LINE) (angle[m] - NEXT_alfa<-0.00349) (next:ARC_G02)'#OK!! G7
                            NEXT_arc_itrs_lineZ,NEXT_arc_itrs_lineX = intersection_line_arc(3,coordZ[m+1]+sin(angle[m])*offset,
                                                                                  coordX[m+1]/d_m+cos(angle[m])*offset,
                                                                                  coordZ[m]+sin(angle[m])*offset,
                                                                                  coordX[m]/d_m+cos(angle[m])*offset,
                                                                                  NEXT_centreZ,NEXT_centreX,NEXT_radius-offset) 
                            prog(program,1,NEXT_arc_itrs_lineX*d_m,NEXT_arc_itrs_lineZ)
                            part_n+=1
                            papp(part_n,1,NEXT_arc_itrs_lineX*d_m,NEXT_arc_itrs_lineZ,P)

                        elif (angle[m] - NEXT_alfa>0.00349): 
                            print '(G01:LINE) (angle[m] - NEXT_alfa>0.00349) (next:ARC_G02)'#OK!! G7
                            prog(program,1,coordX[m]+cos(angle[m])*offsetX,
                                 coordZ[m]+sin(angle[m])*offset)
                            part_n+=1
                            papp(part_n,1,coordX[m]+cos(angle[m])*offsetX,
                                 coordZ[m]+sin(angle[m])*offset,P)
                            prog(program,3,cw_next_pointX,cw_next_pointZ,offset)
                            part_n+=1
                            papp(part_n,3,cw_next_pointX,cw_next_pointZ,P,offset,coordX[m]/d_m,coordZ[m])
                        else:       #angle[m] == NEXT_alfa
                            print '(G01:LINE)  (next:ARC_G02 angle[m] == NEXT_alfa) (next:ARC_G02)'#OK!! G7
                            prog(program,1,coordX[m]+cos(angle[m])*offsetX,
                                 coordZ[m]+sin(angle[m])*offset)
                            part_n+=1
                            papp(part_n,1,coordX[m]+cos(angle[m])*offsetX,
                                 coordZ[m]+sin(angle[m])*offset,P)
#+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
            else:  
                radius = sqrt((coordK[m])*(coordK[m]) + (coordI[m])*(coordI[m]))
                centreX = (coordX[m+1]/d_m + coordI[m])
                centreZ = coordZ[m+1] + coordK[m]
                lengthZ = abs(centreZ - coordZ[m])
                lengthX = abs(centreX - coordX[m]/d_m) 
                alfa = atan2(lengthZ,lengthX)
                zz= (radius-offset)*sin(alfa)
                xx= (radius-offset)*cos(alfa)
                pointZ=centreZ-zz
                if (coordX[m]/d_m < centreX):
                    pointX=centreX-xx
                else:
                    pointX=centreX+xx
                if (line_or_arc[m] == 3): 
                    if (line_or_arc[m-1] == 1): 
                        if (angle[m-1] - alfa < -0.00349):
                            print '(G03:ARC)(ANGLE:angle[m-1] - alfa < -0.00349)(next:LINE)'#DXF arc_G3_line<.dxf
                            cw_zz = (radius+offset)*sin(alfa)
                            cw_xx = (radius+offset)*cos(alfa)
                            cw_pointZ= centreZ+cw_zz
                            cw_pointX= centreX+cw_xx                                     
                            prog(program,3,cw_pointX,cw_pointZ,radius+offset)
                            
                            part_n+=1
                            papp(part_n,3,cw_pointX,cw_pointZ,P,radius+offset,centreX,centreZ)
                            prog(program,3,coordX[m]+cos(angle[m-1])*offsetX,
                                 coordZ[m]+sin(angle[m-1])*offset,offset)
                            part_n+=1
                            papp(part_n,3,coordX[m]+cos(angle[m-1])*offsetX,
                                  coordZ[m]+sin(angle[m-1])*offset,P,offset,coordX[m],coordZ[m]) 
                        elif (angle[m-1] - alfa > 0.00349):
                            print '(G03:ARC)(ANGLE:angle[m-1] - alfa > 0.00349)(next:LINE)'#OK!! G7
                            radius_and_off = radius+offset
                            if m==0:
                                
                                arc_itrs_lineZ,arc_itrs_lineX = coordZ[m], centreX+cathetus(radius+offset,
                                                                                    abs(centreZ-coordZ[m-1]))
                                print '$$$$$$$$$$$$$$$$$$$$$$'
                            else:
                                arc_itrs_lineZ,arc_itrs_lineX = intersection_line_arc(3,coordZ[m]+sin(angle[m-1])*offset,
                                                                                     coordX[m]/d_m+cos(angle[m-1])*offset,
                                                                                     coordZ[m-1]+sin(angle[m-1])*offset,
                                                                                     coordX[m-1]/d_m+cos(angle[m-1])*offset,
                                                                                     centreZ,centreX,radius_and_off)
                            prog(program,3,arc_itrs_lineX*d_m,arc_itrs_lineZ,radius+offset)
                            part_n+=1 
                            papp(part_n,3,arc_itrs_lineX*d_m,arc_itrs_lineZ,P,radius_and_off,centreX,centreZ) 
                        else:      
                            print 'G03:ARC   next:LINE angle[m-1] == alfa' #DXF arc_G3_line=.dxf OK_G7!
                            print  'angle[m-1]-degrees= ', degrees(angle[m-1])
                            print  'alfa-degrees= ', degrees(alfa)
                            print  'angle[m-1]= ', angle[m-1]
                            print  'alfa= ', alfa 
                            print  'angle[m-1] - alfa= ', angle[m-1] - alfa                           
                            prog(program,3,coordX[m]+cos(angle[m-1])*offsetX,
                                 coordZ[m]+sin(angle[m-1])*offset,radius+offset)
                            part_n+=1
                            papp(part_n,3,coordX[m]+cos(angle[m-1])*offsetX,
                                 coordZ[m]+sin(angle[m-1])*offset,P,radius+offset,centreX,centreZ)                               
                    else:  #если дуга G3
                        NEXT_radius = sqrt((coordK[m-1])*(coordK[m-1]) + (coordI[m-1])*(coordI[m-1]))
                        NEXT_centreX = coordX[m] + coordI[m-1]
                        NEXT_centreZ = coordZ[m] + coordK[m-1]                      
                        if (line_or_arc[m-1] == 3):   # и следующая дуга G3 
                            print 'G03:ARC  next:ARC_G03'
                            NEXT_X,NEXT_Z=intersection_arc_arc(NEXT_centreX,NEXT_centreZ, 
                                                               NEXT_radius+offset,centreX,centreZ,radius+offset,
                                                               coordX[m],coordZ[m])                
                            prog(program,3,NEXT_X,NEXT_Z,radius+offset)
                            part_n+=1
                            papp(part_n,3,NEXT_X,NEXT_Z,P,radius+offset,centreX,centreZ)
                        if (line_or_arc[m-1] == 2): # и следующая дуга G2 
                            print 'G03:ARC ANGLE:ccw next:ARC_G02'
                            NEXT_X,NEXT_Z=intersection_arc_arc(NEXT_centreX,NEXT_centreZ, 
                                                               NEXT_radius-offset,centreX,centreZ,radius+offset,
                                                               coordX[m],coordZ[m])                
                            prog(program,3,NEXT_X,NEXT_Z,radius+offset)
                            part_n+=1
                            papp(part_n,3,NEXT_X,NEXT_Z,P,radius+offset,centreX,centreZ)
                else: #если участок "дуга" CCW  
                    if (line_or_arc[m-1] == 1): 
                        if (angle[m-1] - alfa < -0.00349):
                            print '(G02:ARC) (angle[m-1] - alfa < -0.00349) (next:LINE)'  #OK_G7!
                            prog(program,2,pointX*d_m,pointZ,radius-offset)
                            part_n+=1
                            papp(part_n,2,pointX*d_m,pointZ,P,radius-offset,centreX,centreZ)
                            if m:
                                prog(program,3,coordX[m]+cos(angle[m-1])*offsetX,
                                     coordZ[m]+sin(angle[m-1])*offset,offset)
                                part_n+=1
                                papp(part_n,3,coordX[m]+cos(angle[m-1])*offsetX,
                                     coordZ[m]+sin(angle[m-1])*offset,P,offset,coordX[m]/d_m,coordZ[m]) 
                        elif (angle[m-1] - alfa > 0.00349):
                            print '(G02:ARC)(ANGLE:angle[m-1] - alfa > 0.00349)(next:LINE)'      
                            radius_and_off = radius-offset
                            if m==0:
                                arc_itrs_lineZ,arc_itrs_lineX = coordZ[m],coordX[m]-offsetX#XXX
                                print 'coordX[m]=',coordX[m]
                            else:
                                arc_itrs_lineZ,arc_itrs_lineX = intersection_line_arc(2,coordZ[m]+sin(angle[m-1])*offset,
                                                                                     coordX[m]+cos(angle[m-1])*offsetX,
                                                                                     coordZ[m-1]+sin(angle[m-1])*offset,
                                                                                     coordX[m-1]+cos(angle[m-1])*offsetX,
                                                                                     centreZ,centreX,radius_and_off)
                            prog(program,2,arc_itrs_lineX,arc_itrs_lineZ,radius-offset)
                            part_n+=1
                            papp(part_n,2,arc_itrs_lineX,arc_itrs_lineZ,P,radius_and_off,centreX,centreZ) 
 
                        else:
                            print 'G02:ARC   next:LINE angle[m-1] == alfa'
                            prog(program,2,coordX[m]+cos(angle[m-1])*offsetX,
                                     coordZ[m]+sin(angle[m-1])*offset,radius-offset)
                            part_n+=1
                            papp(part_n,2,coordX[m]+cos(angle[m-1])*offsetX,
                                 coordZ[m]+sin(angle[m-1])*offset,P,radius-offset,centreX,centreZ)                              
                            
                    else: 
                        NEXT_radius = sqrt((coordK[m-1])*(coordK[m-1]) + (coordI[m-1])*(coordI[m-1]))
                        NEXT_centreX = coordX[m] + coordI[m-1]
                        NEXT_centreZ = coordZ[m] + coordK[m-1]                  
                        if (line_or_arc[m-1] == 2): 
                            print 'G02:ARC  next:ARC_G02'
                            NEXT_X,NEXT_Z=intersection_arc_arc(NEXT_centreX,NEXT_centreZ, 
                                                               NEXT_radius-offset,centreX,centreZ,radius-offset,
                                                               coordX[m],coordZ[m])                
                            prog(program,2,NEXT_X,NEXT_Z,radius-offset)
                            part_n+=1
                            papp(part_n,2,NEXT_X,NEXT_Z,P,radius-offset,centreX,centreZ)
                            ########################################
                        if (line_or_arc[m-1] == 3): 
                            print 'G02:ARC ANGLE:ccw next:ARC_G03'
                            NEXT_X,NEXT_Z=intersection_arc_arc(NEXT_centreX,NEXT_centreZ, 
                                                               NEXT_radius+offset,centreX,centreZ,radius-offset,
                                                               coordX[m],coordZ[m])                
                            prog(program,2,NEXT_X,NEXT_Z,radius-offset)
                            part_n+=1
                            papp(part_n,2,NEXT_X,NEXT_Z,P,radius-offset,centreX,centreZ)
##################################################################### GO!
        print 'program =', program 
        print 'P =', P                            
        flag_micro_part = 0        
        bounce = 0.5 
        self.execute("G21 G18 G49  G90 G61")
        
        fgcode.write("G21 G18 G49  G90 G61 \n")
        fgcode.write("F%f \n" % feed_rate)
        fgcode.write("M6 T2\n")
        COORDx0 = P[len(P)-1][3] 
        self.execute("G1 X%f" % (COORDx0))
        fgcode.write("G1 X%f\n" % (COORDx0))
        if flag_executed :
            i = len(P)-1
            if only_finishing_cut==0 :
                if COORDx0 - P[len(P)-1][1] <= d:
                    d=0
                while COORDx0 - P[i][1] >= d :
                    d = float(words['d'])  
                    if P[i][0] == 1:
                        Mz1 = P[i][2]
                        Mx1 = P[i][1]
                        Mz2 = P[i][4]
                        Mx2 = P[i][3]  
                        if (Mz2-Mz1)!=0:
                            K=(Mx2-Mx1)/(Mz2-Mz1)
                            B=-(K*Mz1-Mx1)
                            COORDz0 = (COORDx0 - B)/K
                        else:
                            COORDz0=P[i][2] 
                    elif P[i][0] == 2:
                        Mz1 = P[i][2]
                        Mx1 = P[i][3]/d_m #XXX
                        Mz2 = P[i][4]
                        Mx2 = P[i][3]/d_m #XXX 
                        B=COORDx0 /d_m#XXX                           
                        center = [P[i][7],P[i][6]] #XXX
                        radius = P[i][5]                   
                        b = -2*center[0]   
                        c = -radius**2 + (B-center[1])**2 + center[0]**2  
                        D = b**2 - 4*c
                        print 'Mx1=',Mx1
                        print 'Mx2=',Mx2
                        print 'center=',center
                        print 'radius=',radius
                        print 'B=',B                          
                        if D < 0:  
                            print 'D<0  G2'
                        else:   
                            z1 = (-b-sqrt(D))/2 
                            z2 = (-b+sqrt(D))/2
                            if Mz1 < z1 < Mz2:#TODO 
                                COORDz0=z2
                            else:
                                COORDz0=z1
                    elif P[i][0] == 3:
                        Mz1 = P[i][2]
                        Mx1 = P[i][3]/d_m #XXX
                        Mz2 = P[i][4]
                        Mx2 = P[i][3]/d_m #XXX
                        B=COORDx0/d_m #XXX     
                        center = [P[i][7],P[i][6]]#XXX
                        radius = P[i][5] 
                        b = -2*center[0]  
                        c = -radius**2 + (B-center[1])**2 + center[0]**2  
                        D = b**2 - 4*c 
                        '''print 'Mx1=',Mx1
                        print 'Mx2=',Mx2
                        print 'center=',center
                        print 'radius=',radius
                        print 'B=',B'''
                        if D < 0: 
                            print 'D<0  G3'
                        else:  
                            z1 = (-b-sqrt(D))/2 
                            z2 = (-b+sqrt(D))/2 
                            '''print 'z1=',z1
                            print 'z2=',z2'''
                            if Mz1 < z1 < Mz2:#TODO 
                                COORDz0=z1
                            else:
                                COORDz0=z2
                    self.execute("G1 Z%f" % ((COORDz0)))
                    fgcode.write("G1 Z%f\n" % ((COORDz0)))
                    if bounce > coordZ_start - COORDz0:
                        self.execute("G0 X%f Z%f" % ((COORDx0),(coordZ_start)))
                        fgcode.write("G0 X%f Z%f\n" % ((COORDx0),(coordZ_start)))
                    else:
                        self.execute("G0 X%f Z%f" % ((COORDx0+bounce),(COORDz0+bounce)))
                        fgcode.write("G0 X%f Z%f\n" % ((COORDx0+bounce),(COORDz0+bounce)))
                        self.execute("G0 Z%f" % (coordZ_start))
                        fgcode.write("G0 Z%f\n" % (coordZ_start))

                    COORDx0 = COORDx0 - d
                    for next_i in reversed(range(len(P))): 
                        if P[next_i][3] >= COORDx0 > P[next_i][1]:
                            i=next_i                     
                    self.execute("G1 X%f" % (COORDx0))
                    fgcode.write("G1 X%f\n" % (COORDx0)) 
                    if flag_micro_part :                    
                        if COORDx0 - P[i][1] < d and P[i][3] > COORDx0 > P[i][1]:
                            d=0
                            flag_micro_part = 1
                        else:
                            flag_micro_part = 0
                        continue
                    if COORDx0 - P[i][1] < d:
                        if P[i][0] == 1:
                            Mz1 = P[i][2]
                            Mx1 = P[i][1]
                            Mz2 = P[i][4]
                            Mx2 = P[i][3]  
                            if (Mz2-Mz1)!=0:
                                K=(Mx2-Mx1)/(Mz2-Mz1)
                                B=-(K*Mz1-Mx1)
                                COORDz0 = (COORDx0 - B)/K
                            else:
                                COORDz0=P[i][2] 
                            self.execute("G1 Z%f" % ((COORDz0)))
                            fgcode.write("G1 Z%f\n" % ((COORDz0)))
                            if bounce > coordZ_start - COORDz0:
                                self.execute("G0 X%f Z%f" % ((COORDx0),(coordZ_start)))
                                fgcode.write("G0 X%f Z%f\n" % ((COORDx0),(coordZ_start)))
                            else:
                                self.execute("G0 X%f Z%f" % ((COORDx0+bounce),(COORDz0+bounce)))
                                fgcode.write("G0 X%f Z%f\n" % ((COORDx0+bounce),(COORDz0+bounce)))
                                self.execute("G0 Z%f" % (coordZ_start))
                                fgcode.write("G0 Z%f\n" % (coordZ_start))
                            if i>1:
                                COORDx0 = COORDx0 - d 
                                for next_i in reversed(range(len(P))): 
                                    if P[next_i][3] >= COORDx0 > P[next_i][1]:
                                        i=next_i                                  
                                if COORDx0 - P[i][1] < d and P[i][3] > COORDx0 > P[i][1]:
                                    d=0
                                    flag_micro_part = 1   
                                self.execute("G1 X%f" % (COORDx0))
                                fgcode.write("G1 X%f\n" % (COORDx0))
                        elif P[i][0] == 2:
                            Mz1 = P[i][2]
                            Mx1 = P[i][3]/d_m#XXX
                            Mz2 = P[i][4]
                            Mx2 = P[i][3]/d_m#XXX 
                            B=COORDx0 /d_m #XXX                         
                            center = [P[i][7],P[i][6]]#XXX
                            radius = P[i][5]  
                            b = -2*center[0]  
                            c = -radius**2 + (B-center[1])**2 + center[0]**2
                            D = b**2 - 4*c 
                            if D < 0:
                                print 'D<0'
                            else: 
                                z1 = (-b-sqrt(D))/2
                                z2 = (-b+sqrt(D))/2 
                                if Mz1 < z1 < Mz2:#TODO
                                    COORDz0=z2
                                else:
                                    COORDz0=z1
                            self.execute("G1 Z%f" % ((COORDz0)))
                            fgcode.write("G1 Z%f\n" % ((COORDz0)))                          
                            if bounce > coordZ_start - COORDz0:
                                self.execute("G0 X%f Z%f" % ((COORDx0),(coordZ_start)))
                                fgcode.write("G0 X%f Z%f\n" % ((COORDx0),(coordZ_start)))
                            else:
                                self.execute("G0 X%f Z%f" % ((COORDx0+bounce),(COORDz0+bounce)))
                                fgcode.write("G0 X%f Z%f\n" % ((COORDx0+bounce),(COORDz0+bounce)))
                                self.execute("G0 Z%f" % (coordZ_start))
                                fgcode.write("G0 Z%f\n" % (coordZ_start))
                            if i>1:
                                COORDx0 = COORDx0 - d 
                                for next_i in reversed(range(len(P))): 
                                    if P[next_i][3] >= COORDx0 > P[next_i][1]:
                                        i=next_i                                  
                                if COORDx0 - P[i][1] < d and P[i][3] > COORDx0 > P[i][1]:
                                    d=0
                                    flag_micro_part = 1
                                self.execute("G1 X%f" % (COORDx0))
                                fgcode.write("G1 X%f\n" % (COORDx0))
                        elif P[i][0] == 3:
                            Mz1 = P[i][2]
                            Mx1 = P[i][3]/d_m#XXX
                            Mz2 = P[i][4]
                            Mx2 = P[i][3]/d_m#XXX 
                            B=COORDx0/d_m #XXX
                            center = [P[i][7],P[i][6]]#XXX
                            radius = P[i][5]
                            b = -2*center[0]
                            c = -radius**2 + (B-center[1])**2 + center[0]**2
                            D = b**2 - 4*c
                            if D < 0:  
                                print 'D<0'
                            else:   
                                z1 = (-b-sqrt(D))/2   
                                z2 = (-b+sqrt(D))/2 
                                if Mz1 < z1 < Mz2: #TODO сделать "умнее" расчет
                                    COORDz0=z1
                                else:
                                    COORDz0=z2
                            self.execute("G1 Z%f" % ((COORDz0)))
                            fgcode.write("G1 Z%f\n" % ((COORDz0)))
                            if bounce > coordZ_start - COORDz0:
                                self.execute("G0 X%f Z%f" % ((COORDx0),(coordZ_start)))
                                fgcode.write("G0 X%f Z%f\n" % ((COORDx0),(coordZ_start)))
                            else:
                                self.execute("G0 X%f Z%f" % ((COORDx0+bounce),(COORDz0+bounce)))
                                fgcode.write("G0 X%f Z%f\n" % ((COORDx0+bounce),(COORDz0+bounce)))
                                self.execute("G0 Z%f" % (coordZ_start))
                                fgcode.write("G0 Z%f\n" % (coordZ_start))
                            if i>1:
                                COORDx0 = COORDx0 - d 
                                for next_i in reversed(range(len(P))): 
                                    if P[next_i][3] >= COORDx0 > P[next_i][1]:
                                        i=next_i                                  
                                if COORDx0 - P[i][1] < d and P[i][3] > COORDx0 > P[i][1]:
                                    d=0
                                    flag_micro_part = 1
                                self.execute("G1 X%f" % (COORDx0))
                                fgcode.write("G1 X%f\n" % (COORDx0))                         
            else:
                MESSAGE("Only finishing cut") 
                self.execute("M0")                          
#####################################################                                                          
        flag_executed = 0                                            
        for w in program:
            try:  
                self.execute(w)
                fgcode.write(w)
                fgcode.write("\n")
            except InterpreterException,e:
                        msg = "%d: '%s' - %s" % (e.line_number,e.line_text, e.error_message)
                        self.set_errormsg(msg) 
                        return INTERP_ERROR  
        offset-=offset_mem/quantity
        program = []
        self.execute("G0 Z%f" % (coordZ_start)) 
        fgcode.write("G0 Z%f\n" % (coordZ_start))   
#####################################################
    self.execute("G40 " ) 
    #self.execute("G42" )
 #   self.execute("G0 X%f Z%f" % ((FIRST_pointX),(coordZ_start)))
#    self.execute("G1 X%f " % FIRST_pointX)
    if words.has_key('t'):
        self.execute("M6 T%d" % (tool))
        fgcode.write("M6 T%d\n" % (tool))
    if words.has_key('f'):
        feed_rate = float(words['f'])
        self.execute("F%f" % feed_rate)#TODO
        fgcode.write("F%f\n" % feed_rate)                  
    for w in lines:
        if  re.search("^\s*[(]\s*N\d", w.upper()):
            if not re.search("[^\(\)\.\-\+NGZXRIK\d\s]", w.upper()):
                num2 = int(re.findall("^\s*\d*",(re.split('N',w.upper())[1]))[0])
                if num2 >= p and num2 <= q:
                    try: 
                        contour=re.split('\)',(re.split('\(',w.upper())[1]))[0]
                        self.execute(contour)
                        fgcode.write(contour)
                        fgcode.write("\n")
                    except InterpreterException,e:
                        msg = "%d: '%s' - %s" % (e.line_number,e.line_text, e.error_message)
                        self.set_errormsg(msg) 
                        return INTERP_ERROR
    self.execute("G40" )   
    self.execute("G0 Z0")
    fgcode.write("G0 Z0\n")
    fgcode.write("M02\n")                             
    f.close() 
    fgcode.close()               
    return INTERP_OK
=================
через s.poll "переключаться" G7-G8 не выйдет - емс всегда ставит по умолчанию G8 (и правильно делает! :) )
так что парсим по коду...
если кто работает ТОЛЬКО в диаметрах , то вот dxf-to-gcode
выдает в диаметрах:

Код: Выделить всё

#!/usr/bin/python
# -*- coding: utf-8 -*-

import sys
if globals().has_key('init_modules'):
    for m in [x for x in sys.modules.keys() if x not in init_modules]:
        del(sys.modules[m]) 
else:
    init_modules = sys.modules.keys()


import sys, os, string, ConfigParser
from dxf2gcode_v01_point import PointClass
from dxf2gcode_v01_shape import ShapeClass
import dxf2gcode_v01_dxf_import as dxf_import 
import dxf2gcode_v01_tsp_opt as tsp


import webbrowser
from Tkconstants import END, INSERT, ALL, N, S, E, W, RAISED, RIDGE, GROOVE, FLAT, DISABLED, NORMAL, ACTIVE, LEFT
from tkMessageBox import showwarning, showerror
from Tkinter import Tk, Canvas, Menu, Frame, Grid, DoubleVar, StringVar , IntVar, Radiobutton,Checkbutton, Label, Entry, Text, Scrollbar, Toplevel,Button , PhotoImage
from tkFileDialog import askopenfile, asksaveasfilename
from tkSimpleDialog import askfloat
from Canvas import Rectangle, Line, Oval, Arc
from copy import copy

from math import radians, cos, sin
import re
APPNAME = "dxf2gcode_v01"

class Erstelle_Fenster:
    def __init__(self, master = None, load_filename=None ):
        
        self.master=master     

        self.load_filename=load_filename

        self.frame_l=Frame(master) 
        self.frame_l.grid(row=0,column=0,rowspan=2,padx=4,pady=4,sticky=N+E+W)
        
        self.frame_c=Frame(master,relief = RIDGE,bd = 2)
        self.frame_c.grid(row=0,column=1,padx=4,pady=4,sticky=N+E+S+W)
        
        self.frame_u=Frame(master) 
        self.frame_u.grid(row=1,column=1,padx=4,sticky=N+E+W+S)
        self.textbox=TextboxClass(frame=self.frame_u,master=self.master)

        self.config=ConfigClass(self.textbox)

        self.postpro=PostprocessorClass(self.config,self.textbox)

        self.master.columnconfigure(0,weight=0)
        self.master.columnconfigure(1,weight=1)
        self.master.rowconfigure(0,weight=1)
        self.master.rowconfigure(1,weight=0)
            

        self.ExportParas =ExportParasClass(self.frame_l,self.config,self.postpro)
        self.Canvas =CanvasClass(self.frame_c,self)

        self.CanvasContent=CanvasContentClass(self.Canvas,self.textbox,self.config)
        self.Canvas.Content=self.CanvasContent

        self.erstelle_menu()        
        
        if not(self.load_filename==None):
            self.Canvas.canvas.update()
            self.Load_File(self.load_filename)

    def erstelle_menu(self): 
        self.menu = Menu(self.master)
        self.master.config(menu=self.menu)

        self.filemenu = Menu(self.menu,tearoff=0)
        self.menu.add_cascade(label="File", menu=self.filemenu)
        self.filemenu.add_command(label="Read DXF", command=self.Get_Load_File)
        self.filemenu.add_separator()
        self.filemenu.add_command(label="Exit", command=self.ende)

        self.exportmenu = Menu(self.menu,tearoff=0)
        self.menu.add_cascade(label="Export", menu=self.exportmenu)
        self.exportmenu.add_command(label="Write G-Code", command=self.Write_GCode)
        self.exportmenu.entryconfig(0,state=DISABLED)

        self.viewmenu=Menu(self.menu,tearoff=0)
        self.menu.add_cascade(label="View",menu=self.viewmenu)
        self.viewmenu.add_checkbutton(label="Show workpiece zero",\
                                      variable=self.CanvasContent.toggle_wp_zero,\
                                      command=self.CanvasContent.plot_wp_zero)
        self.viewmenu.add_checkbutton(label="Show all path directions",\
                                      variable=self.CanvasContent.toggle_start_stop,\
                                      command=self.CanvasContent.plot_cut_info)
        self.viewmenu.add_checkbutton(label="Show disabled shapes",\
                                      variable=self.CanvasContent.toggle_show_disabled,\
                                      command=self.CanvasContent.show_disabled)
            
        self.viewmenu.add_separator()
        self.viewmenu.add_command(label='Autoscale',command=self.Canvas.autoscale)

        self.viewmenu.add_separator()
        self.viewmenu.add_command(label='Delete Route',command=self.del_route_and_menuentry)         

        self.viewmenu.entryconfig(0,state=DISABLED)
        self.viewmenu.entryconfig(1,state=DISABLED)
        self.viewmenu.entryconfig(2,state=DISABLED)
        self.viewmenu.entryconfig(4,state=DISABLED)
        self.viewmenu.entryconfig(6,state=DISABLED)

        self.optionmenu=Menu(self.menu,tearoff=0)
        self.menu.add_cascade(label="Options",menu=self.optionmenu)
        self.optionmenu.add_command(label="Set tolerances", command=self.Get_Cont_Tol)
        self.optionmenu.add_separator()
        self.optionmenu.add_command(label="Scale contours", command=self.Get_Cont_Scale)
        self.optionmenu.add_command(label="Move workpiece zero", command=self.Move_WP_zero)
        self.optionmenu.entryconfig(2,state=DISABLED)
        self.optionmenu.entryconfig(3,state=DISABLED)
        
        
        self.helpmenu = Menu(self.menu,tearoff=0)
        self.menu.add_cascade(label="Help", menu=self.helpmenu)
        self.helpmenu.add_command(label="About...", command=self.Show_About)

    def Get_Load_File(self):
        myFormats = [('AutoCAD / QCAD Drawing','*.dxf'),\
        ('All File','*.*') ]
        inidir=self.config.load_path
        filename = askopenfile(initialdir=inidir,\
                               filetypes=myFormats)
        if not filename:
            return
        else:
            self.load_filename=filename.name
            
        self.Load_File(self.load_filename)

    def Load_File(self,filename):
   
        self.textbox.text.delete(7.0,END)
        self.textbox.prt('\nLoading file: %s ' %filename)
        
        self.values=dxf_import.Load_DXF(filename,self.config,self.textbox)
        
        self.textbox.prt('\nLoaded layers: ' +str(len(self.values.layers)))
        self.textbox.prt('\nLoaded blocks: ' +str(len(self.values.blocks.Entities)))
        for i in range(len(self.values.blocks.Entities)):
            layers=self.values.blocks.Entities[i].get_used_layers()
            self.textbox.prt('\nBlock ' +str(i) +' includes '+str(len(self.values.blocks.Entities[i].geo))\
                             +' Geometries, reduced to ' +str(len(self.values.blocks.Entities[i].cont)) \
                             +' Contours, used layers: ' +str(layers))
        layers=self.values.entities.get_used_layers()
        insert_nr=self.values.entities.get_insert_nr()
        self.textbox.prt('\nLoaded ' +str(len(self.values.entities.geo))\
                             +' Entities geometries, reduced to ' +str(len(self.values.entities.cont))\
                             +' Contours, used layers: ' +str(layers)\
                             +' ,Number of inserts: ' +str(insert_nr))

        self.cont_scale=1.0
        
        self.cont_dx=0.0
        self.cont_dy=0.0

        self.viewmenu.entryconfig(0,state=NORMAL)
        self.viewmenu.entryconfig(1,state=NORMAL)
        self.viewmenu.entryconfig(2,state=NORMAL)
        self.viewmenu.entryconfig(4,state=NORMAL)

        self.exportmenu.entryconfig(0,state=NORMAL)

        self.optionmenu.entryconfig(2,state=NORMAL)
        self.optionmenu.entryconfig(3,state=NORMAL)        

        self.CanvasContent.makeplot(self.values)

        self.del_route_and_menuentry()
            
    def Get_Cont_Tol(self):

        title='Contour tolerances'
        label=(("Tolerance for common points [mm]:"),\
               ("Tolerance for curve fitting [mm]:"))
        value=(self.config.points_tolerance.get(),self.config.fitting_tolerance.get())
        dialog=Tkinter_Variable_Dialog(self.master,title,label,value)
        self.config.points_tolerance.set(dialog.result[0])
        self.config.fitting_tolerance.set(dialog.result[1])
        
        if self.load_filename==None:
            return
        self.Load_File(self.load_filename)
        self.textbox.prt(("\nSet new Contour tolerances (Pts: %0.3f, Fit: %0.3f) reloaded file"\
                              %(dialog.result[0],dialog.result[1])))
        
    def Get_Cont_Scale(self):
        old_scale=self.cont_scale
                
        value=askfloat('Scale Contours','Set the scale factor',\
                                initialvalue=self.cont_scale)
        if value==None:
            return
        
        self.cont_scale=value

        self.textbox.prt(("\nScaled Contours by factor %0.3f" %self.cont_scale))

        self.Canvas.scale_contours(self.cont_scale/old_scale)        
        
    def Move_WP_zero(self):
        old_dx=self.cont_dx
        old_dy=self.cont_dy

        title='Workpiece zero offset'
        label=(("Offset %s axis by mm:" %self.config.ax1_letter),\
               ("Offset %s axis by mm:" %self.config.ax2_letter))
        value=(self.cont_dx,self.cont_dy)
        dialog=Tkinter_Variable_Dialog(self.master,title,label,value)

        if dialog.result==False:
            return
        
        self.cont_dx=dialog.result[0]
        self.cont_dy=dialog.result[1]

        self.textbox.prt(("\nWorpiece zero offset: %s %0.2f; %s %0.2f" \
                              %(self.config.ax1_letter,self.cont_dx,
                                self.config.ax2_letter,self.cont_dy)))

        self.Canvas.move_wp_zero(self.cont_dx-old_dx,self.cont_dy-old_dy)

    def Get_Save_File(self):

        if self.load_filename==None:
            showwarning("Export G-Code", "Nothing to export!")
            return
        
        myFormats = [('G-Code for EMC2','*.ngc'),\
        ('All File','*.*') ]

        (beg, ende)=os.path.split(self.load_filename)
        (fileBaseName, fileExtension)=os.path.splitext(ende)

        inidir=self.config.save_path
        self.save_filename = asksaveasfilename(initialdir=inidir,\
                               initialfile=fileBaseName +'.ngc',filetypes=myFormats)

    def Write_GCode(self):

        self.opt_export_route()

        status=1

        config=self.config
        postpro=self.postpro

        postpro.write_gcode_be(self.ExportParas,self.load_filename)


        for nr in range(1,len(self.TSP.opt_route)):
            shape=self.shapes_to_write[self.TSP.opt_route[nr]]
            self.textbox.prt(("\nWriting Shape: %s" %shape),1)
                


            if not(shape.nr in self.CanvasContent.Disabled):
                stat =shape.Write_GCode(config,postpro)
                status=status*stat


        string=postpro.write_gcode_en(self.ExportParas)

        if status==1:
            self.textbox.prt(("\nSuccessfully generated G-Code"))
            self.master.update_idletasks()

        else:
            self.textbox.prt(("\nError during G-Code Generation"))
            self.master.update_idletasks()


################################################################################вывод программы
        save_file = self.config.tempfile_gcode
        f = open(save_file, "w")
        f.write(string)
        f.close()
        
        f = open(save_file, "r")  
        lines = f.readlines()
        f.close()
        ch = '' 
        ch1 = ''
        program = ''
        x_max, p, q, d, k, i, f, j, s, l, t = 0, 1, 15, 1.5, 0.3, 1, 433, 0, 0, 1, 1
        Dtr, Lng, Prk = 0, 0, 0
        N_start_end = []
        Z_start = []
        for l in lines:
            if  re.search("[^\(\)\.\-\+NGZXRIK\d\s]",l.upper()):
                l=str(re.sub("^\s+|\n|\r|\s+$", '', l.upper(),re.I))
                ch1 +=l
                ch1 +='\n'
            elif  re.search("G\s*([0-3.]+)", l.upper() ,re.I):
                if not  re.search("[^\(\)\.\-\+NGZXRIK\d\s]",l.upper()):
                    l=re.sub("^\s+|\n|\r|\s+$", '', l.upper(),re.I)
                    ch +='('
                    ch +=l
                    ch +=')'
                    ch +='\n'
                    p1 = N_start_end.append(int(re.search("N\s*([-0-9.]+)",l.upper(), re.I).group(1)))
                    z_st = Z_start.append(float(re.search("Z\s*([-0-9.]+)",l.upper(), re.I).group(1)))
                    x_max_sr = float(re.search("X\s*([-0-9.]+)",l.upper(), re.I).group(1))
                    if x_max_sr > x_max:
                        x_max = x_max_sr
                    z_max = float(re.search("Z\s*([-0-9.]+)",l.upper(), re.I).group(1))
                        
        p = N_start_end[0]
        q = N_start_end[-1]
        z0 = Z_start[0]
        d = float(self.ExportParas.d_D.get())
        k = float(self.ExportParas.d_K.get())
        i = float(self.ExportParas.d_I.get())
        f = float(self.ExportParas.d_F.get())
        s = float(self.ExportParas.d_S.get())
        l = float(self.ExportParas.d_L.get())
        t = int(self.ExportParas.d_T.get())
        rb = self.ExportParas.g71_72.get()

        Dtr = float(self.ExportParas.D_out.get())
        Lng = float(self.ExportParas.Lg.get())
        Prk = float(self.ExportParas.D_in.get())
        checkbutton = self.ExportParas.only.get()
        show_blank = self.ExportParas.show_blank.get()
        code = 'G71.2'
        start_point = str('G1 X%s  Z%s \n' % (x_max, z0))
        if rb :
            code = 'G72.2'
            start_point = str('G1 X%s  Z%s \n' % (x_max, z_max))
        if checkbutton :
            j = 1           
        program += ch1
        blank = str('(AXIS,blank,%s,%s,%s)\n' % (Dtr, Lng, Prk))
        if show_blank :
            program += blank
        program += start_point
        stt = str('%s P%s Q%s  D%s K%s I%s F%s J%s S%s L%s T%s\n' % (code,p,q,d,k,i,f,j,s,l,t))
        program += stt
        program += ch
        program += 'M2'
        
        stdoutsav = sys.stdout
        editfile = self.config.editfilename
        outlog = open(editfile, "w")
        outlog.write(program)
        outlog.close()
        print(program)
        self.ende()          
            

    def opt_export_route(self):
        
        iter =min(self.config.max_iterations,len(self.CanvasContent.Shapes)*20)
        
        self.shapes_to_write=[]
        shapes_st_en_points=[]
        
        for shape_nr in range(len(self.CanvasContent.Shapes)):
            shape=self.CanvasContent.Shapes[shape_nr]
            if not(shape.nr in self.CanvasContent.Disabled):
                self.shapes_to_write.append(shape)
                shapes_st_en_points.append(shape.get_st_en_points())
                

        x_st=self.config.axis1_st_en.get()
        y_st=self.config.axis2_st_en.get()
        start=PointClass(x=x_st,y=y_st)
        ende=PointClass(x=x_st,y=y_st)
        shapes_st_en_points.append([start,ende])

        self.textbox.prt(("\nTSP Starting"),1)
                
        self.TSP=tsp.TSPoptimize(shapes_st_en_points,self.textbox,self.master,self.config)
        self.textbox.prt(("\nTSP start values initialised"),1)

        for it_nr in range(iter):
            if (it_nr%10)==0:
                self.textbox.prt(("\nTSP Iteration nr: %i" %it_nr),1)
                for hdl in self.CanvasContent.path_hdls:
                    self.Canvas.canvas.delete(hdl)
                self.CanvasContent.path_hdls=[]
                self.CanvasContent.plot_opt_route(shapes_st_en_points,self.TSP.opt_route)
                self.master.update_idletasks()
                
            self.TSP.calc_next_iteration()
            
        self.textbox.prt(("\nTSP done with result:"),1)
        self.textbox.prt(("\n%s" %self.TSP),1)

        self.viewmenu.entryconfig(6,state=NORMAL)        

    def del_route_and_menuentry(self):
        try:
            self.viewmenu.entryconfig(6,state=DISABLED)
            self.CanvasContent.delete_opt_path()
        except:
            pass
        
    def Show_About(self):
        Show_About_Info(self.master)
  
    def ende(self):
        self.master.destroy()
        self.master.quit()

class TextboxClass:
    def __init__(self,frame=None,master=None,DEBUG=0):
            
        self.DEBUG=DEBUG
        self.master=master
        self.text = Text(frame,height=7)
        
        self.textscr = Scrollbar(frame)
        self.text.grid(row=0,column=0,pady=4,sticky=E+W)
        self.textscr.grid(row=0,column=1,pady=4,sticky=N+S)
        frame.columnconfigure(0,weight=1)
        frame.columnconfigure(1,weight=0)

        
        self.text.bind("<Button-3>", self.text_contextmenu)

        self.textscr.config(command=self.text.yview)
        self.text.config(yscrollcommand=self.textscr.set)
        self.prt('Program started\nVersion V0.1LatheG71\n')

    def set_debuglevel(self,DEBUG=0):
        self.DEBUG=DEBUG
        if DEBUG:
            self.text.config(height=15)

    def prt(self,txt='',DEBUGLEVEL=0):

        if self.DEBUG>=DEBUGLEVEL:
            self.text.insert(END,txt)
            self.text.yview(END)
            self.master.update_idletasks()
            

    def text_contextmenu(self,event):

        popup = Menu(self.text,tearoff=0)        
        popup.add_command(label='Delete text entries',command=self.text_delete_entries)
        popup.post(event.x_root, event.y_root)
        
    def text_delete_entries(self):
        self.text.delete(7.0,END)
        self.text.yview(END)           

class ExportParasClass:
    def __init__(self,master=None,config=None,postpro=None):
        self.master=master
  
        self.nb = NotebookClass(self.master,width=280)

        self.nb_f1 = Frame(self.nb())
        self.nb_f2 = Frame(self.nb())
        self.nb_f3 = Frame(self.nb())
        
        self.nb.add_screen(self.nb_f1, "Parameter")
        self.nb.add_screen(self.nb_f2, "Gcode    ")
        self.nb.add_screen(self.nb_f3, "Img      ")
        
        self.nb_f1.columnconfigure(0,weight=1)
        self.nb_f2.columnconfigure(0,weight=1)        
        self.nb_f3.columnconfigure(0,weight=1) 
    
        self.erstelle_eingabefelder(config)
        self.erstelle_textfelder(config )

        self.gcode_be.insert(END,postpro.gcode_be)
        self.gcode_en.insert(END,postpro.gcode_en)

        self.ccc = CanvasContentClass(self,Canvas,config)# ????????????????????????????????????????????????
        

        


        
    def erstelle_eingabefelder(self,config):
       
        f1=Frame(self.nb_f1,relief = GROOVE,bd = 2)
        f1.grid(row=0,column=0,padx=2,pady=2,sticky=N+W+E)
        f2=Frame(self.nb_f1,relief = GROOVE,bd = 2)
        f2.grid(row=1,column=0,padx=2,pady=2,sticky=N+W+E)
        f3=Frame(self.nb_f1,relief = GROOVE,bd = 2)
        f3.grid(row=2,column=0,padx=2,pady=2,sticky=N+W+E)
        f4=Frame(self.nb_f1,relief = GROOVE,bd = 2)
        f4.grid(row=3,column=0,padx=2,pady=2,sticky=N+W+E)
            
        f1.columnconfigure(0,weight=1)
        f2.columnconfigure(0,weight=1)
        f3.columnconfigure(0,weight=1) 
        f4.columnconfigure(0,weight=1)         
#########################################################################################параметры в окне              
        Label(f1, text="Depth of cut   [D]")\
                .grid(row=0,column=0,sticky=N+W,padx=4)
        self.d_D = Entry(f1,width=7,textvariable=config.depth_D)
        self.d_D.grid(row=0,column=1,sticky=N+E)
             
        Label(f1, text="Finishing(depth)      [K]")\
                .grid(row=1,column=0,sticky=N+W,padx=4)
        self.d_K = Entry(f1,width=7,textvariable=config.finishing_depth)
        self.d_K.grid(row=1,column=1,sticky=N+E)        

        Label(f1, text=("Quantity      [I]" ))\
                .grid(row=2,column=0,sticky=N+W,padx=4)
        self.d_I = Entry(f1,width=7,textvariable=config.quantity_I)
        self.d_I.grid(row=2,column=1,sticky=N+E)
        

        Label(f2, text=("Feedrate   [F]"))\
                .grid(row=0,column=0,sticky=N+W,padx=4)
        self.d_F = Entry(f2,width=7,textvariable=config.feedrate_F)
        self.d_F.grid(row=0,column=1,sticky=N+E)

        Label(f2, text=("Ending Block  [Q]"))\
                .grid(row=1,column=0,sticky=N+W,padx=4)
        self.d_Q = Entry(f2,width=7,textvariable=config.ending_block_Q)
        self.d_Q.grid(row=1,column=1,sticky=N+E)

        Label(f2, text=("Start_Z  [Z0]"))\
                .grid(row=2,column=0,sticky=N+W,padx=4)
        self.d_Z0 = Entry(f2,width=7,textvariable=config.start_Z0)
        self.d_Z0.grid(row=2,column=1,sticky=N+E)
        
        Label(f2, text=("reserve  [S]" ))\
                .grid(row=3,column=0,sticky=N+W,padx=4)
        self.d_S = Entry(f2,width=7,textvariable=config.reserve_S)
        self.d_S.grid(row=3,column=1,sticky=N+E)

        Label(f2, text=("Tool  [T]" ))\
                .grid(row=4,column=0,sticky=N+W,padx=4)
        self.d_T = Entry(f2,width=7,textvariable=config.tool_T)
        self.d_T.grid(row=4,column=1,sticky=N+E)


        Label(f2, text=("reserve  [L]" ))\
                .grid(row=5,column=0,sticky=N+W,padx=4)
        self.d_L = Entry(f2,width=7,textvariable=config.reserve_L)  
        self.d_L.grid(row=5,column=1,sticky=N+E)

                               
        self.g71_72=IntVar()
        self.g71_72.set(0)
        self.only=IntVar()
        self.show_blank=IntVar()
        self.show_blank.set(1)
        
        Label(f3, text=("G71" ))\
        .grid(row=3,column=0,sticky=N+W,padx=4)
        self.rad0 = Radiobutton(f3,text="G71",variable=self.g71_72,value=0 ,command=lambda: self.change_img71())
        self.rad0.grid(row=3,column=1,sticky=N+E)
        
        Label(f3, text=("G72" ))\
        .grid(row=4,column=0,sticky=N+W,padx=4)        
        self.rad1 = Radiobutton(f3,text="G72",variable=self.g71_72,value=1,command=lambda: self.change_img72())
        self.rad1.grid(row=4,column=1,sticky=N+E)
        
        Label(f3, text=("Only finishing [J]" ))\
        .grid(row=5,column=0,sticky=N+W,padx=4)        
        self.rad2 = Checkbutton(f3,text="",variable=self.only,onvalue=1,offvalue=0)
        self.rad2.grid(row=5,column=1,sticky=N+E)
        
        
        Label(f4, text="Diameter blank outside")\
        .grid(row=0,column=0,sticky=N+W,padx=4)
        self.D_out = Entry(f4,width=7,textvariable=config.b_D_out)
        self.D_out.grid(row=0,column=1,sticky=N+E)
             
        Label(f4, text="Lenght blank")\
        .grid(row=1,column=0,sticky=N+W,padx=4)
        self.Lg = Entry(f4,width=7,textvariable=config.b_L)
        self.Lg.grid(row=1,column=1,sticky=N+E)        

        Label(f4, text=("Blank diam. inside" ))\
        .grid(row=2,column=0,sticky=N+W,padx=4)
        self.D_in = Entry(f4,width=7,textvariable=config.b_D_in)
        self.D_in.grid(row=2,column=1,sticky=N+E)
        
        Label(f4, text=("Show blank" ))\
        .grid(row=3,column=0,sticky=N+W,padx=4)        
        self.rad3 = Checkbutton(f4,text="",variable=self.show_blank,onvalue=1,offvalue=0)
        self.rad3.grid(row=3,column=1,sticky=N+E)
        
    def revers_contour(self):
        aa=self.ccc.switch_shape_dir()# ????????????????????????????????????????????????
 
    def change_img71( self): #при выборе 71-72 меняем картинки
        self.textbox.prt('\ncheckbutton is OK!!')
        self.im = PhotoImage(file='G71.gif') 
        f33=Frame(self.nb_f3,relief = FLAT,bd = 1)
        f33.grid(row=0,column=0,padx=2,pady=2,sticky=N+W+E)
        f33.columnconfigure(0,weight=1) 

        self.gif = Label(f33 , image=self.im)
        self.gif.grid(row=0,column=0,columnspan=2,sticky=N+W,padx=2)


        f33.columnconfigure(0,weight=1)
        f33.rowconfigure(1,weight=0)
        f33.rowconfigure(3,weight=0)
        
    def change_img72( self):
        self.im = PhotoImage(file='G72.gif') 
        f33=Frame(self.nb_f3,relief = FLAT,bd = 1)
        f33.grid(row=0,column=0,padx=2,pady=2,sticky=N+W+E)
        f33.columnconfigure(0,weight=1) 

        self.gif = Label(f33 , image=self.im)
        self.gif.grid(row=0,column=0,columnspan=2,sticky=N+W,padx=2)


        f33.columnconfigure(0,weight=1)
        f33.rowconfigure(1,weight=0)
        f33.rowconfigure(3,weight=0) 
        
    def erstelle_textfelder(self,config):
        f22=Frame(self.nb_f2,relief = FLAT,bd = 1)
        f22.grid(row=0,column=0,padx=2,pady=2,sticky=N+W+E)
        f22.columnconfigure(0,weight=1)        

        Label(f22 , text="G-Code at the begin of file")\
                .grid(row=0,column=0,columnspan=2,sticky=N+W,padx=2)
        self.gcode_be = Text(f22,width=10,height=8)
        self.gcode_be_sc = Scrollbar(f22)
        self.gcode_be.grid(row=1,column=0,pady=2,sticky=E+W)
        self.gcode_be_sc.grid(row=1,column=1,padx=2,pady=2,sticky=N+S)
        self.gcode_be_sc.config(command=self.gcode_be.yview)
        self.gcode_be.config(yscrollcommand=self.gcode_be_sc.set)

        Label(f22, text="G-Code at the end of file")\
                .grid(row=2,column=0,columnspan=2,sticky=N+W,padx=2)
        self.gcode_en = Text(f22,width=10,height=5)
        self.gcode_en_sc = Scrollbar(f22)
        self.gcode_en.grid(row=3,column=0,pady=2,sticky=E+W)
        self.gcode_en_sc.grid(row=3,column=1,padx=2,pady=2,sticky=N+S)
        self.gcode_en_sc.config(command=self.gcode_en.yview)
        self.gcode_en.config(yscrollcommand=self.gcode_en_sc.set)

        f22.columnconfigure(0,weight=1)
        f22.rowconfigure(1,weight=0)
        f22.rowconfigure(3,weight=0)
# вкладка Img
 
        f33=Frame(self.nb_f3,relief = FLAT,bd = 1)
        f33.grid(row=0,column=0,padx=2,pady=2,sticky=N+W+E)
        f33.columnconfigure(0,weight=1)
        self.im = PhotoImage(file='G71.gif')  
        self.gif = Label(f33 , image=self.im)
        self.gif.grid(row=0,column=0,columnspan=2,sticky=N+W,padx=2)


        f33.columnconfigure(0,weight=1)
        f33.rowconfigure(1,weight=0)
        f33.rowconfigure(3,weight=0)
      

 
class CanvasClass:
    def __init__(self, master = None,text=None):
        
        self.master=master
        self.Content=[]

        self.lastevent=[]
        self.sel_rect_hdl=[]
        self.dir_var = IntVar()
        self.dx=0.0
        self.dy=0.0
        self.scale=1.0


        self.label=Label(self.master, text="Curser Coordinates: X=0.0, Y=0.0, Scale: 1.00",bg="white",anchor="w")
        self.label.grid(row=1,column=0,sticky=E+W)
        
        self.var = IntVar()
        self.cbutt = Checkbutton(self.master,text="Revers",variable=self.var,command=lambda: self.Content.switch_shape_dir)
        self.cbutt.grid(row=2,column=1,sticky=E+W)
        
        self.canvas=Canvas(self.master,width=650,height=500, bg = "white")
        self.canvas.grid(row=0,column=0,sticky=N+E+S+W)
        self.master.columnconfigure(0,weight=1)
        self.master.rowconfigure(0,weight=1)
        for i in range(25):
            self.canvas.create_oval(5+(4*i),5+(3*i),(5*i)+60,(i)+60, fill='gray70')

        self.canvas.bind("<Motion>", self.moving)

        self.canvas.bind("<Button-1>", self.select_cont)
        
        self.canvas.bind("<Shift-Button-1>", self.multiselect_cont)
        self.canvas.bind("<B1-Motion>", self.select_rectangle)
        self.canvas.bind("<ButtonRelease-1>", self.select_release)

        self.canvas.bind("<Button-3>", self.make_contextmenu)

        self.canvas.bind("<Control-Button-1>", self.mouse_move)
        self.canvas.bind("<Control-B1-Motion>", self.mouse_move_motion)
        self.canvas.bind("<Control-ButtonRelease-1>", self.mouse_move_release)
        self.canvas.bind("<Control-Button-3>", self.mouse_zoom)
        self.canvas.bind("<Control-B3-Motion>", self.mouse_zoom_motion)
        self.canvas.bind("<Control-ButtonRelease-3>", self.mouse_zoom_release) 
          
    def revers_contour(self,event):
        a=self.Content.select_cont


    def moving(self,event):
        x=self.dx+(event.x/self.scale)
        y=self.dy+(self.canvas.winfo_height()-event.y)/self.scale

        if self.scale<1:
            self.label['text']=("Curser Coordinates: X= %5.0f Y= %5.0f , Scale: %5.3f" \
                                %(x,y,self.scale))
            
        elif (self.scale>=1)and(self.scale<10):      
            self.label['text']=("Curser Coordinates: X= %5.1f Y= %5.1f , Scale: %5.2f" \
                                %(x,y,self.scale))
        elif self.scale>=10:      
            self.label['text']=("Curser Coordinates: X= %5.2f Y= %5.2f , Scale: %5.1f" \
                                %(x,y,self.scale))
        
    def select_cont(self,event):
        self.schliesse_contextmenu()
        
        self.moving(event)
        self.Content.deselect()
        self.sel_rect_hdl=Rectangle(self.canvas,event.x,event.y,event.x,event.y,outline="grey") 
        self.lastevent=event

    def multiselect_cont(self,event):
        self.schliesse_contextmenu()
        
        self.sel_rect_hdl=Rectangle(self.canvas,event.x,event.y,event.x,event.y,outline="grey") 
        self.lastevent=event

    def select_rectangle(self,event):
        self.moving(event)
        self.canvas.coords(self.sel_rect_hdl,self.lastevent.x,self.lastevent.y,\
                           event.x,event.y)

    def select_release(self,event):
 
        dx=self.lastevent.x-event.x
        dy=self.lastevent.y-event.y
        self.canvas.delete(self.sel_rect_hdl)
        
        
        if (abs(dx)+abs(dy))>6:
            items=self.canvas.find_overlapping(event.x,event.y,event.x+dx,event.y+dy)
            mode='multi'
        else:
            items=self.canvas.find_overlapping(event.x-3,event.y-3,event.x+3,event.y+3)
            mode='single'
            
        self.Content.addselection(items,mode)

    def mouse_move(self,event):
        self.master.config(cursor="fleur")
        self.lastevent=event

    def mouse_move_motion(self,event):
        self.moving(event)
        dx=event.x-self.lastevent.x
        dy=event.y-self.lastevent.y
        self.dx=self.dx-dx/self.scale
        self.dy=self.dy+dy/self.scale
        self.canvas.move(ALL,dx,dy)
        self.lastevent=event

    def mouse_move_release(self,event):
        self.master.config(cursor="")      

    def mouse_zoom(self,event):
        self.canvas.focus_set()
        self.master.config(cursor="sizing")
        self.firstevent=event
        self.lastevent=event

    def mouse_zoom_motion(self,event):
        self.moving(event)
        dy=self.lastevent.y-event.y
        sca=(1+(dy*3)/float(self.canvas.winfo_height()))
       
        self.dx=(self.firstevent.x+((-self.dx*self.scale)-self.firstevent.x)*sca)/sca/-self.scale
        eventy=self.canvas.winfo_height()-self.firstevent.y
        self.dy=(eventy+((-self.dy*self.scale)-eventy)*sca)/sca/-self.scale
        
        self.scale=self.scale*sca
        self.canvas.scale( ALL, self.firstevent.x,self.firstevent.y,sca,sca)
        self.lastevent=event

        self.Content.plot_cut_info() 
        self.Content.plot_wp_zero()

    def mouse_zoom_release(self,event):
        self.master.config(cursor="")
                
    def make_contextmenu(self,event):
        self.lastevent=event

        self.schliesse_contextmenu()
            
        popup = Menu(self.canvas,tearoff=0)
        self.popup=popup
        popup.add_command(label='Invert Selection',command=self.Content.invert_selection)
        popup.add_command(label='Disable Selection',command=self.Content.disable_selection)
        popup.add_command(label='Enable Selection',command=self.Content.enable_selection)

        popup.add_separator()
        popup.add_command(label='Switch Direction',command=self.Content.switch_shape_dir)
        
        self.dir_var.set(self.Content.calc_dir_var())
        cut_cor_menu = Menu(popup,tearoff=0)
        cut_cor_menu.add_checkbutton(label="G40 No correction",\
                                     variable=self.dir_var,onvalue=0,\
                                     command=lambda:self.Content.set_cut_cor(40))
        cut_cor_menu.add_checkbutton(label="G41 Cutting left",\
                                     variable=self.dir_var,onvalue=1,\
                                     command=lambda:self.Content.set_cut_cor(41))
        cut_cor_menu.add_checkbutton(label="G42 Cutting right",\
                                     variable=self.dir_var,onvalue=2,\
                                     command=lambda:self.Content.set_cut_cor(42))
        popup.add_cascade(label='Set Cutter Correction',menu=cut_cor_menu)

        if len(self.Content.Selected)==0:
            popup.entryconfig(0,state=DISABLED)
            popup.entryconfig(1,state=DISABLED)
            popup.entryconfig(2,state=DISABLED)
            popup.entryconfig(4,state=DISABLED)
            popup.entryconfig(5,state=DISABLED)

        popup.post(event.x_root, event.y_root)
        
    def schliesse_contextmenu(self):
        try:
            self.popup.destroy()
            del(self.popup)
        except:
            pass

    def autoscale(self):

        rand=20

        self.canvas.move(ALL,self.dx*self.scale,-self.canvas.winfo_height()-self.dy*self.scale)
        self.dx=0;
        self.dy=-self.canvas.winfo_height()/self.scale

        d=self.canvas.bbox(ALL)
        cx=(d[0]+d[2])/2
        cy=(d[1]+d[3])/2
        dx=d[2]-d[0]
        dy=d[3]-d[1]

        xs=float(dx)/(self.canvas.winfo_width()-rand)
        ys=float(dy)/(self.canvas.winfo_height()-rand)
        scale=1/max(xs,ys)
        
        self.canvas.scale( ALL,0,0,scale,scale)
        self.scale=self.scale*scale

        dx=self.canvas.winfo_width()/2-cx*scale
        dy=self.canvas.winfo_height()/2-cy*scale
        self.dy=self.dy/scale
        self.dx=self.dx/scale
        self.canvas.move(ALL,dx,dy)
        
        self.dx=self.dx-dx/self.scale
        self.dy=self.dy+dy/self.scale

        self.Content.plot_cut_info()
        self.Content.plot_wp_zero()
        
    def get_can_coordinates(self,x_st,y_st):
        x_ca=(x_st-self.dx)*self.scale
        y_ca=(y_st-self.dy)*self.scale-self.canvas.winfo_height()
        return x_ca, y_ca

    def scale_contours(self,delta_scale):     
        self.scale=self.scale/delta_scale
        self.dx=self.dx*delta_scale
        self.dy=self.dy*delta_scale

        event=PointClass(x=0,y=0)
        self.moving(event)

        for shape in self.Content.Shapes:
            shape.sca[0]=shape.sca[0]*delta_scale
            shape.sca[1]=shape.sca[1]*delta_scale
            shape.sca[2]=shape.sca[2]*delta_scale
            
            shape.p0=shape.p0*[delta_scale,delta_scale]

    def move_wp_zero(self,delta_dx,delta_dy):
        self.dx=self.dx-delta_dx
        self.dy=self.dy-delta_dy

        for shape in self.Content.Shapes:
            shape.p0-=PointClass(x=delta_dx,y=delta_dy)

        self.Content.plot_wp_zero()
        
class CanvasContentClass:
    def __init__(self,Canvas,textbox,config):
        self.Canvas=Canvas
        self.textbox=textbox
        self.config=config
        self.Shapes=[]
        self.LayerContents=[]
        self.EntitieContents=[]
        self.Selected=[]
        self.Disabled=[]
        self.wp_zero_hdls=[]
        self.dir_hdls=[]
        self.path_hdls=[]
        

        self.toggle_wp_zero=IntVar()
        self.toggle_wp_zero.set(1)

        self.toggle_start_stop=IntVar()
        self.toggle_start_stop.set(1) #показывать стрелки направления контура при старте

        self.toggle_show_disabled=IntVar()
        self.toggle_show_disabled.set(0)  
        
    def __str__(self):
        s='\nNr. of Shapes ->'+str(len(self.Shapes))
        for lay in self.LayerContents:
            s=s+'\n'+str(lay)
        for ent in self.EntitieContents:
            s=s+'\n'+str(ent)
        s=s+'\nSelected ->'+str(self.Selected)\
           +'\nDisabled ->'+str(self.Disabled)
        return s

    def calc_dir_var(self):
        if len(self.Selected)==0:
            return -1
        dir=self.Shapes[self.Selected[0]].cut_cor
        for shape_nr in self.Selected[1:len(self.Selected)]: 
            if not(dir==self.Shapes[shape_nr].cut_cor):
                return -1   
        return dir-40
                
    def makeplot(self,values):
        self.values=values

        self.Canvas.canvas.delete(ALL)
        
        self.Canvas.scale=1
        self.Canvas.dx=0
        self.Canvas.dy=-self.Canvas.canvas.winfo_height()

        self.Shapes=[]
        self.LayerContents=[]
        self.EntitieContents=[]
        self.Selected=[]
        self.Disabled=[]
        self.wp_zero_hdls=[]
        self.dir_hdls=[]
        self.path_hdls=[]

        self.make_shapes(p0=PointClass(x=0,y=0),sca=[1,1,1])
        self.plot_shapes()
        self.LayerContents.sort()
        self.EntitieContents.sort()

        self.Canvas.autoscale()

    def make_shapes(self,ent_nr=-1,p0=PointClass(x=0,y=0),sca=[1,1,1]):
        if ent_nr==-1:
            entities=self.values.entities
        else:
            entities=self.values.blocks.Entities[ent_nr]
        ent_geos=entities.geo
        cont=entities.cont
        for c_nr in range(len(cont)):
            if ent_geos[cont[c_nr].order[0][0]].Typ=="Insert":
                ent_geo=ent_geos[cont[c_nr].order[0][0]]
                self.make_shapes(ent_geo.Block,ent_geo.Point,ent_geo.Scale)
            else:
                self.Shapes.append(ShapeClass(len(self.Shapes),ent_nr,c_nr,cont[c_nr].closed,p0,sca[:],40,cont[c_nr].length*sca[0],[],[]))
                for ent_geo_nr in range(len(cont[c_nr].order)):
                    ent_geo=ent_geos[cont[c_nr].order[ent_geo_nr][0]]
                    if cont[c_nr].order[ent_geo_nr][1]:
                        ent_geo.geo.reverse()
                        for geo in ent_geo.geo:
                            geo=copy(geo)
                            geo.reverse()
                            self.Shapes[-1].geos.append(geo)

                        ent_geo.geo.reverse()
                    else:
                        for geo in ent_geo.geo:
                            self.Shapes[-1].geos.append(copy(geo))
                        
                self.addtoLayerContents(self.Shapes[-1].nr,ent_geo.Layer_Nr)
                self.addtoEntitieContents(self.Shapes[-1].nr,ent_nr,c_nr)

    def plot_shapes(self):
        for shape in self.Shapes:
            shape.plot2can(self.Canvas.canvas)
            
    def plot_wp_zero(self):
        for hdl in self.wp_zero_hdls:
            self.Canvas.canvas.delete(hdl) 
        self.wp_zero_hdls=[]
        if self.toggle_wp_zero.get(): 
            x_zero,y_zero=self.Canvas.get_can_coordinates(0,0)
            xy=x_zero-8,-y_zero-8,x_zero+8,-y_zero+8
            hdl=Oval(self.Canvas.canvas,xy,outline="gray")
            self.wp_zero_hdls.append(hdl)

            xy=x_zero-6,-y_zero-6,x_zero+6,-y_zero+6
            hdl=Arc(self.Canvas.canvas,xy,start=0,extent=180,style="pieslice",outline="gray")
            self.wp_zero_hdls.append(hdl)
            hdl=Arc(self.Canvas.canvas,xy,start=90,extent=180,style="pieslice",outline="gray")
            self.wp_zero_hdls.append(hdl)
            hdl=Arc(self.Canvas.canvas,xy,start=270,extent=90,style="pieslice",outline="gray",fill="gray")
            self.wp_zero_hdls.append(hdl)
    def plot_cut_info(self):
        for hdl in self.dir_hdls:
            self.Canvas.canvas.delete(hdl) 
        self.dir_hdls=[]
       
        if not(self.toggle_start_stop.get()):
            draw_list=self.Selected[:]
        else:
            draw_list=range(len(self.Shapes))    
        for shape_nr in draw_list:
            if not(shape_nr in self.Disabled):
                self.dir_hdls+=self.Shapes[shape_nr].plot_cut_info(self.Canvas,self.config)


    def plot_opt_route(self,shapes_st_en_points,route):
        for en_nr in range(len(route)):
            if en_nr==0:
                st_nr=-1
                col='gray'
            elif en_nr==1:
                st_nr=en_nr-1
                col='gray'
            else:
                st_nr=en_nr-1
                col='peru'
                
            st=shapes_st_en_points[route[st_nr]][1]
            en=shapes_st_en_points[route[en_nr]][0]

            x_ca_s,y_ca_s=self.Canvas.get_can_coordinates(st.x,st.y)
            x_ca_e,y_ca_e=self.Canvas.get_can_coordinates(en.x,en.y)

            self.path_hdls.append(Line(self.Canvas.canvas,x_ca_s,-y_ca_s,x_ca_e,-y_ca_e,fill=col,arrow='last'))
        self.Canvas.canvas.update()


    def addtoLayerContents(self,shape_nr,lay_nr):
        for LayCon in self.LayerContents:
            if LayCon.LayerNr==lay_nr:
                LayCon.Shapes.append(shape_nr)
                return

        LayerName=self.values.layers[lay_nr].name
        self.LayerContents.append(LayerContentClass(lay_nr,LayerName,[shape_nr]))
        
    def addtoEntitieContents(self,shape_nr,ent_nr,c_nr):
        
        for EntCon in self.EntitieContents:
            if EntCon.EntNr==ent_nr:
                if c_nr==0:
                    EntCon.Shapes.append([])
                
                EntCon.Shapes[-1].append(shape_nr)
                return

        if ent_nr==-1:
            EntName='Entities'
        else:
            EntName=self.values.blocks.Entities[ent_nr].Name
            
        self.EntitieContents.append(EntitieContentClass(ent_nr,EntName,[[shape_nr]]))

    def delete_opt_path(self):
        for hdl in self.path_hdls:
            self.Canvas.canvas.delete(hdl)
            
        self.path_hdls=[]
        
    def deselect(self): 
        self.set_shapes_color(self.Selected,'deselected')
        
        if not(self.toggle_start_stop.get()):
            for hdl in self.dir_hdls:
                self.Canvas.canvas.delete(hdl) 
            self.dir_hdls=[]
        
    def addselection(self,items,mode):
        for item in items:
            try:
                tag=int(self.Canvas.canvas.gettags(item)[-1])
                if not(tag in self.Selected):
                    self.Selected.append(tag)

                    self.textbox.prt('\n\nAdded shape to selection:'\
                                     +str(self.Shapes[tag]),3)
                    
                    if mode=='single':
                        break
            except:
                pass
 
        self.plot_cut_info()
        self.set_shapes_color(self.Selected,'selected')
 
    def invert_selection(self):
        new_sel=[]
        for shape_nr in range(len(self.Shapes)):
            if (not(shape_nr in self.Disabled)) & (not(shape_nr in self.Selected)):
                new_sel.append(shape_nr)

        self.deselect()
        self.Selected=new_sel
        self.set_shapes_color(self.Selected,'selected')
        self.plot_cut_info()

        self.textbox.prt('\nInverting Selection',3)
        

    def disable_selection(self):
        for shape_nr in self.Selected:
            if not(shape_nr in self.Disabled):
                self.Disabled.append(shape_nr)
        self.set_shapes_color(self.Selected,'disabled')
        self.Selected=[]
        self.plot_cut_info()

    def enable_selection(self):
        for shape_nr in self.Selected:
            if shape_nr in self.Disabled:
                nr=self.Disabled.index(shape_nr)
                del(self.Disabled[nr])
        self.set_shapes_color(self.Selected,'deselected')
        self.Selected=[]
        self.plot_cut_info()

    def show_disabled(self):
        if (self.toggle_show_disabled.get()==1):
            self.set_hdls_normal(self.Disabled)
            self.show_dis=1
        else:
            self.set_hdls_hidden(self.Disabled)
            self.show_dis=0
            
    def switch_shape_dir(self):
        for shape_nr in self.Selected:
            self.Shapes[shape_nr].reverse()
            self.textbox.prt('\n\nSwitched Direction at Shape:'\
                             +str(self.Shapes[shape_nr]))
        self.plot_cut_info()

                
    def set_cut_cor(self,correction):
        for shape_nr in self.Selected: 
            self.Shapes[shape_nr].cut_cor=correction
            
            self.textbox.prt('\n\nChanged Cutter Correction at Shape:'\
                             +str(self.Shapes[shape_nr]),3)
        self.plot_cut_info() 
        
    def set_shapes_color(self,shape_nrs,state):
        s_shape_nrs=[]
        d_shape_nrs=[]
        for shape in shape_nrs:
            if not(shape in self.Disabled):
                s_shape_nrs.append(shape)
            else:
                d_shape_nrs.append(shape)
        
        s_hdls=self.get_shape_hdls(s_shape_nrs)
        d_hdls=self.get_shape_hdls(d_shape_nrs)
    
        if state=='deselected':
            s_color='black'
            d_color='gray'
            self.Selected=[]
        elif state=='selected':
            s_color='red'
            d_color='blue'
        elif state=='disabled':
            s_color='gray'
            d_color='gray'
            
        self.set_color(s_hdls,s_color)
        self.set_color(d_hdls,d_color)

        if (self.toggle_show_disabled.get()==0):
            self.set_hdls_hidden(d_shape_nrs)
        
    def set_color(self,hdls,color):
        for hdl in hdls:
            if (self.Canvas.canvas.type(hdl)=="oval") :
                self.Canvas.canvas.itemconfig(hdl, outline=color)
            else:
                self.Canvas.canvas.itemconfig(hdl, fill=color)

    def set_hdls_hidden(self,shape_nrs):
        hdls=self.get_shape_hdls(shape_nrs)
        for hdl in hdls:
            self.Canvas.canvas.itemconfig(hdl,state='hidden')

    def set_hdls_normal(self,shape_nrs):
        hdls=self.get_shape_hdls(shape_nrs)
        for hdl in hdls:
            self.Canvas.canvas.itemconfig(hdl,state='normal')            
        
    def get_shape_hdls(self,shape_nrs):        
        hdls=[]
        for s_nr in shape_nrs:
            if type(self.Shapes[s_nr].geos_hdls[0]) is list:
                for subcont in self.Shapes[s_nr].geos_hdls:
                    hdls=hdls+subcont
            else:
                hdls=hdls+self.Shapes[s_nr].geos_hdls
        return hdls      
                                       
       
class LayerContentClass:
    def __init__(self,LayerNr=None,LayerName='',Shapes=[]):
        self.LayerNr=LayerNr
        self.LayerName=LayerName
        self.Shapes=Shapes
        
    def __cmp__(self, other):
         return cmp(self.LayerNr, other.LayerNr)

    def __str__(self):
        return '\nLayerNr ->'+str(self.LayerNr)+'\nLayerName ->'+str(self.LayerName)\
               +'\nShapes ->'+str(self.Shapes)
    
class EntitieContentClass:
    def __init__(self,EntNr=None,EntName='',Shapes=[]):
        self.EntNr=EntNr
        self.EntName=EntName
        self.Shapes=Shapes

    def __cmp__(self, other):
         return cmp(self.EntNr, other.EntNr)        
        
    def __str__(self):
        return '\nEntNr ->'+str(self.EntNr)+'\nEntName ->'+str(self.EntName)\
               +'\nShapes ->'+str(self.Shapes)

class ConfigClass:
    def __init__(self,textbox):
        self.folder=self.get_settings_folder(str(APPNAME))

        self.parser = ConfigParser.ConfigParser()
        self.cfg_file_name=APPNAME+'_config.cfg'
        self.parser.read(os.path.join(self.folder,self.cfg_file_name))

        if len(self.parser.sections())==0:
            self.make_new_Config_file()
            self.parser.read(os.path.join(self.folder,self.cfg_file_name))
            textbox.prt(('\nNo config file found generated new on at: %s' \
                             %os.path.join(self.folder,self.cfg_file_name)))
        else:
            textbox.prt(('\nLoading config file:%s' \
                             %os.path.join(self.folder,self.cfg_file_name)))

        self.get_all_vars()

        textbox.set_debuglevel(DEBUG=self.debug)
        textbox.prt('\nDebug Level: ' +str(self.debug),1)
        textbox.prt(str(self),1)

    def get_settings_folder(self,appname): 
 
        folder = os.path.join(os.getcwd(), appname) 

        try: 
            os.mkdir(folder) 
        except OSError: 
            pass 

        return folder 

    def make_new_Config_file(self):
        pass
            
    def get_all_vars(self):
        try:               
            self.tool_dia=DoubleVar()
            self.tool_dia.set(float(2.333))
 ####################################################################### настройки по дефолту           
            self.depth_D = DoubleVar()
            self.depth_D.set(float(self.parser.get('Parameters','depth_D')))
            
            self.finishing_depth = DoubleVar()
            self.finishing_depth.set(float(self.parser.get('Parameters','finishing_depth')))
                       
            self.feedrate_F = DoubleVar()
            self.feedrate_F.set(float(self.parser.get('Parameters','feedrate_F'))) 
                       
            self.ending_block_Q = DoubleVar()
            self.ending_block_Q.set(float(self.parser.get('Parameters','ending_block_Q')))         
           
            self.start_Z0  = IntVar()
            self.start_Z0.set(float(self.parser.get('Parameters','start_Z0'))) 
            
            self.tool_T  = IntVar()
            self.tool_T.set(int(self.parser.get('Parameters','tool_T'))) 
            
            self.reserve_S  = IntVar()
            self.reserve_S.set(float(self.parser.get('Parameters','reserve_S')))
            
            self.reserve_L  = IntVar()
            self.reserve_L.set(float(self.parser.get('Parameters','reserve_L')))            
            
            self.quantity_I  = IntVar()
            self.quantity_I.set(float(self.parser.get('Parameters','quantity_I')))            

            self.tempfile_gcode = self.parser.get('Paths','tempfile_gcode')
            self.editfilename = self.parser.get('Paths','editfilename')
            
            
            
            
            
            self.start_rad=DoubleVar()
            self.start_rad.set(float(self.parser.get('Parameters','start_radius')))        
           
            self.axis1_st_en=DoubleVar()
            self.axis1_st_en.set(float(self.parser.get('Plane Coordinates','axis1_start_end')))

            self.axis2_st_en=DoubleVar()
            self.axis2_st_en.set(float(self.parser.get('Plane Coordinates','axis2_start_end')))        
            
            self.axis3_retract=DoubleVar()
            self.axis3_retract.set(float(self.parser.get('Depth Coordinates','axis3_retract')))
            
            self.axis3_safe_margin=DoubleVar()
            self.axis3_safe_margin.set(float(self.parser.get('Depth Coordinates','axis3_safe_margin')))

            self.axis3_slice_depth=DoubleVar()
            self.axis3_slice_depth.set(float(self.parser.get('Depth Coordinates','axis3_slice_depth')))        

            self.axis3_mill_depth=DoubleVar()
            self.axis3_mill_depth.set(float(self.parser.get('Depth Coordinates','axis3_mill_depth')))        
            
            self.F_G1_Depth=DoubleVar()
            self.F_G1_Depth.set(float(self.parser.get('Feed Rates','f_g1_depth')))

            self.F_G1_Plane=DoubleVar()
            self.F_G1_Plane.set(float(self.parser.get('Feed Rates','f_g1_plane')))

            self.points_tolerance=DoubleVar()
            self.points_tolerance.set(float(self.parser.get('Import Parameters','point_tolerance')))

            self.fitting_tolerance=DoubleVar()
            self.fitting_tolerance.set(float(self.parser.get('Import Parameters','fitting_tolerance')))

            self.begin_art=self.parser.get('Route Optimisation', 'Begin art')
            self.max_population=int((int(self.parser.get('Route Optimisation', 'Max. population'))/4)*4)
            self.max_iterations=int(self.parser.get('Route Optimisation', 'Max. iterations'))  
            self.mutate_rate=float(self.parser.get('Route Optimisation', 'Mutation Rate', 0.95))

            self.ax1_letter=self.parser.get('Axis letters', 'ax1_letter')
            self.ax2_letter=self.parser.get('Axis letters', 'ax2_letter')
            self.ax3_letter=self.parser.get('Axis letters', 'ax3_letter')

            self.load_path=self.parser.get('Paths','load_path')
            self.save_path=self.parser.get('Paths','save_path')          

            self.debug=int(self.parser.get('Debug', 'global_debug_level'))

            self.b_D_out = DoubleVar()
            self.b_D_out.set(float(self.parser.get('Parameters','b_D_out')))
            
            self.b_L = DoubleVar()
            self.b_L.set(float(self.parser.get('Parameters','b_L')))            
            
             
            self.b_D_in = DoubleVar()
            self.b_D_in.set(float(self.parser.get('Parameters','b_D_in')))           
                       
            
        except:
            showerror("Error during reading config file", "Please delete or correct\n %s"\
                      %(os.path.join(self.folder,self.cfg_file_name)))
            raise Exception, "Problem during import from INI File" 
            
    def __str__(self):

        str=''
        for section in self.parser.sections(): 
            str= str +"\nSection: "+section 
            for option in self.parser.options(section): 
                str= str+ "\n   -> %s=%s" % (option, self.parser.get(section, option))
        return str

class PostprocessorClass:
    def __init__(self,config=None,textbox=None):
        self.string=''
        self.textbox=textbox
        self.config=config

        self.parser = ConfigParser.ConfigParser()
        self.postpro_file_name=APPNAME+'_postprocessor.cfg'
        self.parser.read(os.path.join(config.folder,self.postpro_file_name))

        if len(self.parser.sections())==0:
            self.make_new_postpro_file()
            self.parser.read(os.path.join(config.folder,self.postpro_file_name))
            textbox.prt(('\nNo postprocessor file found generated new on at: %s' \
                             %os.path.join(config.folder,self.postpro_file_name)))
        else:
            textbox.prt(('\nLoading postprocessor file: %s' \
                             %os.path.join(self.config.folder,self.postpro_file_name)))

        self.get_all_vars()

        textbox.prt(str(self),1)        

    def get_all_vars(self):
        self.abs_export=int(self.parser.get('General', 'abs_export'))
        self.write_to_stdout=int(self.parser.get('General', 'write_to_stdout'))
        self.gcode_be=self.parser.get('General', 'code_begin')
        self.gcode_en=self.parser.get('General', 'code_end')

        self.pre_dec=int(self.parser.get('Number format','pre_decimals'))
        self.post_dec=int(self.parser.get('Number format','post_decimals'))
        self.dec_sep=self.parser.get('Number format','decimal_seperator')
        self.pre_dec_z_pad=int(self.parser.get('Number format','pre_decimal_zero_padding'))
        self.post_dec_z_pad=int(self.parser.get('Number format','post_decimal_zero_padding'))
        self.signed_val=int(self.parser.get('Number format','signed_values'))

        self.use_line_nrs=int(self.parser.get('Line numbers','use_line_nrs'))
        self.line_nrs_begin=int(self.parser.get('Line numbers','line_nrs_begin'))
        self.line_nrs_step=int(self.parser.get('Line numbers','line_nrs_step'))

        self.tool_ch_str=self.parser.get('Program','tool_change')
        self.feed_ch_str=self.parser.get('Program','feed_change')
        self.rap_pos_plane_str=self.parser.get('Program','rap_pos_plane')
        self.rap_pos_depth_str=self.parser.get('Program','rap_pos_depth')
        self.lin_mov_plane_str=self.parser.get('Program','lin_mov_plane')
        self.lin_mov_depth_str=self.parser.get('Program','lin_mov_depth')
        self.arc_int_cw=self.parser.get('Program','arc_int_cw')
        self.arc_int_ccw=self.parser.get('Program','arc_int_ccw')
        self.cut_comp_off_str=self.parser.get('Program','cutter_comp_off')
        self.cut_comp_left_str=self.parser.get('Program','cutter_comp_left')
        self.cut_comp_right_str=self.parser.get('Program','cutter_comp_right')                        
                        
        self.feed=0
        self.x=self.config.axis1_st_en.get()
        self.y=self.config.axis2_st_en.get()
        self.z=self.config.axis3_retract.get()
        self.lx=self.x
        self.ly=self.y
        self.lz=self.z
        self.i=0.0
        self.j=0.0
        if self.diameter_mode():
            self.vars={"%feed":'self.iprint(self.feed)',\
                       "%nl":'self.nlprint()',\
                       "%X":'self.fnprint(self.x*2)',\
                       "%-X":'self.fnprint(-self.x)',\
                       "%Y":'self.fnprint(self.y)',\
                       "%-Y":'self.fnprint(-self.y)',\
                       "%Z":'self.fnprint(self.z)',\
                       "%-Z":'self.fnprint(-self.z)',\
                       "%I":'self.fnprint(self.i)',\
                       "%-I":'self.fnprint(-self.i)',\
                       "%J":'self.fnprint(self.j)',\
                       "%-J":'self.fnprint(-self.j)'}
        else:
            self.vars={"%feed":'self.iprint(self.feed)',\
                   "%nl":'self.nlprint()',\
                   "%X":'self.fnprint(self.x)',\
                   "%-X":'self.fnprint(-self.x)',\
                   "%Y":'self.fnprint(self.y)',\
                   "%-Y":'self.fnprint(-self.y)',\
                   "%Z":'self.fnprint(self.z)',\
                   "%-Z":'self.fnprint(-self.z)',\
                   "%I":'self.fnprint(self.i)',\
                   "%-I":'self.fnprint(-self.i)',\
                   "%J":'self.fnprint(self.j)',\
                   "%-J":'self.fnprint(-self.j)'}                   

    def diameter_mode(self):
        self.sgg =("%s\n" %self.gcode_be)
        if re.search("\s*G7[^0-9]", self.sgg, re.I):
            return 1
        else:
        
            return 1
    def make_new_postpro_file(self):
        pass

    def write_gcode_be(self,ExportParas,load_filename):
        str=("(File: %s)\n" %load_filename)
        self.string=(str.encode("utf-8"))    
        self.string+=("%s\n" %ExportParas.gcode_be.get(1.0,END).strip())

    def write_gcode_en(self,ExportParas):
        self.string+=ExportParas.gcode_en.get(1.0,END)

        self.make_line_numbers()        
        
        return self.string

    def make_line_numbers(self):
        line_format='N%i ' 
        if self.use_line_nrs:
            nr=0
            line_nr=self.line_nrs_begin
            self.string=((line_format+'%s') %(line_nr,self.string))
            nr=self.string.find('\n',nr)
            while not(nr==-1):
                line_nr+=self.line_nrs_step  
                self.string=(('%s'+line_format+'%s') %(self.string[0:nr+1],\
                                          line_nr,\
                                          self.string[nr+1:len(self.string)]))
                
                nr=self.string.find('\n',nr+len(((line_format) %line_nr))+2)
                          
            
            
    def chg_feed_rate(self,feed):
        self.feed=feed
        
    def set_cut_cor(self,cut_cor):
        self.cut_cor=cut_cor

               
    def lin_pol_arc(self,dir,ende,IJ):
        if not(self.abs_export):
            self.x=ende.x-self.lx
            self.y=ende.y-self.lx
            self.lx=ende.x
            self.ly=ende.y
        else:
            self.x=ende.x
            self.y=ende.y

        self.i=IJ.x
        self.j=IJ.y

        if dir=='cw':
            self.string+=self.make_print_str(self.arc_int_cw)
        else:
            self.string+=self.make_print_str(self.arc_int_ccw)

          
    def rap_pos_z(self,z_pos):
        if not(self.abs_export):
            self.z=z_pos-self.lz
            self.lz=z_pos
        else:
            self.z=z_pos

        self.string+=self.make_print_str(self.rap_pos_depth_str)           
         
    def rap_pos_xy(self,newpos):
        if not(self.abs_export):
            self.x=newpos.x-self.lx
            self.lx=newpos.x
            self.y=newpos.y-self.ly
            self.ly=newpos.y
        else:
            self.x=newpos.x
            self.y=newpos.y

        self.string+=self.make_print_str(self.lin_mov_plane_str)        
    
    def lin_pol_z(self,z_pos):
        if not(self.abs_export):
            self.z=z_pos-self.lz
            self.lz=z_pos
        else:
            self.z=z_pos

        self.string+=self.make_print_str(self.lin_mov_depth_str)      
    def lin_pol_xy(self,newpos):
        if not(self.abs_export):
            self.x=newpos.x-self.lx
            self.lx=newpos.x
            self.y=newpos.y-self.ly
            self.ly=newpos.y
        else:
            self.x=newpos.x
            self.y=newpos.y

        self.string+=self.make_print_str(self.lin_mov_plane_str)       

    def make_print_str(self,string):
        new_string=string
        for key_nr in range(len(self.vars.keys())):
            new_string=new_string.replace(self.vars.keys()[key_nr],\
                                          eval(self.vars.values()[key_nr]))
        return new_string

    def iprint(self,interger):
        return ('%i' %interger)

    def nlprint(self):
        return '\n'

    def fnprint(self,number):
        string=''
        if (self.signed_val)and(self.pre_dec_z_pad):
            numstr=(('%+0'+str(self.pre_dec+self.post_dec+1)+\
                     '.'+str(self.post_dec)+'f') %number)
        elif (self.signed_val==0)and(self.pre_dec_z_pad):
            numstr=(('%0'+str(self.pre_dec+self.post_dec+1)+\
                    '.'+str(self.post_dec)+'f') %number)
        elif (self.signed_val)and(self.pre_dec_z_pad==0):
            numstr=(('%+'+str(self.pre_dec+self.post_dec+1)+\
                    '.'+str(self.post_dec)+'f') %number)
        elif (self.signed_val==0)and(self.pre_dec_z_pad==0):
            numstr=(('%'+str(self.pre_dec+self.post_dec+1)+\
                    '.'+str(self.post_dec)+'f') %number)
            
        string+=numstr[0:-(self.post_dec+1)]
        
        string_end=self.dec_sep
        string_end+=numstr[-(self.post_dec):]

        if self.post_dec_z_pad==0:
            while (len(string_end)>0)and((string_end[-1]=='0')or(string_end[-1]==self.dec_sep)):
                string_end=string_end[0:-1]                
        return string+string_end
    
    def __str__(self):

        str=''
        for section in self.parser.sections(): 
            str= str +"\nSection: "+section 
            for option in self.parser.options(section): 
                str= str+ "\n   -> %s=%s" % (option, self.parser.get(section, option))
        return str
        
class Show_About_Info(Toplevel):
    def __init__(self, parent):
        Toplevel.__init__(self, parent)
        self.transient(parent)

        self.title("About DXF2GCODE")
        self.parent = parent
        self.result = None

        body = Frame(self)
        self.initial_focus = self.body(body)
        body.pack(padx=5, pady=5)

        self.buttonbox()
        self.grab_set()

        if not self.initial_focus:
            self.initial_focus = self

        self.protocol("WM_DELETE_WINDOW", self.close)
        self.geometry("+%d+%d" % (parent.winfo_rootx()+50,
                                  parent.winfo_rooty()+50))

        self.initial_focus.focus_set()
        self.wait_window(self)

    def buttonbox(self):
        box = Frame(self)
        w = Button(box, text="OK", width=10, command=self.ok, default=ACTIVE)
        w.pack(padx=5, pady=5)
        self.bind("<Return>", self.ok)
        box.pack()

    def ok(self, event=None):   
        self.withdraw()
        self.update_idletasks()
        self.close()

    def close(self, event=None):
        self.parent.focus_set()
        self.destroy()

    def show_hand_cursor(self,event):
        event.widget.configure(cursor="hand1")
    def show_arrow_cursor(self,event):
        event.widget.configure(cursor="")
        
    def click(self,event):
        w = event.widget
        x, y = event.x, event.y
        tags = w.tag_names("@%d,%d" % (x, y))
        for t in tags:
            if t.startswith("href:"):
                webbrowser.open(t[5:])
                break


    def body(self, master):
        text = Text(master,width=40,height=8)
        text.pack()
        text.tag_config("a", foreground="blue", underline=1)
        text.tag_bind("a", "<Enter>", self.show_hand_cursor)
        text.tag_bind("a", "<Leave>", self.show_arrow_cursor)
        text.tag_bind("a", "<Button-1>", self.click)
        text.config(cursor="arrow")

        href = "https://github.com/nkp2169/G71"
        text.insert(END, "\nVersion Lathe")
        text.insert(END, "\nhttps://github.com/nkp2169/G71", ("a", "href:"+href))


class NotebookClass:    
    def __init__(self, master,width=0,height=0):

        self.active_fr = None
        self.count = 0
        self.choice = IntVar(0)

        self.dummy_x_fr = Frame(master, width=width, borderwidth=0)
        self.dummy_y_fr = Frame(master, height=height, borderwidth=0)
        self.dummy_x_fr.grid(row=0,column=1)
        self.dummy_x_fr.grid_propagate(0)
        self.dummy_y_fr.grid(row=1,rowspan=2,column=0)
        self.dummy_y_fr.grid_propagate(0)

        self.rb_fr = Frame(master, borderwidth=0)
        self.rb_fr.grid(row=1,column=1, sticky=N+W)
        
        self.screen_fr = Frame(master, borderwidth=2, relief=RIDGE)
        self.screen_fr.grid(row=2,column=1,sticky=N+W+E)

        master.rowconfigure(2,weight=1)
        master.columnconfigure(1,weight=1)
        

    def __call__(self):
        return self.screen_fr

    def add_screen(self, fr, title):

        b = Radiobutton(self.rb_fr,bd=1, text=title, indicatoron=0, \
                        variable=self.choice, value=self.count, \
                        command=lambda: self.display(fr))
        
        b.grid(column=self.count,row=0,sticky=N+E+W)
        self.rb_fr.columnconfigure(self.count,weight=1)

        fr.grid(sticky=N+W+E)
        self.screen_fr.columnconfigure(0,weight=1)
        fr.grid_remove()

        if not self.active_fr:
            fr.grid()
            self.active_fr = fr

        self.count += 1

        return b


    def display(self, fr):
        self.active_fr.grid_remove()
        fr.grid()
        self.active_fr = fr


         
class Tkinter_Variable_Dialog(Toplevel):
    def __init__(self, parent=None,title='Test Dialog',label=('label1','label2'),value=(0.0,0.0)):
        if not(len(label)==len(value)):
            raise Exception, "Number of labels different to number of values"

        self.label=label
        self.value=value
        self.result=False

        Toplevel.__init__(self, parent)
        self.transient(parent)

        self.title(title)
        self.parent = parent

        body = Frame(self)
        self.initial_focus = self.body(body)
        body.pack(padx=5, pady=5)

        self.buttonbox()
        self.grab_set()

        if not self.initial_focus:
            self.initial_focus = self

        self.protocol("WM_DELETE_WINDOW", self.cancel)
        self.geometry("+%d+%d" % (parent.winfo_rootx()+50,
                                  parent.winfo_rooty()+50))

        self.initial_focus.focus_set()
        self.wait_window(self)

    def buttonbox(self):
        
        box = Frame(self)

        w = Button(box, text="OK", width=10, command=self.ok, default=ACTIVE)
        w.pack(side=LEFT, padx=5, pady=5)
        w = Button(box, text="Cancel", width=10, command=self.cancel)
        w.pack(side=LEFT, padx=5, pady=5)

        self.bind("<Return>", self.ok)
        self.bind("<Escape>", self.cancel)

        box.pack()

    def ok(self, event=None):   
        self.withdraw()
        self.update_idletasks()
        self.apply()
        self.cancel()

    def cancel(self, event=None):
        self.parent.focus_set()
        self.destroy()

    def body(self, master):
        self.tkintervars=[]
        for row_nr in range(len(self.label)):
            self.tkintervars.append(DoubleVar())
            self.tkintervars[-1].set(self.value[row_nr])
            Label(master, text=self.label[row_nr]).grid(row=row_nr,padx=4,sticky=N+W)
            Entry(master,textvariable=self.tkintervars[row_nr],width=10).grid(row=row_nr, column=1,padx=4,sticky=N+W)

    def apply(self):
        self.result=[]
        for tkintervar in self.tkintervars:
            self.result.append(tkintervar.get())

if __name__ == "__main__":
   
    master = Tk()
    master.title("DXF 2 G-Code, Version 0.1")

    if len(sys.argv) > 1:
        Erstelle_Fenster(master,sys.argv[1])
    else:
        Erstelle_Fenster(master)

    master.mainloop()

    
nkp
Мастер
Сообщения: 8340
Зарегистрирован: 28 ноя 2011, 00:25
Репутация: 1589
Контактная информация:

Re: G71 , ... (remap)

Сообщение nkp »

для G7:
G71.tar
(2.11 МБ) 381 скачивание
Последний раз редактировалось nkp 14 дек 2016, 15:52, всего редактировалось 1 раз.
nkp
Мастер
Сообщения: 8340
Зарегистрирован: 28 ноя 2011, 00:25
Репутация: 1589
Контактная информация:

Re: G71 , ... (remap)

Сообщение nkp »

с R в gкоде (радиусами в дугах) тоже должно работать:
nkp
Мастер
Сообщения: 8340
Зарегистрирован: 28 ноя 2011, 00:25
Репутация: 1589
Контактная информация:

Re: G71 , ... (remap)

Сообщение nkp »

вопрос к токарям-практикам ;) :
чем (с практической точки зрения) отличается обработка G71 от G72 одного и того же контура
(вот конкретно к примеру этого:
Выделение_197.png (3629 просмотров) <a class='original' href='./download/file.php?id=112400&sid=3e4e03a161d349c3c28b98b7b4adc80b&mode=view' target=_blank>Загрузить оригинал (64.79 КБ)</a>
Выделение_196.png (3629 просмотров) <a class='original' href='./download/file.php?id=112401&sid=3e4e03a161d349c3c28b98b7b4adc80b&mode=view' target=_blank>Загрузить оригинал (64.54 КБ)</a>
что мы можем "выиграть" в первом или втором случае?
Ответить

Вернуться в «LinuxCNC»