Example #1
0
def activate_plugin(plugin, config=None, db=None):
	if not config:
		config = ConfigService()
	if not db:
		db = Database(config)
		
	plugins_path = config.get('general', 'plugins_path')
	fabui_path = config.get('general', 'fabui_path')

	plugin_dir = os.path.join(plugins_path, plugin)
	
	if not os.path.exists(plugin_dir):
		return False

	# Link controller
	create_link( os.path.join(plugin_dir, 'controller.php'), os.path.join(fabui_path, 'application/controllers/Plugin_{0}.php'.format(plugin) ) ) 
	# Link views
	create_dir(os.path.join( fabui_path, 'application/views/plugin' ) )
	create_link( os.path.join(plugin_dir, 'views'), os.path.join(fabui_path, 'application/views/plugin/{0}'.format(plugin)) ) 
	# Link assets
	create_dir( os.path.join( fabui_path, 'assets/plugin' ) )
	create_link( os.path.join(plugin_dir, 'assets'), os.path.join(fabui_path, 'assets/plugin/{0}'.format(plugin)) ) 

	meta_file = os.path.join( plugin_dir, "meta.json" )

	with open(meta_file) as f:
		meta_content = f.read()

	p = Plugin(db)
	p['name'] = plugin
	p['attributes'] = meta_content
	p.write()

	return True
Example #2
0
def extract_plugin(plugin_filename, config=None):
	"""
	Extract plugin file and verify that it IS a plugin archive
	"""
	if not config:
		config = ConfigService()
		
	top = ""
	meta = {}
	
	temp_dir = build_path( config.get('general', 'temp_path'), 'new_plugin' )
	create_dir(temp_dir)
	
	cmd = 'unzip "{0}" -d "{1}" -o'.format(plugin_filename, temp_dir)
	try:
		subprocess.check_output( shlex.split(cmd) )
	except subprocess.CalledProcessError as e:
		pass
	
	fn = find_file("meta.json", temp_dir)

	try:
		fn = fn[0]
		f = open(fn)
		meta =  json.loads( f.read() )
		top = os.path.dirname(fn)
	except Exception as e:
		remove_dir(temp_dir)
	
	return top, meta
Example #3
0
 def __init__(self, jog_response_file, gcs = None, config = None, logger = None):
     if not config:
         self.config = ConfigService()
     else:
         self.config = config
     
     if not gcs:
         self.gcs = GCodeServiceClient()
     else:
         self.gcs = gcs
     
     if logger:
         self.log = logger
     else:
         self.log = logging.getLogger('Jog')
         ch = logging.StreamHandler()
         ch.setLevel(logging.DEBUG)
         formatter = logging.Formatter("%(levelname)s : %(message)s")
         ch.setFormatter(formatter)
         self.log.addHandler(ch)
     
     self.jog_response_file = jog_response_file
     # Erase content of jog_response_file
     open(jog_response_file, 'w').close()
     
     self.backtrack = int(self.config.get('jog', 'backtrack', 20))
     self.response = {}
     self.tokens = []
     self.cq = queue.Queue()
     self.running = False
     
     self.send_thread = None
Example #4
0
    def __init__(self,
                 arch='armhf',
                 mcu='atmega1280',
                 notify_update=None,
                 config=None,
                 gcs=None):
        self.config = config
        if not config:
            self.config = ConfigService()

        if not gcs:
            self.gcs = GCodeServiceClient()
        else:
            self.gcs = gcs

        self.arch = arch
        self.mcu = mcu
        self.remote = RemoteVersion(arch, mcu, config=config)

        self.tasks = []
        self.notify_update = notify_update

        self.reboot_required = False
        self.status = ''
        self.task = ''
class Translation():
    def __init__(self, config=None):
        if not config:
            self.config = ConfigService()

        self.tr = gettext.translation('fabui',
                                      '/usr/share/fabui/locale',
                                      fallback=True)
        self.tp = gettext.translation('fabui',
                                      '/usr/share/fabui/locale',
                                      fallback=True)

    def setLanguage(self, lang, domain='fabui'):

        locale_path = self.config.get('general', 'locale_path')
        self.tr = gettext.translation('fabui',
                                      locale_path,
                                      fallback=True,
                                      languages=[lang])

    def setPluginLanguage(self, plugin_name, lang):
        plugins_path = self.config.get('general', 'plugins_path')
        locale_path = '{0}{1}/locale'.format(plugins_path, plugin_name)
        self.tp = gettext.translation(plugin_name,
                                      locale_path,
                                      fallback=True,
                                      languages=[lang])

    def get(self, text):

        t = self.tp.gettext(text)
        if t == text:
            t = self.tr.gettext(text)
        return t
Example #6
0
    def __init__(self, gcs, logger, config=None):

        if config:
            self.config = config
        else:
            self.config = ConfigService()

        self.gcs = gcs
        self.db = Database(self.config)
        self.log = logger

        self.url = self.config.get('my.fabtotum.com', 'myfabtotum_url')
        self.api_version = self.config.get('my.fabtotum.com',
                                           'myfabtotum_api_version')
        self.thread_polling = None
        self.thread_update = None
        self.thread_reload = None
        self.running = False
        self.jsonrpc_version = "2.0"
        self.request_timeout = 5
        self.polling_interval = 5
        self.info_interval = (60 * 30)  # 30 minutes
        self.internal_update_interval = (60 * 5)  #  5 minutes
        self.id_counter = 0
        self.leds_colors = {}
        #self.mac_address      = None
        #self.serial_number    = None
        #self.fab_id           = None
        #self.unit_name        = None
        #self.batch_number     = None
        #self.fw_version       = None

        self.__init_vars()
Example #7
0
def install_plugin(plugin_filename, config=None, db=None):
	if not config:
		config = ConfigService()
		
	plugins_path = config.get('general', 'plugins_path')
	top, meta = extract_plugin(plugin_filename, config)

	if meta:
		slug = meta['plugin_slug']
		plugin_dir  = os.path.join(plugins_path, slug)
		
		installed_plugins = get_installed_plugins(config)
		active_plugins = get_active_plugins(config, db)
		
		was_active = False
		if slug in active_plugins:
			deactivate_plugin(slug, config, db)
			was_active = True
		
		if slug in installed_plugins:
			remove_plugin(slug, config)

		create_dir(plugin_dir)
		copy_files( os.path.join(top, '*'), plugin_dir)
		
		remove_dir(top)
		
		if was_active:
			activate_plugin(slug, config, db)
		
		return True
		
	return False
Example #8
0
    def __init__(self, WebSocket=None, notify_file=None, config=None):

        self.notify_lock = RLock()

        if not config:
            self.config = ConfigService()
        else:
            self.config = config

        if not notify_file:
            notify_file = self.config.get('general', 'notify_file')

        if not WebSocket:
            SOCKET_HOST = self.config.get('socket', 'host')
            SOCKET_PORT = self.config.get('socket', 'port')
            self.ws = WebSocketClient('ws://' + SOCKET_HOST + ':' +
                                      SOCKET_PORT + '/')
            self.ws.connect()
        else:
            self.ws = WebSocket

        self.notify_file = notify_file

        self.backtrack = int(self.config.get('notify', 'backtrack', 30))
        self.event_id = 0
        self.events = []
Example #9
0
 def __init__(self, config = None):
     if not config:
         self.config = ConfigService()
     else:
         self.config = config
     
     self.lock = RLock()
     self.database_file = self.config.get('general', 'database')
Example #10
0
def main():
    from ws4py.client.threadedclient import WebSocketClient
    from fabtotum.fabui.notify       import NotifyService
    from fabtotum.utils.pyro.gcodeclient import GCodeServiceClient
    from fabtotum.fabui.config import ConfigService
    from fabtotum.os.paths     import RUN_PATH
    import logging
    import argparse
    import os
    
    
    # Setup arguments
    parser = argparse.ArgumentParser()
    parser.add_argument("-L", "--log", help="Use logfile to store log messages.",   default='/var/log/fabui/gpiomonitor.log')
    parser.add_argument("-p", "--pidfile", help="File to store process pid.",       default=os.path.join(RUN_PATH, 'gpiomonitor.pid') )

    # Get arguments
    args = parser.parse_args()
    pidfile = args.pidfile
    
    with open(pidfile, 'w') as f:
        f.write( str(os.getpid()) )
    
    config = ConfigService()

    # Load configuration
    NOTIFY_FILE         = config.get('general', 'notify_file')
    ##################################################################
    SOCKET_HOST         = config.get('socket', 'host')
    SOCKET_PORT         = config.get('socket', 'port')
    ##################################################################
    EVENT_PIN           = config.get('totumduino', 'event_pin')
    
    # Pyro GCodeService wrapper
    gcs = GCodeServiceClient()
    
    ws = WebSocketClient('ws://'+SOCKET_HOST +':'+SOCKET_PORT+'/')
    ws.connect();

    # Notification service
    ns = NotifyService(ws, NOTIFY_FILE, config)
    
    # Setup logger
    logger2 = logging.getLogger('GPIOMonitor')
    logger2.setLevel(logging.DEBUG)
    fh = logging.FileHandler(args.log, mode='w')

    #~ formatter = logging.Formatter("%(name)s - %(levelname)s : %(message)s")
    formatter = logging.Formatter("[%(asctime)s] %(levelname)s : %(message)s")
    fh.setFormatter(formatter)
    fh.setLevel(logging.DEBUG)
    logger2.addHandler(fh)
    
    gpioMonitor = GPIOMonitor(ns, gcs, logger2, EVENT_PIN)
    gpioMonitor.start()
    gpioMonitor.loop()
Example #11
0
    def __init__(self, config=None):
        if not config:
            self.config = ConfigService()

        self.tr = gettext.translation('fabui',
                                      '/usr/share/fabui/locale',
                                      fallback=True)
        self.tp = gettext.translation('fabui',
                                      '/usr/share/fabui/locale',
                                      fallback=True)
Example #12
0
def setLanguage(lang, domain='fab_diagnostic', config=None):
    if not config:
        config = ConfigService()

    locale_path = config.get('general', 'locale_path')
    
    tr = gettext.translation('fab_diagnostic', locale_path, fallback=True, languages=[lang])
    _ = tr.ugettext
    
    return _
Example #13
0
def main():
    config = ConfigService()

    # SETTING EXPECTED ARGUMENTS
    parser = argparse.ArgumentParser(
        formatter_class=argparse.ArgumentDefaultsHelpFormatter)
    parser.add_argument("-T", "--task-id", help="Task ID.", default=0)
    parser.add_argument("-F", "--file-name", help="File name.", required=True)
    parser.add_argument(
        "--autolevel",
        action='store_true',
        help="Auto bed leveling. Valid only when --standalone is used.",
        default=False)
    parser.add_argument("--lang",
                        help="Output language",
                        default='en_US.UTF-8')
    parser.add_argument("--email",
                        help="Send an email on task finish",
                        action='store_true',
                        default=False)
    parser.add_argument("--shutdown",
                        help="Shutdown on task finish",
                        action='store_true',
                        default=False)

    # GET ARGUMENTS
    args = parser.parse_args()

    # INIT VARs
    gcode_file = args.file_name  # GCODE FILE
    task_id = args.task_id
    autolevel = args.autolevel
    lang = args.lang
    send_email = bool(args.email)

    if task_id == 0:
        standalone = True
    else:
        standalone = False

    monitor_file = config.get(
        'general', 'task_monitor'
    )  # TASK MONITOR FILE (write stats & task info, es: temperatures, speed, etc
    log_trace = config.get('general', 'trace')  # TASK TRACE FILE

    app = PrintApplication(log_trace,
                           monitor_file,
                           standalone,
                           autolevel,
                           lang=lang,
                           send_email=send_email)

    app.run(task_id, gcode_file)
    app.loop()
    def __init__(self, verbose=False):

        ## init attr
        self.verbose = verbose
        self._adapter = None
        self.controller_address = None
        self.config = ConfigService()
        self.status = None

        ## init adapater
        self._init_adapter()
Example #15
0
def remove_plugin(plugin, config=None):
	if not config:
		config = ConfigService()
	
	plugins_path = config.get('general', 'plugins_path')
	plugin_dir = os.path.join( plugins_path, plugin )
	
	if os.path.exists(plugin_dir):
		remove_dir(plugin_dir)
		return True
		
	return False
Example #16
0
def main():
    config = ConfigService()

    # SETTING EXPECTED ARGUMENTS
    destination = config.get('general', 'bigtemp_path')
    
    # SETTING EXPECTED ARGUMENTS
    parser = argparse.ArgumentParser(formatter_class=argparse.ArgumentDefaultsHelpFormatter)
    parser.add_argument("task_id",          help="Task ID." )
    parser.add_argument("-d", "--dest",     help="Destination folder."),      default=destination )
    parser.add_argument("-i", "--intrinsic",help="Intrinsic camera parameters.", default='intrinsic.json' )
    parser.add_argument("-o", "--output",   help="Extrinsic camera parameters.", default='extrinsic.json' )
    parser.add_argument("-W", "--width",    help="Image width in pixels.",   default=1296)
    parser.add_argument("-H", "--height",   help="Image height in pixels.",  default=972)
    parser.add_argument("-r", "--rotation", help="Image rotation.",          default=0)
    parser.add_argument("-x", "--x-offset", help="X offset.",                default=104)
    parser.add_argument("-y", "--y-offset", help="Y offset.",                default=117)
    parser.add_argument("-z", "--z-offset", help="Z offset.",                default=220)
    parser.add_argument("-b", "--base-height", help="Chessboard height of it's base.", default=0)
    parser.add_argument("--lang",           help="Output language", 		 default='en_US.UTF-8' )
    
    # GET ARGUMENTS    
    args = parser.parse_args()
    
    # INIT VARs
    task_id         = int(args.task_id)
    destination     = args.dest
    intrinsic_file  = args.intrinsic
    monitor_file    = config.get('general', 'task_monitor') # TASK MONITOR FILE (write stats & task info, ex: temperatures, speed, etc
    log_trace       = config.get('general', 'trace')        # TASK TRACE FILE 
    width           = int(args.width)
    height          = int(args.height)
    rotation        = int(args.rotation)
    x_offset        = float(args.x_offset)
    y_offset        = float(args.y_offset)
    z_offset        = float(args.z_offset)
    base_height     = float(args.base_height)
    output_file     = args.output
    lang			= args.lang
    output_dir      = destination

    if not os.path.exists(output_dir):
        makedirs(output_dir)
    
    app = Extrinsic(log_trace,
                  monitor_file, 
                  output_dir,
                  output_file,
                  width=width,
                  height=height,
                  rotation=rotation,
                  lang=lang)
Example #17
0
def get_active_plugins(config=None, db=None):
	if not config:
		config = ConfigService()
	if not db:
		db = Database(config)
		
	return Plugin(db).get_active_plugins()
Example #18
0
def main():
    config = ConfigService()

    # SETTING EXPECTED ARGUMENTS
    parser = argparse.ArgumentParser(formatter_class=argparse.ArgumentDefaultsHelpFormatter)
    parser.add_argument("-T", "--task-id",     help=_("Task ID."),      default=0)
    parser.add_argument("-F", "--file-name",   help=_("File name."),    required=True)
    parser.add_argument("--lang",              help="Output language", default='en_US.UTF-8' )
    parser.add_argument("--email",             help="Send an email on task finish", action='store_true', default=False)
    parser.add_argument("--shutdown",          help="Shutdown on task finish", action='store_true', default=False )
    
    # GET ARGUMENTS
    args = parser.parse_args()

    # INIT VARs
    gcode_file      = args.file_name     # GCODE FILE
    task_id         = args.task_id
    lang            = args.lang
    send_email      = bool(args.email)
    auto_shutdown   = bool(args.shutdown)
    
    if task_id == 0:
        standalone  = True
    else:
        standalone  = False

    app = Application(standalone)

    app.run(task_id, gcode_file)
    app.loop()
Example #19
0
def main():
    # Setup arguments
    parser = argparse.ArgumentParser()
    parser.add_argument("-L",
                        "--log",
                        help="Use logfile to store log messages.",
                        default='<stdout>')
    parser.add_argument("-p",
                        "--pidfile",
                        help="File to store process pid.",
                        default=os.path.join(RUN_PATH, 'xmlrpcserver.pid'))

    # Get arguments
    args = parser.parse_args()
    pidfile = args.pidfile

    with open(pidfile, 'w') as f:
        f.write(str(os.getpid()))

    time.sleep(2)

    gcs = GCodeServiceClient()
    config = ConfigService()

    rpc = create(gcs, config, args.log)
    rpc.start()
    rpc.loop()
Example #20
0
def get_installed_plugins(config=None):
	if not config:
		config = ConfigService()
		
	plugins_path = config.get('general', 'plugins_path')
	
	result = {}
	
	for dirname in os.listdir(plugins_path):
		plugin_dir = os.path.join( plugins_path, dirname)
		plugin_meta = os.path.join(plugin_dir, "meta.json")
		if os.path.exists(plugin_meta):
			with open(plugin_meta) as f:
				meta = json.loads( f.read() )
				result[dirname] = meta
				
	return result
Example #21
0
def main():
    config = ConfigService()

    # SETTING EXPECTED ARGUMENTS
    parser = argparse.ArgumentParser(
        formatter_class=argparse.ArgumentDefaultsHelpFormatter)
    parser.add_argument("-T", "--task-id", help="Task ID.", default=0)
    parser.add_argument("-e",
                        "--extruder",
                        help="Extruder to select.",
                        default=0)
    parser.add_argument("-t",
                        "--temp",
                        help="Temperature used for PID tunind.",
                        default=200)
    parser.add_argument("-c",
                        "--cycles",
                        help="Number of tuning cycles",
                        default=8)
    parser.add_argument("--lang",
                        help="Output language",
                        default='en_US.UTF-8')

    # GET ARGUMENTS
    args = parser.parse_args()

    # INIT VARs
    task_id = int(args.task_id)  # TASK ID
    monitor_file = config.get(
        'general', 'task_monitor'
    )  # TASK MONITOR FILE (write stats & task info, ex: temperatures, speed, etc
    log_trace = config.get('general', 'trace')  # TASK TRACE FILE
    temperature = int(args.temp)
    extruder = int(args.extruder)
    cycles = int(args.cycles)
    lang = args.lang

    app = PIDAutotune(log_trace, monitor_file, lang=lang)

    app_thread = Thread(target=app.run,
                        args=([task_id, extruder, temperature, cycles]))
    app_thread.start()

    # app.loop() must be started to allow callbacks
    app.loop()
    app_thread.join()
Example #22
0
    def __init__(self, arch='armhf', mcu='atmega1280', config=None):
        self.config = config
        if not config:
            self.config = ConfigService()

        self.colibri_endpoint = self.config.get('updates', 'colibri_endpoint')
        self.firmware_endpoint = self.config.get('updates',
                                                 'firmware_endpoint')
        self.plugin_endpoint = self.config.get('updates', 'plugins_endpoint')
        self.arch = arch
        self.mcu = mcu
        self.colibri = None
        self.firmware = None
        self.plugins = None
        self.setColibri()
        self.setFirmware()
        self.setPlugins()
    def __init__(self, x1, x2, y1, y2, skip_homing=False, lang='en_US.UTF-8'):
        config = ConfigService()
        monitor_file = config.get('general', 'task_monitor')
        log_trace = config.get('general', 'trace')
        super(ProbeArea, self).__init__(log_trace,
                                        monitor_file,
                                        config=config,
                                        use_stdout=False,
                                        lang=lang)

        self.probe_length = 50

        self.x1 = x1
        self.x2 = x2
        self.y1 = y1
        self.y2 = y2
        self.skip_homing = skip_homing
Example #24
0
def deactivate_plugin(plugin, config=None, db=None):
	if not config:
		config = ConfigService()
	if not db:
		db = Database(config)
		
	fabui_path = config.get('general', 'fabui_path')
	
	remove_file( os.path.join(fabui_path, 'application/controllers/Plugin_{0}.php'.format(plugin) ) )
	remove_file( os.path.join(fabui_path, 'application/views/plugin/{0}'.format(plugin)) )
	remove_file( os.path.join(fabui_path, 'assets/plugin/{0}'.format(plugin)) )
	
	p = Plugin(db)
	p.query_by('name', plugin)
	p.delete()
	
	return True
Example #25
0
    def __init__(self, stats_file, gcs=None, config=None, logger=None):

        if not gcs:
            self.gcs = GCodeServiceClient()
        else:
            self.gcs = gcs

        if not config:
            self.config = ConfigService()
        else:
            self.config = config

        if logger:
            self.log = logger
        else:
            self.log = logging.getLogger('StatsMonitor')
            ch = logging.StreamHandler()
            ch.setLevel(logging.DEBUG)
            formatter = logging.Formatter("%(levelname)s : %(message)s")
            ch.setFormatter(formatter)
            self.log.addHandler(ch)

        self.stats_file = stats_file
        self.running = False

        self.monitor_thread = None
        self.monitor_write_thread = None
        self.ev_update = Event()
        self.backtrack = int(self.config.get('monitor', 'backtrack', 20))
        self.update_period = float(self.config.get('monitor', 'period'))

        ## Monitor variables, fill arrays with zeros
        self.ext_temp = [0.0] * self.backtrack
        self.ext_temp_target = [0.0] * self.backtrack
        self.bed_temp = [0.0] * self.backtrack
        self.bed_temp_target = [0.0] * self.backtrack
        self.delta = [0] * self.backtrack
        self.last_update_time = time.time()

        # re
        #~ self.re_temp = re.compile('ok\sT:(?P<T>[0-9]+\.[0-9]+)\s\/(?P<TT>[0-9]+\.[0-9]+)\sB:(?P<B>[0-9]+\.[0-9]+)\s\/(?P<BT>[0-9]+\.[0-9]+)\s')

        self.config.register_callback(self.__reload_config)
Example #26
0
def main():
    config = ConfigService()

    # SETTING EXPECTED ARGUMENTS
    parser = argparse.ArgumentParser(
        formatter_class=argparse.ArgumentDefaultsHelpFormatter)
    parser.add_argument("-T", "--task-id", help="Task ID.", default=0)
    parser.add_argument("-n",
                        "--num_probes",
                        help="Number of probings per screw.",
                        default=1,
                        type=int)
    parser.add_argument("-s",
                        "--skip_homing",
                        action='store_true',
                        help="Skip homing.")
    parser.add_argument("--lang",
                        help="Output language",
                        default='en_US.UTF-8')

    # GET ARGUMENTS
    args = parser.parse_args()

    # INIT VARs
    task_id = int(args.task_id)
    monitor_file = config.get('general', 'task_monitor')
    log_trace = config.get('general', 'trace')
    num_probes = args.num_probes
    skip_homing = args.skip_homing
    lang = args.lang

    print "num_probes: ", num_probes

    app = ManualBedLeveling(log_trace, monitor_file, config=config, lang=lang)

    app_thread = Thread(target=app.run,
                        args=([task_id, num_probes, skip_homing]))
    app_thread.start()

    app.loop()  # app.loop() must be started to allow callbacks
    app_thread.join()
def startup(gcs):
    config = ConfigService()
    
    try:
        color = config.get('units', 'color')
    except KeyError:
        color = {
            'r' : 255,
            'g' : 255,
            'b' : 255,
        }
    
    try:
        safety_door = config.get('units', 'safety')['door']
    except KeyError:
        safety_door = 0
    
    try:
        switch = config.get('units', 'switch')
    except KeyError:
        switch = 0
    
    try:
        collision_warning = config.get('units', 'safety')['collision-warning']
    except KeyError:
        collision_warning = 0
    
    gcs.send("M728")
    gcs.send("M402")
    gcs.send("M701 S"+str(color['r']))
    gcs.send("M702 S"+str(color['g']))
    gcs.send("M703 S"+str(color['b']))
        
    gcs.send("M732 S"+str(safety_door))
    gcs.send("M714 S"+str(switch))
        
    gcs.send("M734 S"+str(collision_warning))
Example #28
0
class Database(object):
    """
    """
    
    def __init__(self, config = None):
        if not config:
            self.config = ConfigService()
        else:
            self.config = config
        
        self.lock = RLock()
        self.database_file = self.config.get('general', 'database')
        
    def get_connection(self):
        return sqlite3.connect(self.database_file)
Example #29
0
def reset():

    print "TOTUMDUINO: reset"

    config = ConfigService()

    reset_pin_s = config.get('totumduino', 'reset_pin', '17')
    reset_pins = reset_pin_s.split(',')

    try:
        #GPIO.setmode(GPIO.BOARD)
        GPIO.setmode(GPIO.BCM)
        GPIO.setwarnings(False)

        for pin in reset_pins:
            reset_pin = int(pin)

            GPIO.setup(reset_pin, GPIO.OUT)
            GPIO.output(reset_pin, GPIO.HIGH)
            time.sleep(0.5)
            GPIO.output(reset_pin, GPIO.LOW)

        time.sleep(0.5)

        for pin in reset_pins:
            reset_pin = int(pin)

            GPIO.output(reset_pin, GPIO.HIGH)

        GPIO.cleanup()

    except Exception as e:
        print e
        print "No GPIO support in QEMU simulation"

    time.sleep(1)
Example #30
0
def main():
    config = ConfigService()

    # SETTING EXPECTED ARGUMENTS
    parser = argparse.ArgumentParser(
        add_help=False, formatter_class=argparse.ArgumentDefaultsHelpFormatter)

    parser.add_argument("-T", "--task-id", help="Task ID.", default=0)
    parser.add_argument("-U",
                        "--user-id",
                        help="User ID. (future use)",
                        default=0)

    parser.add_argument("--address", help="Remove server address.")
    parser.add_argument("--port", help="Remove server port.", default=9898)
    parser.add_argument("-d",
                        "--dest",
                        help="Destination folder.",
                        default=config.get('general', 'bigtemp_path'))
    parser.add_argument("-s",
                        "--slices",
                        help="Number of slices.",
                        default=100)
    parser.add_argument("-i", "--iso", help="ISO.", default=400)
    parser.add_argument("-W",
                        "--width",
                        help="Image width in pixels.",
                        default=1920)
    parser.add_argument("-H",
                        "--height",
                        help="Image height in pixels",
                        default=1080)
    parser.add_argument("-b",
                        "--begin",
                        help="Begin scanning from X.",
                        default=0)
    parser.add_argument("-e", "--end", help="End scanning at X.", default=360)
    parser.add_argument("-z", "--z-offset", help="Z offset.", default=0)
    parser.add_argument("-y", "--y-offset", help="Y offset.", default=0)
    parser.add_argument("-a",
                        "--a-offset",
                        help="A offset/rotation.",
                        default=0)
    parser.add_argument("--lang",
                        help="Output language",
                        default='en_US.UTF-8')
    parser.add_argument(
        "--standalone",
        action='store_true',
        help="Standalone operation. Does all preparations and cleanup.")
    parser.add_argument('--help',
                        action='help',
                        help="Show this help message and exit")
    parser.add_argument("--email",
                        help="Send an email on task finish",
                        action='store_true',
                        default=False)
    parser.add_argument("--shutdown",
                        help="Shutdown on task finish",
                        action='store_true',
                        default=False)

    # GET ARGUMENTS
    args = parser.parse_args()

    slices = int(args.slices)
    destination = args.dest
    host_address = args.address
    host_port = int(args.port)
    iso = int(args.iso)
    start_a = float(args.begin)
    end_a = float(args.end)
    width = int(args.width)
    height = int(args.height)
    z_offset = float(args.z_offset)
    y_offset = float(args.y_offset)
    a_offset = float(args.a_offset)
    standalone = args.standalone
    task_id = int(args.task_id)
    lang = args.lang
    send_email = bool(args.email)

    monitor_file = config.get(
        'general', 'task_monitor'
    )  # TASK MONITOR FILE (write stats & task info, es: temperatures, speed, etc
    log_trace = config.get('general', 'trace')  # TASK TRACE FILE

    scan_dir = os.path.join(destination, "images")

    if not os.path.exists(scan_dir):
        makedirs('scan_dir')

    ##### delete files
    cleandirs(scan_dir)

    ################################################################################

    app = PhotogrammetryScan(log_trace,
                             monitor_file,
                             scan_dir,
                             standalone=standalone,
                             width=width,
                             height=height,
                             iso=iso,
                             host_address=host_address,
                             host_port=host_port,
                             lang=lang,
                             send_email=send_email)

    app_thread = Thread(target=app.run,
                        args=([task_id, start_a, end_a, y_offset, slices]))
    app_thread.start()

    app.loop()  # app.loop() must be started to allow callbacks
    app_thread.join()
Example #31
0
# Import standard python module
import argparse
import time
import gettext

# Import external modules
from watchdog.observers import Observer
from watchdog.events import PatternMatchingEventHandler

# Import internal modules
from fabtotum.fabui.config  import ConfigService
from fabtotum.fabui.gpusher import GCodePusher
import fabtotum.fabui.macros.general as general_macros
import fabtotum.fabui.macros.printing as print_macros

config = ConfigService()

# SETTING EXPECTED ARGUMENTS
parser = argparse.ArgumentParser()
parser.add_argument("file",         help="gcode file to execute")
parser.add_argument("command_file", help="command file")
parser.add_argument("task_id",      help="id_task")
parser.add_argument("monitor",      help="monitor file",  default=config.get('general', 'task_monitor'), nargs='?')
parser.add_argument("trace",        help="trace file",  default=config.get('general', 'trace'), nargs='?')
parser.add_argument("--ext_temp",   help="extruder temperature (for UI feedback only)",  default=180, nargs='?')
parser.add_argument("--bed_temp",   help="bed temperature (for UI feedback only)",  default=50,  nargs='?')
parser.add_argument("--standalone", help="call macros internally",  default=False, nargs='?')

# GET ARGUMENTS
args = parser.parse_args()
#!/bin/env python
# -*- coding: utf-8; -*-

# Import internal modules
from fabtotum.fabui.config import ConfigService

cfg = ConfigService()

print cfg.get('serial', 'baud')
print cfg.get('serial', 'port')
print cfg.get('task', 'lock_file')
Example #33
0
class RemoteVersion:
    def __init__(self, arch='armhf', mcu='atmega1280', config=None):
        self.config = config
        if not config:
            self.config = ConfigService()

        self.colibri_endpoint = self.config.get('updates', 'colibri_endpoint')
        self.firmware_endpoint = self.config.get('updates',
                                                 'firmware_endpoint')
        self.plugin_endpoint = self.config.get('updates', 'plugins_endpoint')
        self.arch = arch
        self.mcu = mcu
        self.colibri = None
        self.firmware = None
        self.plugins = None
        self.setColibri()
        self.setFirmware()
        self.setPlugins()

    def getRemoteData(self, endpoint):
        curl = pycurl.Curl()
        buffer = BytesIO()
        curl.setopt(pycurl.URL, endpoint)
        curl.setopt(pycurl.TIMEOUT, 30)
        curl.setopt(pycurl.FOLLOWLOCATION, 1)
        curl.setopt(pycurl.SSL_VERIFYPEER, 0)
        curl.setopt(pycurl.SSL_VERIFYHOST, 0)
        curl.setopt(pycurl.MAXREDIRS, 5)
        curl.setopt(curl.WRITEDATA, buffer)
        curl.perform()
        return buffer.getvalue()

    def setColibri(self):
        self.colibri = json.loads(
            self.getRemoteData(
                os.path.join(self.colibri_endpoint, self.arch,
                             "version.json")))

    def setFirmware(self):
        self.firmware = json.loads(
            self.getRemoteData(
                os.path.join(self.firmware_endpoint, "fablin", self.mcu,
                             "version.json")))

    def setPlugins(self):
        self.plugins = json.loads(
            self.getRemoteData(
                os.path.join(self.plugin_endpoint, "cached.json")))

    def getColibri(self):
        return self.colibri

    def getBundles(self):
        return self.colibri['bundles']

    def getBoot(self):
        return self.colibri['boot']

    def getImages(self):
        return self.colibri['images']

    def getFirmware(self):
        if 'firmware' in self.firmware:
            return self.firmware['firmware']
        return {}

    def getPlugins(self):
        return self.plugins

    def getColibriEndpoint(self):
        return os.path.join(self.colibri_endpoint, self.arch)

    def getFirmwareEndpoint(self):
        return os.path.join(self.firmware_endpoint, 'fablin', self.mcu)

    def getPluginsEndpoint(self):
        return self.firmware_endpoint
from fabtotum.utils.pyro.gcodeserver    import GCodeServiceServer
from fabtotum.os.monitor.filesystem     import FolderTempMonitor
from fabtotum.os.monitor.usbdrive       import UsbMonitor
from fabtotum.os.monitor.gpiomonitor    import GPIOMonitor

def signal_handler(signal, frame):
    print "You pressed Ctrl+C!"
    print "Shutting down services. Please wait..."
    ws.close()
    gcserver.stop()
    gcservice.stop()
    observer.stop()
    usbMonitor.stop()
    gpioMonitor.stop()

config = ConfigService()

# Load configuration
LOCK_FILE           = config.get('general', 'lock')
TRACE               = config.get('general', 'trace')
COMMAND             = config.get('general', 'command')
MACRO_RESPONSE      = config.get('general', 'macro_response')
TASK_MONITOR        = config.get('general', 'task_monitor')
EMERGENCY_FILE      = config.get('general', 'emergency_file')
##################################################################
SOCKET_HOST         = config.get('socket', 'host')
SOCKET_PORT         = config.get('socket', 'port')
##################################################################
HW_DEFAULT_SETTINGS = config.get('hardware', 'default_settings')
HW_CUSTOM_SETTINGS  = config.get('hardware', 'custom_settings')
##################################################################