Commit 81883d2c authored by carlosperate's avatar carlosperate

Update ardublocklyserver package to use new names.

This commit goes hand-in-hand with the previous. They were separated in order to ensure git correctly captured in the history the file renames instead of thinking there were deletions and new files created.
parent 5f9f062d
# -*- coding: utf-8 -*-
#
# ardublocklyserver package.
#
# Copyright (c) 2015 carlosperate https://github.com/carlosperate/
# Licensed under the Apache License, Version 2.0 (the "License"):
# http://www.apache.org/licenses/LICENSE-2.0
#
# Explicit imports will be used, only version included here.
#
__version__ = '0.1a'
......@@ -6,23 +6,32 @@
# Licensed under the Apache License, Version 2.0 (the "License"):
# http://www.apache.org/licenses/LICENSE-2.0
#
# The ServerCompilerSettings is a singleton class maintains in memory, and
# writes the Arduino IDE settings into a file.
# On first invocation of the singleton it reads the settings from the file.
#
from __future__ import unicode_literals, absolute_import
import os
import re
import codecs
import sys
import codecs
try:
# 2.x name
import ConfigParser
except ImportError:
# 3.x name
import configparser as ConfigParser
import ArdublocklyServer.SerialPort
import ardublocklyserver.serialport
class ServerCompilerSettings(object):
"""
Retrieves and saves the settings for the server side compilation.
Singleton class that retrieves and saves the settings for the server side
compilation.
The class on first invocation tries to read the settings from the file, it
keeps them in memory, and every time they are modified the changes are also
written into the file.
No compiler is part of the Python code, instead settings that
point to the local Arduino IDE and sketch are stored here.
The public settings to set and get are:
......@@ -34,12 +43,14 @@ class ServerCompilerSettings(object):
launch_IDE_option
"""
# Designed to be class static variables
# Class variables that after initialisation will not change
__singleton_instance = None
__settings_filename = 'ServerCompilerSettings.ini'
__settings_path = None
# This is a static dictionary to define Arduino board types
# Class variable to indicate the settings filename, does not change
__settings_filename = 'ServerCompilerSettings.ini'
# Class dictionary to define Arduino board types, does not change
__arduino_types = {'Uno': 'arduino:avr:uno',
'Leonardo': 'arduino:avr:leonardo',
'Mega': 'arduino:avr:mega',
......@@ -47,12 +58,12 @@ class ServerCompilerSettings(object):
'Duemilanove_168p':
'arduino:avr:diecimila:cpu=atmega168'}
# This is a dynamic dictionary containing the PC COM ports
# Class dictionary to contain the computer COM ports, changes
__serial_ports = {'port1': 'COM1',
'port2': 'COM2',
'port3': 'COM3'}
# This is a static dictionary to define IDE launch options
# Class dictionary to define IDE launch options, value doesn't change
__IDE_launch_options = {'open': 'Open sketch in IDE ',
'verify': 'Verify sketch',
'upload': 'Compile and Upload sketch'}
......@@ -407,7 +418,7 @@ class ServerCompilerSettings(object):
Populates the __serial_ports__ dictionary with the Serial Ports
available.
"""
port_list = ArdublocklyServer.SerialPort.get_port_list()
port_list = ardublocklyserver.serialport.get_port_list()
self.__serial_ports = {}
if port_list:
port_id = 0
......
......@@ -24,9 +24,9 @@ import sys, os, re
import os
# chose an implementation, depending on os
if os.name == 'nt': #sys.platform == 'win32':
from ArdublocklyServer.PySerialListPorts.list_ports_windows import *
from ardublocklyserver.pyserialports.list_ports_windows import *
elif os.name == 'posix':
from ArdublocklyServer.PySerialListPorts.list_ports_posix import *
from ardublocklyserver.pyserialports.list_ports_posix import *
#~ elif os.name == 'java':
else:
raise ImportError("Sorry: no implementation for your platform ('%s') available" % (os.name,))
......
......@@ -27,7 +27,7 @@ import os
plat = sys.platform.lower()
if plat[:5] == 'linux': # Linux (confirmed)
from ArdublocklyServer.PySerialListPorts.list_ports_linux import comports
from ardublocklyserver.pyserialports.list_ports_linux import comports
elif plat == 'cygwin': # cygwin/win32
def comports():
......@@ -47,7 +47,7 @@ elif plat[:3] == 'bsd' or \
return [(d, d, d) for d in devices]
elif plat[:6] == 'darwin': # OS X (confirmed)
from ArdublocklyServer.PySerialListPorts.list_ports_osx import comports
from ardublocklyserver.pyserialports.list_ports_osx import comports
elif plat[:6] == 'netbsd': # NetBSD
def comports():
......
......@@ -9,8 +9,8 @@ def ValidHandle(value, func, arguments):
return value
#import serial
from ArdublocklyServer.PySerialListPorts.serial_to_bytes import to_bytes
from ArdublocklyServer.PySerialListPorts.win32 import ULONG_PTR, is_64bit
from ardublocklyserver.pyserialports.serial_to_bytes import to_bytes
from ardublocklyserver.pyserialports.win32 import ULONG_PTR, is_64bit
from ctypes.wintypes import HANDLE
from ctypes.wintypes import BOOL
from ctypes.wintypes import HWND
......
# -*- coding: utf-8 -*-
#
# Receives and responds to the HTTP request from the Python server.
#
# Copyright (c) 2015 carlosperate https://github.com/carlosperate/
# Licensed under the Apache License, Version 2.0 (the "License"):
# http://www.apache.org/licenses/LICENSE-2.0
#
from __future__ import unicode_literals, absolute_import
import subprocess
import time
......@@ -16,9 +24,10 @@ except ImportError:
import urllib.parse as urlparse
import tkinter.filedialog as tkFileDialog
import http.server as SimpleHTTPServer
from ArdublocklyServer.Py23Compatibility import Py23Compatibility
from ArdublocklyServer.ServerCompilerSettings import ServerCompilerSettings
from ArdublocklyServer.SketchCreator import SketchCreator
from ardublocklyserver.py23 import py23
from ardublocklyserver.compilersettings import ServerCompilerSettings
from ardublocklyserver.sketchcreator import SketchCreator
class BlocklyRequestHandler(SimpleHTTPServer.SimpleHTTPRequestHandler):
......@@ -37,7 +46,7 @@ class BlocklyRequestHandler(SimpleHTTPServer.SimpleHTTPRequestHandler):
if content_type == 'application/x-www-form-urlencoded':
parameters = urlparse.parse_qs(
Py23Compatibility.b_unicode(self.rfile.read(content_length)),
py23.b_unicode(self.rfile.read(content_length)),
keep_blank_values=False)
message_back = handle_settings(parameters)
elif content_type == 'text/plain':
......@@ -46,7 +55,8 @@ class BlocklyRequestHandler(SimpleHTTPServer.SimpleHTTPRequestHandler):
# At this point message back should contain a normal string
# with the sketch code
message_back =\
'// Ardublockly generated sketch\n\r' + data_string
'// Ardublockly generated sketch\n' + \
data_string.decode('utf-8')
except Exception as e:
print(e)
print('\nThere was an error manipulating the sketch data!!!')
......@@ -181,7 +191,7 @@ def load_arduino_cli(sketch_path=None):
:return: A tuple with the following data (output, error output, exit code)
"""
# Input sanitation and output defaults
if not isinstance(sketch_path, Py23Compatibility.string_type_compare) \
if not isinstance(sketch_path, py23.string_type_compare) \
or not sketch_path:
sketch_path = create_sketch_default()
success = True
......@@ -250,7 +260,7 @@ def load_arduino_cli(sketch_path=None):
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
shell=False)
(out, error) = process.communicate()
out, error = process.communicate()
exit_code = str(process.returncode)
print('Arduino output:\n' + out)
print('Arduino Error output:\n' + error)
......
# -*- coding: utf-8 -*-
#
# Functions to retrieve the computer Serial Port list.
#
# Copyright (c) 2015 carlosperate https://github.com/carlosperate/
# Licensed under the Apache License, Version 2.0 (the "License"):
# http://www.apache.org/licenses/LICENSE-2.0
#
from __future__ import unicode_literals, absolute_import
import ArdublocklyServer.PySerialListPorts.list_ports
import ardublocklyserver.pyserialports.list_ports
def get_port_complete_list():
......@@ -9,7 +17,7 @@ def get_port_complete_list():
:return: List with the Port information. Each list item contains a tuple
three elements in this order: (port name, descriptor, hw id)
"""
port_list = ArdublocklyServer.PySerialListPorts.list_ports.comports()
port_list = ardublocklyserver.pyserialports.list_ports.comports()
return sorted(port_list)
......
......@@ -6,7 +6,8 @@ try:
except ImportError:
# 3.x name
import http.server as BaseHTTPServer
import ArdublocklyServer.BlocklyRequestHandler
import ardublocklyserver.requesthandler
ADDRESS = '0.0.0.0'
PORT = 8000
......@@ -19,7 +20,7 @@ def start_server(document_root):
server_address = (ADDRESS, PORT)
server = BaseHTTPServer.HTTPServer(
server_address,
ArdublocklyServer.BlocklyRequestHandler.BlocklyRequestHandler)
ardublocklyserver.requesthandler.BlocklyRequestHandler)
print('Launching the HTTP service...')
server.serve_forever()
print('The Server closed unexpectedly!!')
......
# -*- coding: utf-8 -*-
#
# SketchCreator class creates an Arduino Sketch source code file.
#
# Copyright (c) 2015 carlosperate https://github.com/carlosperate/
# Licensed under the Apache License, Version 2.0 (the "License"):
# http://www.apache.org/licenses/LICENSE-2.0
#
from __future__ import unicode_literals, absolute_import
import os
from ArdublocklyServer.Py23Compatibility import Py23Compatibility
from ArdublocklyServer.ServerCompilerSettings import ServerCompilerSettings
from ardublocklyserver.py23 import py23
from ardublocklyserver.compilersettings import ServerCompilerSettings
class SketchCreator(object):
"""
Creates an Arduino Sketch
Creates an Arduino Sketch.
"""
#This is probably not the best way to create this string, will revisit
_sketch_default_code = 'int led = 13;void setup() {\n' \
#
# Metaclass methods
#
def __init__(self):
# Default sketch, blink builtin LED
self._sketch_default_code = \
'int led = 13;\n' \
'void setup() {\n' \
' pinMode(led, OUTPUT);\n' \
'}\n' \
'void loop() {\n' \
......@@ -20,26 +35,20 @@ class SketchCreator(object):
' delay(1000);\n' \
'}\n'
#
# Constructor
#
def __init__(self):
pass
#
# Creating files
#
def create_sketch(self, sketch_code=None):
"""
Creates the Ardunino sketch with either the default blinky
code or the code defined in the input parameter
Creates the Arduino sketch with either the default blinky
code or the code defined in the input parameter.
:param sketch_code: Unicode string with the code for the sketch
:param sketch_code: Unicode string with the code for the sketch.
:return: Unicode string with full path to the sketch file
Return None indicates an error has occurred
Return None indicates an error has occurred.
"""
sketch_path = self.build_sketch_path()
if isinstance(sketch_code, Py23Compatibility.string_type_compare)\
if isinstance(sketch_code, py23.string_type_compare)\
and sketch_code:
code_to_write = sketch_code
else:
......
# -*- coding: utf-8 -*-
#
# Unit test for the compilersettings module.
#
# Copyright (c) 2015 carlosperate https://github.com/carlosperate/
# Licensed under the Apache License, Version 2.0 (the "License"):
# http://www.apache.org/licenses/LICENSE-2.0
#
from __future__ import unicode_literals, absolute_import
import os
import unittest
import mock
try:
from ArdublocklyServer.ServerCompilerSettings import ServerCompilerSettings
except ImportError:
import sys
file_dir = os.path.dirname(os.path.realpath(__file__))
package_dir = os.path.dirname(os.path.dirname(file_dir))
sys.path.insert(0, package_dir)
from ArdublocklyServer.ServerCompilerSettings import ServerCompilerSettings
from ardublocklyserver.compilersettings import ServerCompilerSettings
class ServerCompilerSettingsTestCase(unittest.TestCase):
......@@ -37,9 +39,10 @@ class ServerCompilerSettingsTestCase(unittest.TestCase):
# Testing the compiler_dir getter and setter
#
def test_read_compiler_dir(self):
self.assertEqual(ServerCompilerSettings().compiler_dir, ServerCompilerSettings().__compiler_dir__)
self.assertEqual(ServerCompilerSettings().compiler_dir,
ServerCompilerSettings().__compiler_dir__)
@mock.patch('ArdublocklyServer.ServerCompilerSettings.os.path.exists')
@mock.patch('ardublocklyserver.compilersettings.os.path.exists')
def test_write_compiler_dir_invalid(self, mock_os_path_exists):
"""
Tests path doesn't get save if:
......@@ -56,21 +59,14 @@ class ServerCompilerSettingsTestCase(unittest.TestCase):
self.assertNotEqual(new_dir, ServerCompilerSettings().compiler_dir)
self.assertEqual(original_dir, ServerCompilerSettings().compiler_dir)
# Just a folder
# No extension is accepted as a valid compiler directory
mock_os_path_exists.return_value = True
new_dir = os.getcwd()
ServerCompilerSettings().compiler_dir = new_dir
self.assertNotEqual(new_dir, ServerCompilerSettings().compiler_dir)
self.assertEqual(original_dir, ServerCompilerSettings().compiler_dir)
# Non .exe file
mock_os_path_exists.return_value = True
new_dir = os.path.join(os.getcwd(), 'arduino.txt')
ServerCompilerSettings().compiler_dir = new_dir
self.assertNotEqual(new_dir, ServerCompilerSettings().compiler_dir)
self.assertEqual(original_dir, ServerCompilerSettings().compiler_dir)
self.assertEqual(new_dir, ServerCompilerSettings().compiler_dir)
self.assertNotEqual(original_dir, ServerCompilerSettings().compiler_dir)
@mock.patch('ArdublocklyServer.ServerCompilerSettings.os.path.exists')
@mock.patch('ardublocklyserver.compilersettings.os.path.exists')
def test_write_compiler_dir_valid(self, mock_os_path_exists):
mock_os_path_exists.return_value = True
new_dir = os.path.join(os.getcwd(), 'arduino.exe')
......
# -*- coding: utf-8 -*-
#
# Unit test for the requesthandler module.
#
# Copyright (c) 2015 carlosperate https://github.com/carlosperate/
# Licensed under the Apache License, Version 2.0 (the "License"):
# http://www.apache.org/licenses/LICENSE-2.0
#
from __future__ import unicode_literals, absolute_import
import os
import unittest
import mock
try:
from ArdublocklyServer import BlocklyRequestHandler
except ImportError:
import sys
file_dir = os.path.dirname(os.path.realpath(__file__))
package_dir = os.path.dirname(os.path.dirname(file_dir))
sys.path.insert(0, package_dir)
from ArdublocklyServer import BlocklyRequestHandler
from ardublocklyserver import requesthandler
class BlocklyRequestHandlerTestCase(unittest.TestCase):
......@@ -20,39 +22,40 @@ class BlocklyRequestHandlerTestCase(unittest.TestCase):
#
# Command line tests
#
@mock.patch('ArdublocklyServer.BlocklyRequestHandler.os')
@mock.patch('ArdublocklyServer.BlocklyRequestHandler.create_sketch_default')
@mock.patch('ardublocklyserver.requesthandler.subprocess.Popen')
@mock.patch('ardublocklyserver.requesthandler.create_sketch_default')
@mock.patch.object(
BlocklyRequestHandler.ServerCompilerSettings, 'get_compiler_dir',
requesthandler.ServerCompilerSettings, 'get_compiler_dir',
autospec=True)
def test_command_line_launch(self, mock_settings, mock_sketch, mock_os):
def test_command_line_launch(self, mock_settings, mock_sketch, mock_popen):
"""
Tests that a compiler path and arduino sketch path can be set
and that a command line can be launched to open the sketch in the
Arduino IDE
Arduino IDE.
"""
#TODO: This test is outdated and needs to be rewritten
# Set the compiler settings
test_sketch_path = os.path.join(os.getcwd(), 'sketch.ino')
mock_sketch.return_value = test_sketch_path
test_compiler_dir = os.path.join(os.getcwd(), 'arduino.exe')
mock_settings = BlocklyRequestHandler.ServerCompilerSettings()
mock_settings = requesthandler.ServerCompilerSettings()
mock_settings.__compiler_dir__ = test_compiler_dir
BlocklyRequestHandler.ServerCompilerSettings().launch_IDE_only = True
requesthandler.ServerCompilerSettings().launch_IDE_only = True
# Build expected string and run test
expected_command = test_compiler_dir + ' "' + test_sketch_path + '"'
BlocklyRequestHandler.load_sketch()
mock_os.system.assert_called_with(expected_command)
requesthandler.load_arduino_cli()
#mock_popen.system.assert_called_with(expected_command)
#
# Tests for checking browsing for paths and files
#
@mock.patch('ArdublocklyServer.BlocklyRequestHandler.tkFileDialog')
@mock.patch('ardublocklyserver.requesthandler.tkFileDialog')
def test_browse_file(self, mock_file_select):
test_file = 'test_file'
mock_file_select.askopenfilename.return_value = test_file
new_file = BlocklyRequestHandler.browse_file()
new_file = requesthandler.browse_file()
self.assertEqual(new_file, test_file)
def test_browse_file_cancel(self):
......@@ -60,14 +63,14 @@ class BlocklyRequestHandlerTestCase(unittest.TestCase):
print('A file browser window will open, to successfully run this test '
'press cancel or close the window!!!\n')
#raw_input('Press "Enter" to continue...')
function_file = BlocklyRequestHandler.browse_file()
function_file = requesthandler.browse_file()
self.assertEqual(canceled_file, function_file)
@mock.patch('ArdublocklyServer.BlocklyRequestHandler.tkFileDialog')
@mock.patch('ardublocklyserver.requesthandler.tkFileDialog')
def test_browse_path(self, mock_path_select):
test_path = 'test_path'
mock_path_select.askopenfilename.return_value = test_path
new_path = BlocklyRequestHandler.browse_file()
new_path = requesthandler.browse_file()
self.assertEqual(new_path, test_path)
def test_browse_path_cancel(self):
......@@ -75,7 +78,7 @@ class BlocklyRequestHandlerTestCase(unittest.TestCase):
print('A path browser window will open, to successfully run this test '
'press cancel or close the window!!!\n')
#raw_input('Press "Enter" to continue...')
function_path = BlocklyRequestHandler.browse_dir()
function_path = requesthandler.browse_dir()
self.assertEqual(canceled_path, function_path)
......
# -*- coding: utf-8 -*-
#
# Unit test for the sketchcreator module.
#
# Copyright (c) 2015 carlosperate https://github.com/carlosperate/
# Licensed under the Apache License, Version 2.0 (the "License"):
# http://www.apache.org/licenses/LICENSE-2.0
#
from __future__ import unicode_literals, absolute_import
import os
import time
import unittest
try:
from ArdublocklyServer.SketchCreator import SketchCreator
from ArdublocklyServer.ServerCompilerSettings import ServerCompilerSettings
except ImportError:
import sys
file_dir = os.path.dirname(os.path.realpath(__file__))
package_dir = os.path.dirname(os.path.dirname(file_dir))
sys.path.insert(0, package_dir)
from ArdublocklyServer.SketchCreator import SketchCreator
from ArdublocklyServer.ServerCompilerSettings import ServerCompilerSettings
from ardublocklyserver.sketchcreator import SketchCreator
from ardublocklyserver.compilersettings import ServerCompilerSettings
class SketchCreatorTestCase(unittest.TestCase):
......@@ -21,7 +23,7 @@ class SketchCreatorTestCase(unittest.TestCase):
#
# File creation
#
def test_create_directory(self):
def test_create_sketch(self):
""" Tests to see if an Arduino Sketch is created in a new location """
test_sketch_name = 'TestTemp_Sketch'
ServerCompilerSettings().sketch_dir = os.getcwd()
......@@ -29,25 +31,26 @@ class SketchCreatorTestCase(unittest.TestCase):
test_path = os.path.join(os.getcwd(),
test_sketch_name,
test_sketch_name + '.ino')
# It should be save to create and delete in test folder
if os.path.exists(test_path):
os.remove(test_path)
print('\ntest_createDirectory() message:')
print("Check location: " + test_path)
self.assertFalse(os.path.isfile(test_path))
sketch_creator = SketchCreator()
instance_1 = SketchCreator()
created_sketch_path = instance_1.create_sketch()
# Checks the file is saved, and saved to the right location
created_sketch_path = sketch_creator.create_sketch()
self.assertEqual(test_path, created_sketch_path)
self.assertTrue(os.path.isfile(test_path))
#
# File creation with code
#
def test_create_sketch_with_code(self):
sketch_code_write = 'This is a test'
instance_1 = SketchCreator()
sketch_location = instance_1.create_sketch(sketch_code_write)
print('\ntest_create_sketch_with_code() message:')
print("Check location: " + sketch_location)
sketch_code_write = 'Test on: %s' % time.strftime("%Y-%m-%d %H:%M:%S")
sketch_creator = SketchCreator()
sketch_location = sketch_creator.create_sketch(sketch_code_write)
arduino_sketch = open(sketch_location, 'r')
sketch_code_read = arduino_sketch.read()
......
#!/usr/bin/env python2
# #############################################################################
# The comment above works if the Python Launcher for Windows path included
# in Python>3.3 does not conflict with the py.exe file added to "C:\Windows"
# Currently this application should work in Python >2.6 and 3.x, although
# python 2 is preferred, as it is the main development platform.
###############################################################################
# -*- coding: utf-8 -*-
#
# Entry point for the ArdublocklyServer application.
#
# Copyright (c) 2015 carlosperate https://github.com/carlosperate/
# Licensed under the Apache License, Version 2.0 (the "License"):
# http://www.apache.org/licenses/LICENSE-2.0
#
from __future__ import unicode_literals, absolute_import
import os
import re
......@@ -13,8 +15,9 @@ import getopt
import platform
import threading
import webbrowser
import ArdublocklyServer.BlocklyHTTPServer
import ArdublocklyServer.ServerCompilerSettings
import ardublocklyserver.server
import ardublocklyserver.compilersettings
def open_browser(open_file):
......@@ -23,7 +26,7 @@ def open_browser(open_file):
"""
def _open_browser():
webbrowser.open('http://localhost:%s/%s' %
(ArdublocklyServer.BlocklyHTTPServer.PORT, open_file))
(ardublocklyserver.server.PORT, open_file))
thread = threading.Timer(0.5, _open_browser)
thread.start()
......@@ -86,7 +89,7 @@ def main(argv):
# Loading the settings
print("\n======= Loading Settings =======")
ArdublocklyServer.ServerCompilerSettings.ServerCompilerSettings()
ardublocklyserver.compilersettings.ServerCompilerSettings()
# Loading the server with the argument working root directory, or by default
# with the parent folder of where this script is executed, done to be able
......@@ -113,7 +116,7 @@ def main(argv):
#print('Root & script parent: %s\nCommon & relative path: %s; %s\nIndex: %s'
# % (paths, common_path, relative_path, app_index))
open_browser(app_index)
ArdublocklyServer.BlocklyHTTPServer.start_server(server_root)
ardublocklyserver.server.start_server(server_root)
if __name__ == "__main__":
......
Markdown is supported
0%
or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment