示例#1
0
def main(gfile, args=None):
	start = datetime.now()
	name = gfile if isinstance(gfile,str) else gfile.name
	puts(colored.blue('Visualizing the file: %s\n Started: %s'%(name,datetime.now())))

	# Read in the gcode
	gcode = GCode(gfile, limit=None)
	gcode.parse()
	
	# parse the code into an array of tool moves
	tool = Tool(gcode)
	tool.uniq()
	box = tool.boundBox()
	
	# proces and save image
	ext = args.ext if args is not None else '.pdf'
	outfile = os.path.splitext(gfile.name)[0] + FILEENDING + ext
	print box
	print box[0:2]
	image = Image(outfile, gridsize=box[0:2])
	image.process(tool)
	image.save()

	# how long did this take?
  	puts(colored.green('Time to completion: %s'%(deltaTime(start))))
  	print
示例#2
0
文件: draw.py 项目: bradodarb/PyGRBL
def main(etch_file, args=None):
    start = datetime.now()
    name = etch_file if isinstance(etch_file, str) else etch_file.name
    puts(
        colored.blue('Visualizing the file: %s\n Started: %s' %
                     (name, datetime.now())))

    # Read in the gcode
    gcode = GCode(etch_file, limit=None)
    gcode.parse()

    # parse the code into an array of tool moves
    tool = Tool(gcode)
    box = tool.boundBox()

    # proces and save image
    outfile = os.path.splitext(etch_file.name)[0] + '.eps'
    print box
    print box[0:2]
    image = Drawing(outfile)  #, bbox=box)
    image.process(tool)
    image.save()

    # how long did this take?
    puts(colored.green('Time to completion: %s' % (deltaTime(start))))
    print
示例#3
0
def main(gfile, args=None):
    start = datetime.now()
    name = gfile if isinstance(gfile, str) else gfile.name
    puts(
        colored.blue('Visualizing the file: %s\n Started: %s' %
                     (name, datetime.now())))

    # Read in the gcode
    gcode = GCode(gfile, limit=None)
    gcode.parse()

    # parse the code into an array of tool moves
    tool = Tool(gcode)
    tool.uniq()
    box = tool.boundBox()

    # proces and save image
    ext = args.ext if args is not None else '.pdf'
    outfile = os.path.splitext(gfile.name)[0] + FILEENDING + ext
    print box
    print box[0:2]
    image = Image(outfile, gridsize=box[0:2])
    image.process(tool)
    image.save()

    # how long did this take?
    puts(colored.green('Time to completion: %s' % (deltaTime(start))))
    print
示例#4
0
 def __init__(self):
     self.tool = Tool()
     self.yml = self.tool.app_data
     self.devices = self.yml.get('devices')
     self.app = self.yml.get('tester')
     self.device_type = self.yml.get('device_type')
     self.ports = []
示例#5
0
文件: modify.py 项目: ajmendez/PyGRBL
def mod(gfile):
  '''For each of the files to process either rotate, move, copy, or
  replicate the code.  General idea:
    read in ascii
    Process into a toolpath list.
    modify.
    Write out toolpath.'''

  start = datetime.now()
  puts(colored.blue('Modifying file: %s\n Started: %s'%(gfile.name,datetime.now())))

  # Parse the gcode.
  gcode = GCode(gfile)
  gcode.parseAll()

  # Create a toolpath from the gcode
  # add in the index so that we can match it to the gcode


  out = []
  if args.move:
    loc = parse(args.move, getUnits=True) # only one move at a time.
    puts(colored.blue('Moving!\n    (0,0) -> (%.3f,%.3f)'%(loc[0],loc[1])))
    tool = Tool()
    # is the addIndex atribut even used any longer?
    tool.build(gcode, addIndex=True)
    tool.move(loc) # ok well this should work
    gcode.update(tool)
    out.append([loc,gcode])

  if args.copy:
    locs = parse(args.copy, getUnits=True)
    puts(colored.blue('Copying!'))
    for loc in locs:
      puts(colored.blue('    (0,0) -> (%.3f,%.3f)'%(loc[0],loc[1])))
      gc = gcode.copy()
      tool = Tool()
      # is the addIndex atribut even used any longer?
      tool.build(gc, addIndex=True)
      tool.move(loc)
      gc.update(tool)
      out.append([loc,gc])

  # if args.replicate:
  #   nxy = map(int,parse(args.replicate)[0]) # ensure int, and only one
  #   puts(colored.blue('Replicating!\n     nx=%i, ny=%i)'%(nxy[0],nxy[1])))

  output = ''.join([o.getGcode(tag=args.name,start=l) for l,o in out])

  outfile = FILEENDING.join(os.path.splitext(gfile.name))
  puts(colored.green('Writing: %s'%outfile))
  with open(outfile,'w') as f:
    f.write(output)

  # how long did this take?
  puts(colored.green('Time to completion: %s'%(deltaTime(start))))
  print
示例#6
0
 def __init__(self):
     self.tool = Tool()
     # 配置信息
     self.yml = self.tool.app_data
     # 所有手机配置信息
     self.devices = self.yml.get('devices')
     # 测试app的信息
     self.app = self.yml.get('tester')
     # Android OR iOS
     self.device_type = self.yml.get('device_type')
     # 用于校验服务是否成功,存储端口号
     self.ports = []
示例#7
0
    def run(self):
        #清理目录下存在的图片
        Tool().clear_picture()
        #生成测试套件
        suit = unittest.TestSuite()
        #获取测试用例
        cases = unittest.defaultTestLoader.discover(WEBCASE_PATH, '*.py')
        #循环添加测试用例至测试套件
        for case in cases:
            suit.addTest(case)
        #测试报告
        report_name = os.path.join(REPOR_TPATH, 'UI测试报告.html')
        f = open(report_name, 'wb')
        #以报告模版运行用例
        runner = HTMLTestRunner(f,
                                verbosity=1,
                                title='测试报告',
                                description='用例执行情况:')
        res = runner.run(suit)
        #将报告文件写入磁盘,并关闭文件
        f.flush()
        f.close()

        success = res.success_count
        failure = res.failure_count

        #发送报告邮件
        title = 'UI测试报告'
        msg = '''
        大家好:
            本次UI测试结果如下:
                通过用例:%s条。
                失败用例:%s条。
                详情信息请看附件【%s】
        ''' % (success, failure, os.path.basename(report_name))
 def __init__(self):
     self.tool = Tool()
     # 获取所有配置信息 字典格式
     self.yml = self.tool.app_data
     self.device_type = self.yml.get('device_type')
     self.tester = self.yml.get('tester')
     self.devices = self.yml.get('devices')
     self.deviceName = self.devices.get(
         self.device_type)[0].get('deviceName')
     self.ports = []
示例#9
0
文件: draw.py 项目: ajmendez/PyGRBL
def main(etch_file, args=None):
	start = datetime.now()
	name = etch_file if isinstance(etch_file,str) else etch_file.name
	puts(colored.blue('Visualizing the file: %s\n Started: %s'%(name,datetime.now())))

	# Read in the gcode
	gcode = GCode(etch_file, limit=None)
	gcode.parse()
	
	# parse the code into an array of tool moves
	tool = Tool(gcode)
	box = tool.boundBox()
	
	# proces and save image
	outfile = os.path.splitext(etch_file.name)[0] + '.eps'
	print box
	print box[0:2]
	image = Drawing(outfile)#, bbox=box)
	image.process(tool)
	image.save()

	# how long did this take?
  	puts(colored.green('Time to completion: %s'%(deltaTime(start))))
  	print
示例#10
0
 def __init__(self):
     self.tool = Tool()
     #获取所有配置信息
     self.yml = self.tool.app_data
     #操作系统
     self.device_type = self.yml.get('device_type')
     #测试APP信息
     self.tester = self.yml.get('tester')
     #获取所有手机配置信息
     self.devices = self.yml.get('devices')
     #设备名称
     self.deviceName = self.devices.get(
         self.device_type)[0].get('deviceName')
     #用于校验服务是否成功,存放端口号
     self.ports = []
示例#11
0
    def run(self):
        Tool().clear_picture()
        suit = unittest.TestSuite()
        cases = unittest.defaultTestLoader.discover(WEBCASEPATH)

        for case in cases:
            suit.addTest(case)

        f = open(REPORTPATH, 'wb')

        runner = HTMLTestRunner(f,
                                verbosity=1,
                                title='UI测试报告',
                                description='用例执行情况:')
        res = runner.run(suit)

        logger.info('共运行%s条,成功%s条,失败%s条' %
                    (res.all_count, res.success_count, res.failure_count))

        f.flush()
        f.close()
示例#12
0
def opt(gfile, offset=(0.0,0.0,0.0), rotate=False):
  '''Optimization core function:
  Reads in gCode ascii file.
  Processes gcode into toolpath list
  figures out milling.
  Reorders milling to get optimal
  Writes out to new file.'''
  
  start = datetime.now()
  puts(colored.blue('Optimizing file: %s\n Started: %s'%(gfile.name,datetime.now())))
  
  # Parse the gcode from the ascii to a list of command numbers and location
  gcode = GCode(gfile)
  gcode.parse()
  
  # Take the list and make a toolpath out of it. A toolpath is a list of locations
  # where the bit needs to be moved / milled : [ [x,y,z,t], ...]
  tool = Tool(gcode)
  tool.offset(offset)
  tool.rotate(rotate)
  
  tool.groupMills()
  puts(colored.blue('Toolpath length: %.2f inches, (mill only: %.2f)'%(tool.length(),tool.millLength())))
  if args.setMillHeight:
    tool.setMillHeight(Z_MILL,Z_SPOT)
  tool.uniqMills()
  
  # This starts the optimization process:
  # start at here, and go to the next path which is closest is the overall plan
  puts(colored.blue('Starting Optimization:'))
  here = [0.0]*3 # start at the origin
  newMills = []  # accumulate mills here
  k = 0
  while len(tool.mills) > 0:
    # No Optimization
    # mill = tool.mills.pop(0)

    # Basic optimization, find the next closest one and use it.
    # mill = tool.getNextMill(here)

    # Advanced Optimization:  Assumes that each mill path closed, so finds 
    #  the mill path which is close to the point and reorders it to be so
    mill = tool.getClosestMill(here)
    
    # you were here, now you are there
    # move mills and update location
    newMills.append(mill) 
    here = newMills[-1][-1]
    
    k += 1
    if (k%10) == 0:
      sys.stdout.write('.')
      sys.stdout.flush()
    
  tool.mills.extend(newMills)
  tool.reTool(Z_MOVE)
  tool.uniq()
  puts(colored.blue('Toolpath length: %.2f inches, (mill only: %.2f)'%(tool.length(),tool.millLength())))

  # Save this with the _opt file ending.
  output = tool.buildGcode()
  outfile = FILEENDING.join(os.path.splitext(gfile.name))
  puts(colored.green('Writing: %s'%outfile))
  with open(outfile,'w') as f:
    f.write(output)
  
  # how long did this take?
  puts(colored.green('Time to completion: %s'%(deltaTime(start))))
  print
示例#13
0
class Controller(object):
    def __init__(self):
        self.tool = Tool()
        # 配置信息
        self.yml = self.tool.app_data
        # 所有手机配置信息
        self.devices = self.yml.get('devices')
        # 测试app的信息
        self.app = self.yml.get('tester')
        # Android OR iOS
        self.device_type = self.yml.get('device_type')
        # 用于校验服务是否成功,存储端口号
        self.ports = []

    def kill_server(self):
        """
        adb如果重启  夜游神将不会被查到
        :return:
        """
        logger.debug('执行[KILL SERVER]操作:%s' % subprocess.getoutput("taskkill /F /IM node.exe /t"))
        logger.debug('重启ADB服务!%s' % subprocess.getoutput("adb kill-server"))

    def server_command(self, **kwargs):
        commond = 'appium -a {ip} -p {port} -U {deviceName} -g {log}'.format(ip=kwargs.get('ip'),
                                                                             port=kwargs.get('port'),
                                                                             deviceName=kwargs.get(
                                                                                 'deviceName'),
                                                                             log=kwargs.get('log_path'))
        logger.debug('启动服务执行的命令:%s' % commond)
        subprocess.Popen(commond, stdout=open(kwargs.get('log_path'), 'a+'), stderr=subprocess.PIPE, shell=True)

    def server(self):
        # 每次启动前,先清掉上一次还存活的端口
        self.kill_server()
        threads_server = []
        for device in self.devices.get(self.device_type):
            # 将手机操作log加到配置中
            device.update({'log_path': os.path.join(LOGPATH, '%s.log' % device.get('name'))})
            logger.debug("每个手机的信息:%s" % device)
            # 提取校验服务启动成功的端口
            self.ports.append(device.get('port'))
            # 启动多线程开启服务
            t = threading.Thread(target=self.server_command, kwargs=device)
            threads_server.append(t)
            t.start()
        for i in threads_server:
            i.join()

    def test_server(self):
        while True:
            for port in self.ports:
                # 通过查看是否有返回值来确定是否启动
                test_out_put = subprocess.getoutput("netstat -ano | findstr %s" % port)
                # 如果有 则从list中删除这个端口 直到这个list为空时 代表启动成功 跳出循环
                if test_out_put:
                    logger.debug('检验服务启动:%s' % test_out_put)
                    self.ports.remove(port)
                else:
                    logger.debug('端口 [%s] 服务启动失败5秒钟后尝试' % port)
            if not self.ports:
                break
            time.sleep(5)
        logger.debug('全部服务启动成功!')
        return True

    def driver_commend(self, **kwargs):
        local.desired_caps = {'platformName': '', 'platformVersion': '', 'deviceName': '',
                              "unicodeKeyboard": "True",
                              "resetKeyboard": "True", 'udid': '', 'noReset': 'True'}
        local.desired_caps.update(kwargs)
        url = 'http://{ip}:{port}/wd/hub'.format(port=local.desired_caps.get('port'),
                                                 ip=local.desired_caps.get('ip'))
        logger.debug('启动的Url:%s' % url)
        driver = webdriver.Remote(url, local.desired_caps)
        # 通过消息对列传递driver驱动
        driver_queue.put(driver)
        # 存放手机名称的对列(用于后续对线程名进行区分)
        device_name_queue.put(local.desired_caps.get('name'))
        # 创建错误图片存放的路径
        app = APPPICTUREPATH.format(local.desired_caps.get('name'))
        # 如果存在则清除目录下的所有内容
        if os.path.exists(app):
            # 调用写好的clear方法
            self.tool.app_clear(app)
        else:
            # 如果不存在path 则递归创建目录
            os.makedirs(app)

    def driver(self):
        thread_driver = []
        for device_app in self.devices.get(self.device_type):
            # 将测试的app信息增加到 手机的配置文件中
            device_app.update(self.app)
            # 多线程启动
            d = threading.Thread(target=self.driver_commend, kwargs=device_app)
            thread_driver.append(d)
            d.start()
        for i in thread_driver:
            i.join()
        # 所有driver启动成功后 返回driver的mq
        return driver_queue
示例#14
0
from conf.settings import logger
from lib.tool import Tool

logger.debug(Tool().app_data)
示例#15
0
class Controller(object):
    def __init__(self):
        self.tool = Tool()
        self.yml = self.tool.app_data
        self.devices = self.yml.get('devices')
        self.app = self.yml.get('tester')
        self.device_type = self.yml.get('device_type')
        self.ports = []

    def kill_server(self):

        logger.debug('执行[KILL SERVER]操作:%s' %
                     subprocess.getoutput("taskkill /F /IM node.exe /t"))
        logger.debug('重启ADB服务!%s' % subprocess.getoutput("adb kill-server"))

    def server_command(self, **kwargs):
        commond = 'appium -a {ip} -p {port} -U {deviceName} -g {log}'.format(
            ip=kwargs.get('ip'),
            port=kwargs.get('port'),
            deviceName=kwargs.get('deviceName'),
            log=kwargs.get('log_path'))
        logger.debug('启动服务执行的命令:%s' % commond)
        subprocess.Popen(commond,
                         stdout=open(kwargs.get('log_path'), 'a+'),
                         stderr=subprocess.PIPE,
                         shell=True)

    def server(self):
        self.kill_server()
        threads_server = []
        for device in self.devices.get(self.device_type):
            device.update({
                'log_path':
                os.path.join(LOGPATH, '%s.log' % device.get('name'))
            })
            logger.debug("每个手机的信息:%s" % device)
            self.ports.append(device.get('port'))
            t = threading.Thread(target=self.server_command, kwargs=device)
            threads_server.append(t)
            t.start()
        for i in threads_server:
            i.join()

    def test_server(self):
        while True:
            for port in self.ports:
                test_out_put = subprocess.getoutput("netstat -ano | grep %s" %
                                                    port)

                if test_out_put:
                    logger.debug('检验服务启动:%s' % test_out_put)
                    self.ports.remove(port)
                else:
                    logger.debug('端口 [%s] 服务启动失败5秒钟后尝试' % port)
            if not self.ports:
                break
            time.sleep(5)
        logger.debug('全部服务启动成功!')
        return True

    def driver_commend(self, **kwargs):
        local.desired_caps = {
            'platformName': '',
            'platformVersion': '',
            'deviceName': '',
            "unicodeKeyboard": "True",
            "resetKeyboard": "True",
            'udid': '',
            'noReset': 'True'
        }
        local.desired_caps.update(kwargs)
        url = 'http://{ip}:{port}/wd/hub'.format(
            port=local.desired_caps.get('port'),
            ip=local.desired_caps.get('ip'))
        logger.debug('启动的Url:%s' % url)
        driver = webdriver.Remote(url, local.desired_caps)

        driver_queue.put(driver)
        device_name_queue.put(local.desired_caps.get('name'))
        app = APPPICTUREPATH.format(local.desired_caps.get('name'))
        if os.path.exists(app):
            self.tool.app_clear(app)
        else:
            os.makedirs(app)

    def driver(self):
        thread_driver = []
        for device_app in self.devices.get(self.device_type):
            device_app.update(self.app)
            d = threading.Thread(target=self.driver_commend, kwargs=device_app)
            thread_driver.append(d)
            d.start()
        for i in thread_driver:
            i.join()
        return driver_queue
示例#16
0
def mod(gfile):
    '''For each of the files to process either rotate, move, copy, or
  replicate the code.  General idea:
    read in ascii
    Process into a toolpath list.
    modify.
    Write out toolpath.'''

    start = datetime.now()
    puts(
        colored.blue('Modifying file: %s\n Started: %s' %
                     (gfile.name, datetime.now())))

    # Parse the gcode.
    gcode = GCode(gfile)
    gcode.parseAll()

    # Create a toolpath from the gcode
    # add in the index so that we can match it to the gcode

    out = []
    if args.move:
        loc = parse(args.move, getUnits=True)  # only one move at a time.
        puts(
            colored.blue('Moving!\n    (0,0) -> (%.3f,%.3f)' %
                         (loc[0], loc[1])))
        tool = Tool()
        # is the addIndex atribut even used any longer?
        tool.build(gcode, addIndex=True)
        tool.move(loc)  # ok well this should work
        gcode.update(tool)
        out.append([loc, gcode])

    if args.copy:
        locs = parse(args.copy, getUnits=True)
        puts(colored.blue('Copying!'))
        for loc in locs:
            puts(colored.blue('    (0,0) -> (%.3f,%.3f)' % (loc[0], loc[1])))
            gc = gcode.copy()
            tool = Tool()
            # is the addIndex atribut even used any longer?
            tool.build(gc, addIndex=True)
            tool.move(loc)
            gc.update(tool)
            out.append([loc, gc])

    # if args.replicate:
    #   nxy = map(int,parse(args.replicate)[0]) # ensure int, and only one
    #   puts(colored.blue('Replicating!\n     nx=%i, ny=%i)'%(nxy[0],nxy[1])))

    output = ''.join([o.getGcode(tag=args.name, start=l) for l, o in out])

    outfile = FILEENDING.join(os.path.splitext(gfile.name))
    puts(colored.green('Writing: %s' % outfile))
    with open(outfile, 'w') as f:
        f.write(output)

    # how long did this take?
    puts(colored.green('Time to completion: %s' % (deltaTime(start))))
    print
示例#17
0
    def _generate_report(self, result):
        rows = []
        sortedResult = self.sortResult(result.result)
        for cid, (cls, cls_results) in enumerate(sortedResult):
            # subtotal for a class
            np = nf = ne = 0
            for n, t, o, e in cls_results:
                if n == 0:
                    np += 1
                elif n == 1:
                    nf += 1
                else:
                    ne += 1

            # format class description
            if cls.__module__ == "__main__":
                name = cls.__name__
            else:
                name = "%s.%s" % (cls.__module__, cls.__name__)
            doc = cls.__doc__ and cls.__doc__.split("\n")[0] or ""
            desc = doc and '%s: %s' % (name, doc) or name

            row = self.REPORT_CLASS_TMPL % dict(
                style=ne > 0 and 'errorClass' or nf > 0 and 'failClass' or 'passClass',
                desc=desc,
                count=np + nf + ne,
                Pass=np,
                fail=nf,
                error=ne,
                cid='c%s' % (cid + 1),
            )
            rows.append(row)
            from lib.tool import Tool
            import os
            pnglist = Tool().app_error_picture()
            logger.debug(pnglist)
            if len(pnglist) > 0:
                Rewrite_results = []
                for cls_p in cls_results:
                    name = cls_p[1].id().split('.')[-1]
                    for png in pnglist:
                        png_name = png[0].split('.')[2]
                        png_name = png_name.split('/')[-1]
                        if png_name == name:
                            tmp = cls_p + png
                            Rewrite_results.append(tmp)
                            break
                    else:
                        tmp = cls_p + ('',)
                        Rewrite_results.append(tmp)
                for tid, (n, t, o, e, png) in enumerate(Rewrite_results):
                    self._generate_report_test(rows, cid, tid, n, t, o, e, png)
            else:
                for tid, (n, t, o, e) in enumerate(cls_results):
                    self._generate_report_test(rows, cid, tid, n, t, o, e)

        report = self.REPORT_TMPL % dict(
            test_list=''.join(rows),
            count=str(result.success_count + result.failure_count + result.error_count),
            Pass=str(result.success_count),
            fail=str(result.failure_count),
            error=str(result.error_count),
        )
        return report
示例#18
0
def zcorrect_file(gfile,surface_file_name = 'probe_test.out'):

    # Load the correction surface
    correction_surface = CorrectionSurface(surface_file_name)

    # keep track of time
    start = datetime.now()

    name = gfile if isinstance(gfile,str) else gfile.name
    puts(colored.blue('Z correcting the file: %s\n Started: %s'%(name,datetime.now())))

    # Load the gcode.
    gcode = GCode(gfile)
    #parse the Gcode
    gcode.parseAll()

    # start an empty list
    #out = []

    # need to get rid of use of 'loc'
    # loc = parse(args.move, getUnits=True) # only one move at a time.
    # puts(colored.blue('Moving!\n    (0,0) -> (%.3f,%.3f)'%(loc[0],loc[1])))

    # create a tool object (toolpath object)
    tool = Tool()
    # load the gcode into the tool object
    tool.build(gcode)
    # adjust the z position at each point by the given amount
    tool.zcorrect(correction_surface)

    ''' the follwing doe not work. is gcode.update(tool) broken?'''
    # load the changes back into the gcode object
    # append the modified g code to the empty list called out
    # out.append([gcode])
    # gcode.update(tool)
    # out = gcode
    # convert gcode to text format
    # output = ''.join([o.getGcode(tag=args.name) for o in out])
    # output = ''.join([out.getGcode()])

    '''instead the following simgle lin suffices'''
    '''is any info lost by doing it this way? E F M'''
    # generate a gcode file from the tool object
    output = tool.buildGcode()

    # get an output file name
    outfile = FILEENDING.join(os.path.splitext(gfile))
    print "outfile is:"
    print outfile
    # tell the user
    puts(colored.green('Writing: %s'%outfile))
    # write to file
    f = open(outfile,'w')
    f.write(output)
    '''
    with open(outfile,'w') as f:
        f.write(output)
    '''
    # how long did this take?
    puts(colored.green('Time to completion: %s'%(deltaTime(start))))
    print