Commit 0b8ce08d authored by carlosperate's avatar carlosperate

Convert server SketchCreator class into a simple Python module

parent af716146
......@@ -2,11 +2,11 @@
#
# Collection of actions to the ardublocklyserver for relieved HTTP requests.
#
# Copyright (c) 2015 carlosperate https://github.com/carlosperate/
# Copyright (c) 2017 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
from __future__ import unicode_literals, absolute_import, print_function
import subprocess
import locale
import time
......@@ -25,7 +25,7 @@ except ImportError:
import tkinter.filedialog as tkFileDialog
from ardublocklyserver.compilersettings import ServerCompilerSettings
from ardublocklyserver.sketchcreator import SketchCreator
from ardublocklyserver import sketchcreator
import ardublocklyserver.six.six.moves as six_moves
from ardublocklyserver.six import six
import ardublocklyserver.gui as gui
......@@ -145,15 +145,15 @@ def load_arduino_cli(sketch_path=None):
def create_sketch_default():
settings = ServerCompilerSettings()
return SketchCreator().create_sketch(
settings.sketch_dir, sketch_name=settings.sketch_name)
return sketchcreator.create_sketch(
sketch_dir=settings.sketch_dir, sketch_name=settings.sketch_name)
def create_sketch_from_string(sketch_code):
settings = ServerCompilerSettings()
return SketchCreator().create_sketch(
settings.sketch_dir, sketch_name=settings.sketch_name,
sketch_code=sketch_code)
return sketchcreator.create_sketch(
sketch_dir=settings.sketch_dir, sketch_name=settings.sketch_name,
sketch_code=sketch_code)
#
......
......@@ -2,100 +2,84 @@
#
# SketchCreator class creates an Arduino Sketch source code file.
#
# Copyright (c) 2015 carlosperate https://github.com/carlosperate/
# Copyright (c) 2017 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
from __future__ import unicode_literals, absolute_import, print_function
import codecs
import os
from ardublocklyserver.six import six
# Default blinky sketch
default_sketch_code = """int led = 13;
void setup() {
pinMode(led, OUTPUT);
}
void loop() {
digitalWrite(led, HIGH);
delay(1000);
digitalWrite(led, LOW);
delay(1000);
}
"""
class SketchCreator(object):
"""
Creates an Arduino Sketch.
"""
# Default sketch name
default_sketch_name = 'ArdublocklySketch'
#
# Metaclass methods
#
def __init__(self, sketch_name=None):
# Default sketch, blink builtin LED
self._default_sketch_code = \
'int led = 13;\n' \
'void setup() {\n' \
' pinMode(led, OUTPUT);\n' \
'}\n' \
'void loop() {\n' \
' digitalWrite(led, HIGH);\n' \
' delay(1000);\n' \
' digitalWrite(led, LOW);\n' \
' delay(1000);\n' \
'}\n'
# Default sketch name
self._default_sketch_name = 'ArdublocklySketch'
#
# Creating files
#
def create_sketch(self, sketch_dir, sketch_name=None, sketch_code=None):
"""
Creates the Arduino sketch with either the default blinky code or the
code defined in the input parameter.
:param sketch_dir: Location for the sketch.
:param sketch_name: Optional name for the sketch.
:param sketch_code: Optional 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.
"""
# Check the code first, to not create sketch file if invalid
if sketch_code is None:
code_to_write = self._default_sketch_code
else:
if isinstance(sketch_code, six.string_types):
code_to_write = sketch_code
else:
print('The sketch code given is not a valid string !!!')
return None
def create_sketch(sketch_dir, sketch_name=None, sketch_code=None):
"""Create an Arduino Sketch file into the given directory.
# Check validity and create the sketch path
if sketch_name is None:
sketch_name = self._default_sketch_name
sketch_path = self.build_sketch_path(sketch_dir, sketch_name)
if sketch_path is None:
return None
Creates an Arduino sketch with either the default blinky code or the
code defined in the input parameter.
try:
arduino_sketch = codecs.open(sketch_path, 'wb+', encoding='utf-8')
try:
arduino_sketch.write(code_to_write)
finally:
arduino_sketch.close()
except Exception as e:
print(e)
print('Arduino sketch could not be created !!!')
:param sketch_dir: Location for the sketch.
:param sketch_name: Optional name for the sketch.
:param sketch_code: Optional 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.
"""
# Check the code first, to not create sketch file if invalid
if sketch_code is None:
code_to_write = default_sketch_code
else:
if isinstance(sketch_code, six.string_types):
code_to_write = sketch_code
else:
print('The sketch code given is not a valid string !!!')
return None
# Check validity and create the sketch path
if sketch_name is None:
sketch_name = default_sketch_name
sketch_path = build_sketch_path(sketch_dir, sketch_name)
try:
with codecs.open(sketch_path, 'wb+', encoding='utf-8') as sketch_f:
sketch_f.write(code_to_write)
except Exception as e:
print(e)
print('Arduino sketch could not be created !!!')
return None
return sketch_path
return sketch_path
@staticmethod
def build_sketch_path(sketch_dir, sketch_name):
"""
If a valid directory is provided, it creates the Arduino sketch folder
(if it does not exists already) and returns a string pointing to the
sketch file path.
:return: unicode string with full path to the sketch file.
Returns None indicates an error has occurred.
"""
sketch_path = None
if os.path.isdir(sketch_dir):
sketch_path = os.path.join(sketch_dir, sketch_name)
if not os.path.exists(sketch_path):
os.makedirs(sketch_path)
sketch_path = os.path.join(sketch_path, sketch_name + '.ino')
else:
print('The sketch directory "%s" does not exists !!!' % sketch_dir)
return sketch_path
def build_sketch_path(sketch_dir, sketch_name):
"""Create the Arduino Sketch folder required for a valid Sketch.
If a valid directory is provided, it creates the Arduino sketch folder
(if it does not exists already) and returns a string pointing to the
sketch file path.
:return: unicode string with full path to the sketch file.
Return None indicates an error has occurred.
"""
sketch_path = None
if os.path.isdir(sketch_dir):
sketch_path = os.path.join(sketch_dir, sketch_name)
if not os.path.exists(sketch_path):
os.makedirs(sketch_path)
sketch_path = os.path.join(sketch_path, sketch_name + '.ino')
else:
print('The sketch directory "%s" does not exists !!!' % sketch_dir)
return sketch_path
......@@ -14,14 +14,14 @@ import shutil
import unittest
try:
from ardublocklyserver.sketchcreator import SketchCreator
from ardublocklyserver import sketchcreator
from ardublocklyserver.compilersettings 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 import sketchcreator
from ardublocklyserver.compilersettings import ServerCompilerSettings
......@@ -36,18 +36,17 @@ class SketchCreatorTestCase(unittest.TestCase):
def test_create_sketch(self):
""" Tests to see if an Arduino Sketch is created in a new location. """
# First test with the default name
sketch_creator = SketchCreator()
sketch_dir = os.getcwd()
final_ino_path = os.path.join(
sketch_dir,
sketch_creator._default_sketch_name,
'%s.ino' % sketch_creator._default_sketch_name)
# It should be save to create and delete the ino file in the test folder
sketchcreator.default_sketch_name,
'%s.ino' % sketchcreator.default_sketch_name)
# Should be safe to create and delete the ino file in the test folder
if os.path.exists(final_ino_path):
os.remove(final_ino_path)
self.assertFalse(os.path.isfile(final_ino_path))
# Checks the file is saved, and saved to the right location
created_sketch_path = sketch_creator.create_sketch(sketch_dir)
created_sketch_path = sketchcreator.create_sketch(sketch_dir)
self.assertEqual(final_ino_path, created_sketch_path)
self.assertTrue(os.path.isfile(final_ino_path))
......@@ -70,7 +69,7 @@ class SketchCreatorTestCase(unittest.TestCase):
self.assertFalse(os.path.isfile(final_ino_path))
# Checks the file is saved, and saved to the right location
created_sketch_path = sketch_creator.create_sketch(
created_sketch_path = sketchcreator.create_sketch(
sketch_dir_unicode, sketch_name=sketch_name)
self.assertEqual(final_ino_path, created_sketch_path)
self.assertTrue(os.path.isfile(final_ino_path))
......@@ -85,20 +84,19 @@ class SketchCreatorTestCase(unittest.TestCase):
# Test for failure on invalid sketch path
random_invalid_path = os.path.join(os.getcwd(), 'raNd_dIr')
self.assertFalse(os.path.isdir(random_invalid_path))
sketch_creator = SketchCreator()
created_sketch_path = sketch_creator.create_sketch(random_invalid_path)
created_sketch_path = sketchcreator.create_sketch(random_invalid_path)
self.assertIsNone(created_sketch_path)
self.assertFalse(os.path.isdir(random_invalid_path))
# Test for failure on invalid sketch code
sketch_path = os.getcwd()
sketch_folder_path = os.path.join(
sketch_path, sketch_creator._default_sketch_name)
sketch_path, sketchcreator.default_sketch_name)
if os.path.isdir(sketch_folder_path):
shutil.rmtree(sketch_folder_path)
self.assertFalse(os.path.isdir(sketch_folder_path))
invalid_sketch_code = True
created_sketch_path = sketch_creator.create_sketch(
created_sketch_path = sketchcreator.create_sketch(
sketch_path, sketch_code=invalid_sketch_code)
self.assertIsNone(created_sketch_path)
self.assertFalse(os.path.isdir(sketch_folder_path))
......@@ -107,16 +105,15 @@ class SketchCreatorTestCase(unittest.TestCase):
# File creation with code
#
def test_create_sketch_with_code(self):
sketch_creator = SketchCreator()
sketch_dir = os.getcwd()
sketch_ino_location = os.path.join(
sketch_dir,
sketch_creator._default_sketch_name,
'%s.ino' % sketch_creator._default_sketch_name)
sketchcreator.default_sketch_name,
'%s.ino' % sketchcreator.default_sketch_name)
sketch_code_write = 'Unicode test (ろΓαζςÂaé) on: %s' % \
time.strftime("%Y-%m-%d %H:%M:%S")
sketch_return_location = sketch_creator.create_sketch(
sketch_return_location = sketchcreator.create_sketch(
sketch_dir, sketch_code=sketch_code_write)
self.assertEqual(sketch_return_location, sketch_ino_location)
......
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