def removeLibrary(self, selected): """ Run a CLI command with the ID of the library to uninstall, also remove the reference of the ID in the preferences file. Arguments: selected {int} position of the option selected in the quick panel. """ list = self.getLibrary('quick_list.json') lib_id = list[selected][2] lib_name = list[selected][0] self.message_queue.startPrint() self.message_queue.put('[ Deviot {0} ]\\n', version) time.sleep(0.01) # uninstall Library with CLI command = ['lib', 'uninstall', lib_id] self.Commands.runCommand(command, extra_message=lib_name) # remove from preferences if (not self.Commands.error_running): installed = self.Preferences.get('user_libraries', '') if (installed): if (lib_id in installed): self.Preferences.data.setdefault('user_libraries', []).remove(lib_id) self.Preferences.saveData() # update menu Tools.updateMenuLibs()
def removeLibrary(self, selected): """ Run a CLI command with the ID of the library to uninstall, also remove the reference of the ID in the preferences file. Arguments: selected {int} position of the option selected in the quick panel. """ list = self.getLibrary('quick_list.json') lib_id = list[selected][2] lib_name = list[selected][0] self.message_queue.startPrint() self.message_queue.put('[ Deviot {0} ]\\n', version) time.sleep(0.01) # uninstall Library with CLI command = ['lib', 'uninstall', lib_id] self.Commands.runCommand(command, extra_message=lib_name) # remove from preferences if (not self.Commands.error_running): installed = self.Preferences.get('user_libraries', '') if(installed): if(lib_id in installed): self.Preferences.data.setdefault( 'user_libraries', []).remove(lib_id) self.Preferences.saveData() # update menu Tools.updateMenuLibs()
def plugin_unloaded(): try: from package_control import events if events.remove(package_name): Tools.removePreferences() except: pass
def on_activated(self, view): """ Set the current version of Deviot Arguments: view {ST object} -- Sublime Text Object """ PlatformioCLI(view, command=False).checkInitFile() Tools.setStatus(view) Tools.userPreferencesStatus(view)
def run(self, board_id): native = Preferences().get('native', False) key = 'env_selected' if (native): key = 'native_env_selected' Preferences().set(key, board_id) Tools.userPreferencesStatus(self.window.active_view())
def run(self, board_id): native = Preferences().get('native', False) key = 'env_selected' if(native): key = 'native_env_selected' Preferences().set(key, board_id) Tools.userPreferencesStatus(self.window.active_view())
def generateFiles(install=False): # Creates new menu api_boards = Paths.getTemplateMenuPath('platformio_boards.json', user_path=True) # create main files PlatformioCLI().saveAPIBoards(install=install) Menu().createMainMenu() Tools.createCompletions() Tools.createSyntaxFile() Menu().createLibraryImportMenu() Menu().createLibraryExamplesMenu() # Run serial port listener Serial = SerialListener(func=Menu().createSerialPortsMenu) Serial.start()
def endSetup(self): # get pio version executable = os.path.join(self.env_bin_dir, 'pio') cmd = ['\"' + executable + '\"', '--version'] out = childProcess(cmd) pio_version = match(r"\w+\W \w+ (.+)", out[1]).group(1) self.Preferences.set('pio_version', pio_version) # save env paths env_path = [self.env_bin_dir] self.saveEnvPaths(env_path) # copy menu sys_os = Tools.getOsName() preset_path = Paths.getPresetPath() plg_path = Paths.getPluginPath() dst = os.path.join(plg_path, 'Settings-Default', 'Main.sublime-menu') if(sys_os == 'windows'): src_path = os.path.join(preset_path, 'Main.sublime-menu.windows') copy(src_path, dst) elif(sys_os == 'osx'): src_path = os.path.join(preset_path, 'Main.sublime-menu.osx') copy(src_path, dst) else: src_path = os.path.join(preset_path, 'Main.sublime-menu.linux') copy(src_path, dst) # creating files (menu, completions, syntax) generateFiles()
def uploadSketchProject(self): ''' Upload the sketch to the select board to the select COM port it returns an error if any com port is selected ''' id_port = self.Preferences.get('id_port', '') current_ports = listSerialPorts() if(id_port not in current_ports and id_port != 'none'): id_port = False # check port selected if(not id_port): current_time = time.strftime('%H:%M:%S') self.message_queue.put('none_port_select_{0}', current_time) self.execute = False if(not self.execute): self.message_queue.stopPrint() return # Stop serial monitor Tools.closeSerialMonitors(self.Preferences) # Compiling code choosen_env = self.buildSketchProject() if(not choosen_env): return if(self.Commands.error_running): self.message_queue.stopPrint() return up_port = '--upload-port %s' % id_port if(id_port == 'none'): up_port = '' command = ['run', '-t upload %s -e %s' % (up_port, choosen_env)] self.Commands.runCommand(command) if(not self.Commands.error_running): autorun = self.Preferences.get('autorun_monitor', False) if(autorun): Tools.toggleSerialMonitor() self.Preferences.set('autorun_monitor', False) self.message_queue.stopPrint()
def plugin_loaded(): protected = Preferences().get('protected') if(not protected): thread = threading.Thread(target=PioInstall().checkPio) thread.start() ThreadProgress(thread, _('processing'), _('done')) else: # creating files Tools.createCompletions() Tools.createSyntaxFile() Menu().createMainMenu() Menu().createLibraryImportMenu() Menu().createLibraryExamplesMenu() # Run serial port listener Serial_Lib = Serial.SerialListener(func=Menu().createSerialPortsMenu) Serial_Lib.start()
def uploadSketchProject(self): ''' Upload the sketch to the select board to the select COM port it returns an error if any com port is selected ''' id_port = self.Preferences.get('id_port', '') current_ports = listSerialPorts() if (id_port not in current_ports and id_port != 'none'): id_port = False # check port selected if (not id_port): current_time = time.strftime('%H:%M:%S') self.message_queue.put('none_port_select_{0}', current_time) self.execute = False if (not self.execute): self.message_queue.stopPrint() return # Stop serial monitor Tools.closeSerialMonitors(self.Preferences) # Compiling code choosen_env = self.buildSketchProject() if (not choosen_env): return if (self.Commands.error_running): self.message_queue.stopPrint() return up_port = '--upload-port %s' % id_port if (id_port == 'none'): up_port = '' command = ['run', '-t upload %s -e %s' % (up_port, choosen_env)] self.Commands.runCommand(command) if (not self.Commands.error_running): autorun = self.Preferences.get('autorun_monitor', False) if (autorun): Tools.toggleSerialMonitor() self.Preferences.set('autorun_monitor', False) self.message_queue.stopPrint()
def plugin_loaded(): protected = Preferences().get('protected') if (not protected): thread = threading.Thread(target=PioInstall().checkPio) thread.start() ThreadProgress(thread, _('processing'), _('done')) else: # creating files Tools.createCompletions() Tools.createSyntaxFile() Menu().createMainMenu() Menu().createLibraryImportMenu() Menu().createLibraryExamplesMenu() # Run serial port listener Serial_Lib = Serial.SerialListener(func=Menu().createSerialPortsMenu) Serial_Lib.start()
def listRootPath(): root_list = [] os_name = Tools.getOsName() if os_name == 'windows': root_list = listWinVolume() else: home_path = os.getenv('HOME') root_list = [home_path, ROOT_PATH] return root_list
def __init__(self): self.lang_params = {} self.ids_lang = [] self.id_path_dict = {} self.trans_dict = {} self.listIds() self.Preferences = Preferences() self.id_lang = self.Preferences.get('id_lang', Tools.getSystemLang()) self.changeLang(self.id_lang)
def getAPIBoards(self): ''' Get the list of boards from platformIO API using CLI. To know more info about platformIO visit: http://www.platformio.org/ Returns: {json object} -- list with all boards in a JSON format ''' window = sublime.active_window() view = window.active_view() Tools.setStatus(view, _('updating_board_list')) boards = [] Run = CommandsPy() command = ['boards', '--json-output'] boards = Run.runCommand(command, setReturn=True) Tools.setStatus(view, _('Done'), erase_time=4000) return boards
def on_close(self, view): """ When a sketch is closed, temp files are deleted Arguments: view {ST object} -- Sublime Text Object """ # Serial Monitor monitor_module = Serial if Messages.isMonitorView(view): name = view.name() serial_port = name.split('-')[1].strip() if serial_port in monitor_module.serials_in_use: cur_serial_monitor = monitor_module.serial_monitor_dict.get( serial_port, None) if cur_serial_monitor: cur_serial_monitor.stop() monitor_module.serials_in_use.remove(serial_port) # Remove cache keep_cache = Preferences().get('keep_cache', True) if (keep_cache): return file_path = Tools.getPathFromView(view) if (not file_path): return file_name = Tools.getFileNameFromPath(file_path, ext=False) tmp_path = Paths.getTempPath() tmp_all = os.path.join(tmp_path, '*') tmp_all = glob.glob(tmp_all) for content in tmp_all: if file_name in content: tmp_path = os.path.join(tmp_path, content) rmtree(tmp_path, ignore_errors=False) Preferences().set('builded_sketch', False) # Empty enviroment menu Menu().createEnvironmentMenu(empty=True)
def on_close(self, view): """ When a sketch is closed, temp files are deleted Arguments: view {ST object} -- Sublime Text Object """ # Serial Monitor monitor_module = Serial if Messages.isMonitorView(view): name = view.name() serial_port = name.split('-')[1].strip() if serial_port in monitor_module.serials_in_use: cur_serial_monitor = monitor_module.serial_monitor_dict.get( serial_port, None) if cur_serial_monitor: cur_serial_monitor.stop() monitor_module.serials_in_use.remove(serial_port) # Remove cache keep_cache = Preferences().get('keep_cache', True) if(keep_cache): return file_path = Tools.getPathFromView(view) if(not file_path): return file_name = Tools.getFileNameFromPath(file_path, ext=False) tmp_path = Paths.getTempPath() tmp_all = os.path.join(tmp_path, '*') tmp_all = glob.glob(tmp_all) for content in tmp_all: if file_name in content: tmp_path = os.path.join(tmp_path, content) rmtree(tmp_path, ignore_errors=False) Preferences().set('builded_sketch', False) # Empty enviroment menu Menu().createEnvironmentMenu(empty=True)
def getEnvPaths(self): # default paths default_paths = Tools.getDefaultPaths() system_paths = os.environ.get("PATH", "").split(os.path.pathsep) env_paths = [] env_paths.extend(default_paths) env_paths.extend(system_paths) env_paths = list(OrderedDict.fromkeys(env_paths)) env_paths = os.path.pathsep.join(env_paths) return env_paths
def getEnvBinDir(): env_dir = getEnvDir() env_bin_dir = os.path.join( env_dir, 'Scripts' if 'windows' in Tools.getOsName() else 'bin') try: os.makedirs(env_bin_dir) except OSError as exc: if exc.errno != errno.EEXIST: raise exc pass return env_bin_dir
def listSerialPorts(): """ List all the serial ports availables in the diffents O.S """ os_name = Tools.getOsName() if os_name == "windows": serial_ports = listWinSerialPorts() elif os_name == 'osx': serial_ports = listOsxSerialPorts() else: serial_ports = listLinuxSerialPorts() serial_ports.sort() return serial_ports
def saveAPIBoards(self, update_method=False, install=False): ''' Save the JSON object in a specific JSON file ''' try: from .Menu import Menu except: from libs.Menu import Menu window = sublime.active_window() view = window.active_view() Tools.setStatus(view, _('updating_board_list')) # console if (not install): console_name = 'Deviot|GetBoards' + str(time.time()) console = Console(window, name=console_name) new_console = True # Queue for the user console message_queue = MessageQueue(console) message_queue.startPrint() message_queue.put("[Deviot {0}]\n", version) message_queue.put("download_board_list") boards = self.getAPIBoards() self.Menu.saveTemplateMenu(data=boards, file_name='platformio_boards.json', user_path=True) self.saveEnvironmentFile() Menu().createMainMenu() if (not install): message_queue.put("list_updated")
def saveAPIBoards(self, update_method=False, install=False): ''' Save the JSON object in a specific JSON file ''' try: from .Menu import Menu except: from libs.Menu import Menu window = sublime.active_window() view = window.active_view() Tools.setStatus(view, _('updating_board_list')) # console if (not install): console_name = 'Deviot|GetBoards' + str(time.time()) console = Console(window, name=console_name) new_console = True # Queue for the user console message_queue = MessageQueue(console) message_queue.startPrint() message_queue.put("[Deviot {0}]\n", version) message_queue.put("download_board_list") boards = self.getAPIBoards() self.Menu.saveTemplateMenu( data=boards, file_name='platformio_boards.json', user_path=True) self.saveEnvironmentFile() Menu().createMainMenu() if(not install): message_queue.put("list_updated")
def installLibrary(self, selected): """ Install the selected library Arguments: selected {int} position in dict of the library selected """ list = self.getLibrary('quick_list.json') lib_id = list[selected][2] lib_name = list[selected][0] self.message_queue.startPrint() self.message_queue.put('[ Deviot {0} ]\\n', version) time.sleep(0.01) # Install Library with CLI command = ['lib', 'install', lib_id] self.Commands.runCommand(command, extra_message=lib_name) # update list of libraries installed in the preference file self.getInstalledList(ids=True) # update menu Tools.updateMenuLibs()
def endSetup(self): try: from .PlatformioCLI import generateFiles except: from libs.PlatformioCLI import generateFiles # save env paths if(self.os != 'osx'): env_path = [self.env_bin_dir] self.saveEnvPaths(env_path) # get pio version if(self.os == 'osx'): executable = os.path.join(self.env_bin_dir, 'python') cmd = ['"%s"' % (executable), '-m', 'platformio', '--version'] else: executable = os.path.join(self.env_bin_dir, 'pio') cmd = ['"%s"' % (executable), '--version'] out = childProcess(cmd) pio_version = match(r"\w+\W \w+ (.+)", out[1]).group(1) self.Preferences.set('pio_version', pio_version) # copy menu sys_os = Tools.getOsName() preset_path = Paths.getPresetPath() plg_path = Paths.getPluginPath() dst = os.path.join(plg_path, 'Settings-Default', 'Main.sublime-menu') if(sys_os == 'windows'): if(platform.release() == '7'): src_path = os.path.join(preset_path, 'Main.sublime-menu.w7') else: src_path = os.path.join(preset_path, 'Main.sublime-menu.windows') copy(src_path, dst) elif(sys_os == 'osx'): src_path = os.path.join(preset_path, 'Main.sublime-menu.osx') copy(src_path, dst) else: src_path = os.path.join(preset_path, 'Main.sublime-menu.linux') copy(src_path, dst) # creating files (menu, completions, syntax) sublime.set_timeout(generateFiles, 0) self.Preferences.set('protected', True) self.Preferences.set('enable_menu', True)
def __init__(self): self.Preferences = Preferences() self.base_dir = Paths.getDeviotUserPath() self.env_dir = Paths.getEnvDir() self.env_bin_dir = Paths.getEnvBinDir() self.cache_dir = Paths.getCacheDir() self.env_file = Paths.getEnvFile() self.cached_file = False self.os = Tools.getOsName() # console window = sublime.active_window() console_name = 'Deviot|Pio_Install' + str(time.time()) console = Messages.Console(window, name=console_name) # Queue for the user console self.message_queue = Messages.MessageQueue(console)
def getTempPath(file_name=False): tmp_path = '/tmp' os_name = Tools.getOsName() if os_name == 'windows': tmp_path = os.environ['tmp'] tmp_path = os.path.join(tmp_path, 'Deviot') if(file_name): tmp_path = os.path.join(tmp_path, file_name) try: os.makedirs(tmp_path) except OSError as exc: if exc.errno != errno.EEXIST: raise exc pass return tmp_path
def getTempPath(file_name=False): tmp_path = '/tmp' os_name = Tools.getOsName() if os_name == 'windows': tmp_path = os.environ['tmp'] tmp_path = os.path.join(tmp_path, 'Deviot') if (file_name): tmp_path = os.path.join(tmp_path, file_name) try: os.makedirs(tmp_path) except OSError as exc: if exc.errno != errno.EEXIST: raise exc pass return tmp_path
def checkInitFile(self): """ Check each platformio.ini file and loads the environments already initialized. """ protected = self.Preferences.get('protected', False) if(not protected): return # Empy menu if it's not a IoT file if(not self.is_iot): if(Tools.getPythonVersion() > 2): self.Menu.createEnvironmentMenu(empty=True) return ini_path = Paths.getFullIniPath(self.dir) # show non native data if(not self.is_native): self.Preferences.set('native', False) self.Preferences.set('ini_path', self.dir) self.Menu.createEnvironmentMenu() return else: self.Preferences.set('native', True) self.Preferences.set('ini_path', self.dir) # get data from platformio.ini file ini_list = [] with open(ini_path, 'r') as file: pattern = compile(r'\[(\w+)\W(\w+)\]') for line in file: if pattern.findall(line): if('#' not in line): line = match(r"\[\w+:(\w+)\]", line).group(1) ini_list.append(line) # save preferences, update menu data type = 'board_id' if not self.is_native else 'found_ini' self.Preferences.set(type, ini_list) self.Menu.createEnvironmentMenu()
def run(self, example_path): Tools.openExample(example_path, self.window)
from __future__ import print_function from __future__ import division from __future__ import unicode_literals import threading import sublime import time try: from . import Tools from .I18n import I18n except: from libs import Tools from libs.I18n import I18n python_version = Tools.getPythonVersion() if python_version < 3: import Queue as queue else: import queue _ = I18n().translate class MessageQueue(object): """ Print messages in the user console, placed in the message queue """
def on_done(self, text): if (text): Tools.sendSerialMessage(text) self.window.run_command('send_message_serial')
def run(self): confirm = sublime.ok_cancel_dialog(_('confirm_del_pref'), _('continue')) if (confirm): Tools.removePreferences()
def run(self, edit, text, erase_time): Tools.setStatus(self.view, text, erase_time)
from __future__ import print_function from __future__ import division from __future__ import unicode_literals import threading import sublime import time try: from . import Tools from .I18n import I18n except: from libs import Tools from libs.I18n import I18n python_version = Tools.getPythonVersion() if python_version < 3: import Queue as queue else: import queue _ = I18n().translate class MessageQueue(object): """ Print messages in the user console, placed in the message queue """ def __init__(self, console=None):
def __init__(self, view=False, console=False, install=False, command=True): ''' Initialize the command and preferences classes, to check if the current work file is an IoT type it received the view parameter (ST parameter). This parameter is necessary only in the options like build or upload. Keyword Arguments: view {st object} -- stores many info related with ST (default: False) ''' self.Preferences = Preferences() self.Menu = Menu() # user console if (console): current_time = time.strftime('%H:%M:%S') self.message_queue = MessageQueue(console) self.message_queue.startPrint() # For installing purposes if (install): self.Commands = CommandsPy(console=console) return self.view = view self.execute = True self.is_native = False self.is_iot = False if (view): # avoid to do anything with a monitor view view_name = view.name() sketch_size = view.size() file_path = Tools.getPathFromView(view) if (not file_path and 'monitor' in view_name.lower()): try: current_time = time.strftime('%H:%M:%S') self.message_queue.put('invalid_file_{0}', current_time) except: pass self.execute = False return # unsaved file if (command and not file_path and sketch_size > 0): saved_file = self.saveCodeInFile(view) view = saved_file[1] file_path = Tools.getPathFromView(view) if (command and not sketch_size): self.message_queue.put('not_empty_sketch_{0}', current_time) # current file / view current_path = Paths.getCurrentFilePath(view) if (not current_path): return self.is_iot = Tools.isIOTFile(view) current_dir = Paths.getCWD(current_path) parent_dir = Paths.getParentCWD(current_path) file_name = Tools.getFileNameFromPath(file_path) temp_name = Tools.getFileNameFromPath(current_path, ext=False) if (not self.is_iot): self.execute = False # check IoT type file if (console and not self.is_iot and not self.execute): current_time = time.strftime('%H:%M:%S') msg = 'not_iot_{0}{1}' if (not file_name): msg = 'not_empty_sketch_{0}' self.message_queue.put(msg, current_time, file_name) self.execute = False return if (not command and not self.is_iot): return # Check native project for file in os.listdir(parent_dir): if (file.endswith('platformio.ini')): self.dir = parent_dir self.src = False self.is_native = True break # set native paths if (not self.is_native): build_dir = Paths.getBuildPath(temp_name) if (not build_dir): build_dir = Paths.getTempPath(temp_name) self.src = current_dir self.dir = build_dir # unsaved changes if (command and view.is_dirty()): view.run_command('save') if (console): self.message_queue.put('[ Deviot {0} ] {1}\\n', version, file_name) time.sleep(0.02) # Initilized commands self.Commands = CommandsPy(console=console, cwd=self.dir)
import time import glob import threading try: from . import Tools from . import pyserial from . import Messages from .Preferences import Preferences except: from libs import Tools from libs import pyserial from libs import Messages from libs.Preferences import Preferences if Tools.getOsName() == 'windows': if Tools.getPythonVersion() < 3: import _winreg as winreg else: import winreg @Tools.singleton class SerialListener(object): """ Constantly checks if a port has been connected or disconnected """ def __init__(self, func=None): self.func = func self.serial_list = [] self.is_alive = False
def run(self, edit, library_path): Tools.addLibraryToSketch(self.view, edit, library_path)
def run(self): Tools.toggleSerialMonitor(self.window)
from .Commands import CommandsPy from .Messages import MessageQueue from .I18n import I18n except: import libs.Paths as Paths import libs.Tools as Tools from libs import Messages from libs import __version__ as version from libs.JSONFile import JSONFile from libs.Preferences import Preferences from libs.Progress import ThreadProgress from libs.Commands import CommandsPy from libs.Messages import MessageQueue from libs.I18n import I18n if(Tools.getPythonVersion() < 3): from urllib import urlencode from urllib2 import Request from urllib2 import urlopen else: from urllib.parse import urlencode from urllib.request import Request from urllib.request import urlopen _ = I18n().translate class Libraries: """ Handle the library API from platformIO More info: http://docs.platformio.org/en/latest/librarymanager/index.html
def run(self): confirm = sublime.ok_cancel_dialog( _('confirm_del_pref'), _('continue')) if(confirm): Tools.removePreferences()
def __init__(self, view=False, console=False, install=False, command=True): ''' Initialize the command and preferences classes, to check if the current work file is an IoT type it received the view parameter (ST parameter). This parameter is necessary only in the options like build or upload. Keyword Arguments: view {st object} -- stores many info related with ST (default: False) ''' self.Preferences = Preferences() self.Menu = Menu() # user console if(console): current_time = time.strftime('%H:%M:%S') self.message_queue = MessageQueue(console) self.message_queue.startPrint() # For installing purposes if(install): self.Commands = CommandsPy(console=console) return self.view = view self.execute = True self.is_native = False self.is_iot = False if(view): # avoid to do anything with a monitor view view_name = view.name() sketch_size = view.size() file_path = Tools.getPathFromView(view) if(not file_path and 'monitor' in view_name.lower()): try: current_time = time.strftime('%H:%M:%S') self.message_queue.put('invalid_file_{0}', current_time) except: pass self.execute = False return # unsaved file if(command and not file_path and sketch_size > 0): saved_file = self.saveCodeInFile(view) view = saved_file[1] file_path = Tools.getPathFromView(view) if(command and not sketch_size): self.message_queue.put('not_empty_sketch_{0}', current_time) # current file / view current_path = Paths.getCurrentFilePath(view) if(not current_path): return self.is_iot = Tools.isIOTFile(view) current_dir = Paths.getCWD(current_path) parent_dir = Paths.getParentCWD(current_path) file_name = Tools.getFileNameFromPath(file_path) temp_name = Tools.getFileNameFromPath(current_path, ext=False) if(not self.is_iot): self.execute = False # check IoT type file if(console and not self.is_iot and not self.execute): current_time = time.strftime('%H:%M:%S') msg = 'not_iot_{0}{1}' if(not file_name): msg = 'not_empty_sketch_{0}' self.message_queue.put(msg, current_time, file_name) self.execute = False return if(not command and not self.is_iot): return # Check native project for file in os.listdir(parent_dir): if(file.endswith('platformio.ini')): self.dir = parent_dir self.src = False self.is_native = True break # set native paths if(not self.is_native): build_dir = self.Preferences.get('build_dir', False) if(not build_dir): build_dir = Paths.getTempPath(temp_name) self.src = current_dir self.dir = build_dir # unsaved changes if (command and view.is_dirty()): view.run_command('save') if(console): self.message_queue.put( '[ Deviot {0} ] {1}\\n', version, file_name) time.sleep(0.02) # Initilized commands self.Commands = CommandsPy(console=console, cwd=self.dir)
def on_done(self, text): if(text): Tools.sendSerialMessage(text) self.window.run_command('send_message_serial')
import time import glob import threading try: from . import Tools from . import pyserial from . import Messages from .Preferences import Preferences except: from libs import Tools from libs import pyserial from libs import Messages from libs.Preferences import Preferences if Tools.getOsName() == 'windows': if Tools.getPythonVersion() < 3: import _winreg as winreg else: import winreg @Tools.singleton class SerialListener(object): """ Constantly checks if a port has been connected or disconnected """ def __init__(self, func=None): self.func = func self.serial_list = []
from .Commands import CommandsPy from .Messages import MessageQueue from .I18n import I18n except: import libs.Paths as Paths import libs.Tools as Tools from libs import Messages from libs import __version__ as version from libs.JSONFile import JSONFile from libs.Preferences import Preferences from libs.Progress import ThreadProgress from libs.Commands import CommandsPy from libs.Messages import MessageQueue from libs.I18n import I18n if (Tools.getPythonVersion() < 3): from urllib import urlencode from urllib2 import Request from urllib2 import urlopen else: from urllib.parse import urlencode from urllib.request import Request from urllib.request import urlopen _ = I18n().translate class Libraries: """ Handle the library API from platformIO More info: http://docs.platformio.org/en/latest/librarymanager/index.html
def checkPio(self): # defining default env paths os.environ['PATH'] = self.getEnvPaths() # checking python cmd = ['python', '--version'] out = childProcess(cmd) # show error and link to download if(out[0] > 0): current_time = time.strftime('%H:%M:%S') go_to = sublime.ok_cancel_dialog( "deviot_need_python", "button_download_python") if(go_to): sublime.run_command( 'open_url', {'url': 'https://www.python.org/downloads/'}) return # check if pio is installed self.message_queue.startPrint() self.message_queue.put("deviot_setup{0}", version) current_time = time.strftime('%H:%M:%S') cmd = ['pio', '--version'] out = childProcess(cmd) if(out[0] == 0): current_time = time.strftime('%H:%M:%S') self.message_queue.put("pio_is_installed{0}", current_time) self.endSetup() return current_time = time.strftime('%H:%M:%S') self.message_queue.put("pio_isn_installed{0}", current_time) # check if virtualenv file is cached if(os.path.exists(self.env_file)): self.cached_file = True # download virtualenv if(not self.cached_file): current_time = time.strftime('%H:%M:%S') self.message_queue.put("downloading_files{0}", current_time) headers = Tools.getHeaders() url_file = 'https://pypi.python.org/packages/source/v/virtualenv/virtualenv-14.0.1.tar.gz' try: file_request = Request(url_file, headers=headers) file_open = urlopen(file_request) file = file_open.read() except: current_time = time.strftime('%H:%M:%S') self.message_queue.put( "error_downloading_files{0}", current_time) print("There was an error downloading virtualenv") return # save file try: output = open(self.env_file, 'wb') output.write(bytearray(file)) output.close() except: current_time = time.strftime('%H:%M:%S') self.message_queue.put("error_saving_files{0}", current_time) print("There was an error saving the virtualenv file") return # extract file current_time = time.strftime('%H:%M:%S') self.message_queue.put("extracting_files{0}", current_time) tmp = tempfile.mkdtemp() Tools.extractTar(self.env_file, tmp) # install virtualenv in a temp dir current_time = time.strftime('%H:%M:%S') self.message_queue.put("installing_pio{0}", current_time) temp_env = os.path.join(tmp, 'env-root') cwd = os.path.join(tmp, 'virtualenv-14.0.1') cmd = ['python', 'setup.py', 'install', '--root', temp_env] out = childProcess(cmd, cwd) # error if(out[0] > 0): current_time = time.strftime('%H:%M:%S') self.message_queue.put("error_installing_env_{0}", current_time) return # make vitualenv for root, dirs, files in os.walk(tmp): for file in files: if(file == 'virtualenv.py'): cwd = root if(os.path.exists(cwd)): cmd = ['python', 'virtualenv.py', '\"' + self.env_dir + '\"'] out = childProcess(cmd, cwd) # error if(out[0] > 0): current_time = time.strftime('%H:%M:%S') self.message_queue.put("error_making_env_{0}", current_time) return # remove temp dir rmtree(tmp) # install pio executable = os.path.join(self.env_bin_dir, 'pip') cmd = ['\"' + executable + '\"', 'install', 'platformio'] out = childProcess(cmd) # error if(out[0] > 0): current_time = time.strftime('%H:%M:%S') self.message_queue.put("error_installing_pio_{0}", current_time) return self.endSetup() current_time = time.strftime('%H:%M:%S') self.message_queue.put("setup_finished{0}", current_time)